prompt
stringlengths
174
59.5k
completion
stringlengths
7
228
api
stringlengths
12
64
""" Friction-slip model formulated as the implicit complementarity problem. To integrate over a (dual) mesh, one needs: * coordinates of element vertices * element connectivity * local base for each element * constant in each sub-triangle of the dual mesh Data for each dual element: * connectivity of its sub-triangles * base directions t_1, t_2 Normal stresses: * Assemble the rezidual and apply the LCBC operator described below. Solution in \hat{V}_h^c: * construct a restriction operator via LCBC just like in the no-penetration case * use the substitution: u_1 = n_1 * w u_2 = n_2 * w u_3 = n_3 * w The new DOF is `w`. * for the record, no-penetration does: w_1 = - (1 / n_1) * (u_2 * n_2 + u_3 * n_3) w_2 = u_2 w_3 = u_3 """ from sfepy.base.base import * from sfepy.base.compat import unique import sfepy.linalg as la from sfepy.fem import Mesh, Domain, Field, Variables from sfepy.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.fem.fe_surface import FESurface from sfepy.fem.utils import compute_nodal_normals def edge_data_to_output(coors, conn, e_sort, data): out = nm.zeros_like(coors) out[conn[e_sort,0]] = data return Struct(name='output_data', mode='vertex', data=out, dofs=None) class DualMesh(Struct): """Dual mesh corresponding to a (surface) region.""" def __init__(self, region): """ Assume a single GeometryElement type in all groups, linear approximation. Works for one group only for the moment. """ domain = region.domain self.dim = domain.shape.dim self.region = copy(region) self.region.setup_face_indices() self.mesh_coors = domain.mesh.coors # add_to_regions=True due to Field implementation shortcomings. omega = domain.create_region('Omega', 'all', add_to_regions=True) self.field = Field('displacements', nm.float64, (3,), omega, 1) self.gel = domain.geom_els.values()[0] self.sgel = self.gel.surface_facet face_key = 's%d' % self.sgel.n_vertex # Coordinate interpolation to face centres. self.ps = self.gel.interp.poly_spaces[face_key] centre = self.ps.node_coors.sum(axis=0) / self.ps.n_nod self.bf = self.ps.eval_base(centre[None,:]) self.surfaces = surfaces = {} self.dual_surfaces = dual_surfaces = {} for ig, conn in enumerate(domain.mesh.conns): surface = FESurface(None, self.region, self.gel.faces, conn, ig) surfaces[ig] = surface dual_surface = self.describe_dual_surface(surface) dual_surfaces[ig] = dual_surface def describe_dual_surface(self, surface): n_fa, n_edge = surface.n_fa, self.sgel.n_edge mesh_coors = self.mesh_coors # Face centres. fcoors = mesh_coors[surface.econn] centre_coors = nm.dot(self.bf.squeeze(), fcoors) surface_coors = mesh_coors[surface.nodes] dual_coors = nm.r_[surface_coors, centre_coors] coor_offset = surface.nodes.shape[0] # Normals in primary mesh nodes. nodal_normals = compute_nodal_normals(surface.nodes, self.region, self.field) ee = surface.leconn[:,self.sgel.edges].copy() edges_per_face = ee.copy() sh = edges_per_face.shape ee.shape = edges_per_face.shape = (sh[0] * sh[1], sh[2]) edges_per_face.sort(axis=1) eo = nm.empty((sh[0] * sh[1],), dtype=nm.object) eo[:] = [tuple(ii) for ii in edges_per_face] ueo, e_sort, e_id = unique(eo, return_index=True, return_inverse=True) ueo = edges_per_face[e_sort] # edge centre, edge point 1, face centre, edge point 2 conn = nm.empty((n_edge * n_fa, 4), dtype=nm.int32) conn[:,0] = e_id conn[:,1] = ee[:,0] conn[:,2] = nm.repeat(nm.arange(n_fa, dtype=nm.int32), n_edge) \ + coor_offset conn[:,3] = ee[:,1] # face centre, edge point 2, edge point 1 tri_conn = nm.ascontiguousarray(conn[:,[2,1,3]]) # Ensure orientation - outward normal. cc = dual_coors[tri_conn] v1 = cc[:,1] - cc[:,0] v2 = cc[:,2] - cc[:,0] normals = nm.cross(v1, v2) nn = nodal_normals[surface.leconn].sum(axis=1).repeat(n_edge, 0) centre_normals = (1.0 / surface.n_fp) * nn centre_normals /= la.norm_l2_along_axis(centre_normals)[:,None] dot = nm.sum(normals * centre_normals, axis=1) assert_((dot > 0.0).all()) # Prepare mapping from reference triangle e_R to a # triangle within reference face e_D. gel = self.gel.surface_facet ref_coors = gel.coors ref_centre = nm.dot(self.bf.squeeze(), ref_coors) cc = nm.r_[ref_coors, ref_centre[None,:]] rconn = nm.empty((n_edge, 3), dtype=nm.int32) rconn[:,0] = gel.n_vertex rconn[:,1] = gel.edges[:,0] rconn[:,2] = gel.edges[:,1] map_er_ed =
VolumeMapping(cc, rconn, gel=gel)
sfepy.fem.mappings.VolumeMapping
""" Friction-slip model formulated as the implicit complementarity problem. To integrate over a (dual) mesh, one needs: * coordinates of element vertices * element connectivity * local base for each element * constant in each sub-triangle of the dual mesh Data for each dual element: * connectivity of its sub-triangles * base directions t_1, t_2 Normal stresses: * Assemble the rezidual and apply the LCBC operator described below. Solution in \hat{V}_h^c: * construct a restriction operator via LCBC just like in the no-penetration case * use the substitution: u_1 = n_1 * w u_2 = n_2 * w u_3 = n_3 * w The new DOF is `w`. * for the record, no-penetration does: w_1 = - (1 / n_1) * (u_2 * n_2 + u_3 * n_3) w_2 = u_2 w_3 = u_3 """ from sfepy.base.base import * from sfepy.base.compat import unique import sfepy.linalg as la from sfepy.fem import Mesh, Domain, Field, Variables from sfepy.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.fem.fe_surface import FESurface from sfepy.fem.utils import compute_nodal_normals def edge_data_to_output(coors, conn, e_sort, data): out = nm.zeros_like(coors) out[conn[e_sort,0]] = data return Struct(name='output_data', mode='vertex', data=out, dofs=None) class DualMesh(Struct): """Dual mesh corresponding to a (surface) region.""" def __init__(self, region): """ Assume a single GeometryElement type in all groups, linear approximation. Works for one group only for the moment. """ domain = region.domain self.dim = domain.shape.dim self.region = copy(region) self.region.setup_face_indices() self.mesh_coors = domain.mesh.coors # add_to_regions=True due to Field implementation shortcomings. omega = domain.create_region('Omega', 'all', add_to_regions=True) self.field = Field('displacements', nm.float64, (3,), omega, 1) self.gel = domain.geom_els.values()[0] self.sgel = self.gel.surface_facet face_key = 's%d' % self.sgel.n_vertex # Coordinate interpolation to face centres. self.ps = self.gel.interp.poly_spaces[face_key] centre = self.ps.node_coors.sum(axis=0) / self.ps.n_nod self.bf = self.ps.eval_base(centre[None,:]) self.surfaces = surfaces = {} self.dual_surfaces = dual_surfaces = {} for ig, conn in enumerate(domain.mesh.conns): surface = FESurface(None, self.region, self.gel.faces, conn, ig) surfaces[ig] = surface dual_surface = self.describe_dual_surface(surface) dual_surfaces[ig] = dual_surface def describe_dual_surface(self, surface): n_fa, n_edge = surface.n_fa, self.sgel.n_edge mesh_coors = self.mesh_coors # Face centres. fcoors = mesh_coors[surface.econn] centre_coors = nm.dot(self.bf.squeeze(), fcoors) surface_coors = mesh_coors[surface.nodes] dual_coors = nm.r_[surface_coors, centre_coors] coor_offset = surface.nodes.shape[0] # Normals in primary mesh nodes. nodal_normals = compute_nodal_normals(surface.nodes, self.region, self.field) ee = surface.leconn[:,self.sgel.edges].copy() edges_per_face = ee.copy() sh = edges_per_face.shape ee.shape = edges_per_face.shape = (sh[0] * sh[1], sh[2]) edges_per_face.sort(axis=1) eo = nm.empty((sh[0] * sh[1],), dtype=nm.object) eo[:] = [tuple(ii) for ii in edges_per_face] ueo, e_sort, e_id = unique(eo, return_index=True, return_inverse=True) ueo = edges_per_face[e_sort] # edge centre, edge point 1, face centre, edge point 2 conn = nm.empty((n_edge * n_fa, 4), dtype=nm.int32) conn[:,0] = e_id conn[:,1] = ee[:,0] conn[:,2] = nm.repeat(nm.arange(n_fa, dtype=nm.int32), n_edge) \ + coor_offset conn[:,3] = ee[:,1] # face centre, edge point 2, edge point 1 tri_conn = nm.ascontiguousarray(conn[:,[2,1,3]]) # Ensure orientation - outward normal. cc = dual_coors[tri_conn] v1 = cc[:,1] - cc[:,0] v2 = cc[:,2] - cc[:,0] normals = nm.cross(v1, v2) nn = nodal_normals[surface.leconn].sum(axis=1).repeat(n_edge, 0) centre_normals = (1.0 / surface.n_fp) * nn centre_normals /= la.norm_l2_along_axis(centre_normals)[:,None] dot = nm.sum(normals * centre_normals, axis=1) assert_((dot > 0.0).all()) # Prepare mapping from reference triangle e_R to a # triangle within reference face e_D. gel = self.gel.surface_facet ref_coors = gel.coors ref_centre = nm.dot(self.bf.squeeze(), ref_coors) cc = nm.r_[ref_coors, ref_centre[None,:]] rconn = nm.empty((n_edge, 3), dtype=nm.int32) rconn[:,0] = gel.n_vertex rconn[:,1] = gel.edges[:,0] rconn[:,2] = gel.edges[:,1] map_er_ed = VolumeMapping(cc, rconn, gel=gel) # Prepare mapping from reference triangle e_R to a # physical triangle e. map_er_e =
SurfaceMapping(dual_coors, tri_conn, gel=gel)
sfepy.fem.mappings.SurfaceMapping
""" Friction-slip model formulated as the implicit complementarity problem. To integrate over a (dual) mesh, one needs: * coordinates of element vertices * element connectivity * local base for each element * constant in each sub-triangle of the dual mesh Data for each dual element: * connectivity of its sub-triangles * base directions t_1, t_2 Normal stresses: * Assemble the rezidual and apply the LCBC operator described below. Solution in \hat{V}_h^c: * construct a restriction operator via LCBC just like in the no-penetration case * use the substitution: u_1 = n_1 * w u_2 = n_2 * w u_3 = n_3 * w The new DOF is `w`. * for the record, no-penetration does: w_1 = - (1 / n_1) * (u_2 * n_2 + u_3 * n_3) w_2 = u_2 w_3 = u_3 """ from sfepy.base.base import * from sfepy.base.compat import unique import sfepy.linalg as la from sfepy.fem import Mesh, Domain, Field, Variables from sfepy.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.fem.fe_surface import FESurface from sfepy.fem.utils import compute_nodal_normals def edge_data_to_output(coors, conn, e_sort, data): out = nm.zeros_like(coors) out[conn[e_sort,0]] = data return Struct(name='output_data', mode='vertex', data=out, dofs=None) class DualMesh(Struct): """Dual mesh corresponding to a (surface) region.""" def __init__(self, region): """ Assume a single GeometryElement type in all groups, linear approximation. Works for one group only for the moment. """ domain = region.domain self.dim = domain.shape.dim self.region = copy(region) self.region.setup_face_indices() self.mesh_coors = domain.mesh.coors # add_to_regions=True due to Field implementation shortcomings. omega = domain.create_region('Omega', 'all', add_to_regions=True) self.field = Field('displacements', nm.float64, (3,), omega, 1) self.gel = domain.geom_els.values()[0] self.sgel = self.gel.surface_facet face_key = 's%d' % self.sgel.n_vertex # Coordinate interpolation to face centres. self.ps = self.gel.interp.poly_spaces[face_key] centre = self.ps.node_coors.sum(axis=0) / self.ps.n_nod self.bf = self.ps.eval_base(centre[None,:]) self.surfaces = surfaces = {} self.dual_surfaces = dual_surfaces = {} for ig, conn in enumerate(domain.mesh.conns): surface =
FESurface(None, self.region, self.gel.faces, conn, ig)
sfepy.fem.fe_surface.FESurface
""" Friction-slip model formulated as the implicit complementarity problem. To integrate over a (dual) mesh, one needs: * coordinates of element vertices * element connectivity * local base for each element * constant in each sub-triangle of the dual mesh Data for each dual element: * connectivity of its sub-triangles * base directions t_1, t_2 Normal stresses: * Assemble the rezidual and apply the LCBC operator described below. Solution in \hat{V}_h^c: * construct a restriction operator via LCBC just like in the no-penetration case * use the substitution: u_1 = n_1 * w u_2 = n_2 * w u_3 = n_3 * w The new DOF is `w`. * for the record, no-penetration does: w_1 = - (1 / n_1) * (u_2 * n_2 + u_3 * n_3) w_2 = u_2 w_3 = u_3 """ from sfepy.base.base import * from sfepy.base.compat import unique import sfepy.linalg as la from sfepy.fem import Mesh, Domain, Field, Variables from sfepy.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.fem.fe_surface import FESurface from sfepy.fem.utils import compute_nodal_normals def edge_data_to_output(coors, conn, e_sort, data): out = nm.zeros_like(coors) out[conn[e_sort,0]] = data return Struct(name='output_data', mode='vertex', data=out, dofs=None) class DualMesh(Struct): """Dual mesh corresponding to a (surface) region.""" def __init__(self, region): """ Assume a single GeometryElement type in all groups, linear approximation. Works for one group only for the moment. """ domain = region.domain self.dim = domain.shape.dim self.region = copy(region) self.region.setup_face_indices() self.mesh_coors = domain.mesh.coors # add_to_regions=True due to Field implementation shortcomings. omega = domain.create_region('Omega', 'all', add_to_regions=True) self.field = Field('displacements', nm.float64, (3,), omega, 1) self.gel = domain.geom_els.values()[0] self.sgel = self.gel.surface_facet face_key = 's%d' % self.sgel.n_vertex # Coordinate interpolation to face centres. self.ps = self.gel.interp.poly_spaces[face_key] centre = self.ps.node_coors.sum(axis=0) / self.ps.n_nod self.bf = self.ps.eval_base(centre[None,:]) self.surfaces = surfaces = {} self.dual_surfaces = dual_surfaces = {} for ig, conn in enumerate(domain.mesh.conns): surface = FESurface(None, self.region, self.gel.faces, conn, ig) surfaces[ig] = surface dual_surface = self.describe_dual_surface(surface) dual_surfaces[ig] = dual_surface def describe_dual_surface(self, surface): n_fa, n_edge = surface.n_fa, self.sgel.n_edge mesh_coors = self.mesh_coors # Face centres. fcoors = mesh_coors[surface.econn] centre_coors = nm.dot(self.bf.squeeze(), fcoors) surface_coors = mesh_coors[surface.nodes] dual_coors = nm.r_[surface_coors, centre_coors] coor_offset = surface.nodes.shape[0] # Normals in primary mesh nodes. nodal_normals = compute_nodal_normals(surface.nodes, self.region, self.field) ee = surface.leconn[:,self.sgel.edges].copy() edges_per_face = ee.copy() sh = edges_per_face.shape ee.shape = edges_per_face.shape = (sh[0] * sh[1], sh[2]) edges_per_face.sort(axis=1) eo = nm.empty((sh[0] * sh[1],), dtype=nm.object) eo[:] = [tuple(ii) for ii in edges_per_face] ueo, e_sort, e_id = unique(eo, return_index=True, return_inverse=True) ueo = edges_per_face[e_sort] # edge centre, edge point 1, face centre, edge point 2 conn = nm.empty((n_edge * n_fa, 4), dtype=nm.int32) conn[:,0] = e_id conn[:,1] = ee[:,0] conn[:,2] = nm.repeat(nm.arange(n_fa, dtype=nm.int32), n_edge) \ + coor_offset conn[:,3] = ee[:,1] # face centre, edge point 2, edge point 1 tri_conn = nm.ascontiguousarray(conn[:,[2,1,3]]) # Ensure orientation - outward normal. cc = dual_coors[tri_conn] v1 = cc[:,1] - cc[:,0] v2 = cc[:,2] - cc[:,0] normals = nm.cross(v1, v2) nn = nodal_normals[surface.leconn].sum(axis=1).repeat(n_edge, 0) centre_normals = (1.0 / surface.n_fp) * nn centre_normals /=
la.norm_l2_along_axis(centre_normals)
sfepy.linalg.norm_l2_along_axis
""" Friction-slip model formulated as the implicit complementarity problem. To integrate over a (dual) mesh, one needs: * coordinates of element vertices * element connectivity * local base for each element * constant in each sub-triangle of the dual mesh Data for each dual element: * connectivity of its sub-triangles * base directions t_1, t_2 Normal stresses: * Assemble the rezidual and apply the LCBC operator described below. Solution in \hat{V}_h^c: * construct a restriction operator via LCBC just like in the no-penetration case * use the substitution: u_1 = n_1 * w u_2 = n_2 * w u_3 = n_3 * w The new DOF is `w`. * for the record, no-penetration does: w_1 = - (1 / n_1) * (u_2 * n_2 + u_3 * n_3) w_2 = u_2 w_3 = u_3 """ from sfepy.base.base import * from sfepy.base.compat import unique import sfepy.linalg as la from sfepy.fem import Mesh, Domain, Field, Variables from sfepy.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.fem.fe_surface import FESurface from sfepy.fem.utils import compute_nodal_normals def edge_data_to_output(coors, conn, e_sort, data): out = nm.zeros_like(coors) out[conn[e_sort,0]] = data return Struct(name='output_data', mode='vertex', data=out, dofs=None) class DualMesh(Struct): """Dual mesh corresponding to a (surface) region.""" def __init__(self, region): """ Assume a single GeometryElement type in all groups, linear approximation. Works for one group only for the moment. """ domain = region.domain self.dim = domain.shape.dim self.region = copy(region) self.region.setup_face_indices() self.mesh_coors = domain.mesh.coors # add_to_regions=True due to Field implementation shortcomings. omega = domain.create_region('Omega', 'all', add_to_regions=True) self.field = Field('displacements', nm.float64, (3,), omega, 1) self.gel = domain.geom_els.values()[0] self.sgel = self.gel.surface_facet face_key = 's%d' % self.sgel.n_vertex # Coordinate interpolation to face centres. self.ps = self.gel.interp.poly_spaces[face_key] centre = self.ps.node_coors.sum(axis=0) / self.ps.n_nod self.bf = self.ps.eval_base(centre[None,:]) self.surfaces = surfaces = {} self.dual_surfaces = dual_surfaces = {} for ig, conn in enumerate(domain.mesh.conns): surface = FESurface(None, self.region, self.gel.faces, conn, ig) surfaces[ig] = surface dual_surface = self.describe_dual_surface(surface) dual_surfaces[ig] = dual_surface def describe_dual_surface(self, surface): n_fa, n_edge = surface.n_fa, self.sgel.n_edge mesh_coors = self.mesh_coors # Face centres. fcoors = mesh_coors[surface.econn] centre_coors = nm.dot(self.bf.squeeze(), fcoors) surface_coors = mesh_coors[surface.nodes] dual_coors = nm.r_[surface_coors, centre_coors] coor_offset = surface.nodes.shape[0] # Normals in primary mesh nodes. nodal_normals = compute_nodal_normals(surface.nodes, self.region, self.field) ee = surface.leconn[:,self.sgel.edges].copy() edges_per_face = ee.copy() sh = edges_per_face.shape ee.shape = edges_per_face.shape = (sh[0] * sh[1], sh[2]) edges_per_face.sort(axis=1) eo = nm.empty((sh[0] * sh[1],), dtype=nm.object) eo[:] = [tuple(ii) for ii in edges_per_face] ueo, e_sort, e_id = unique(eo, return_index=True, return_inverse=True) ueo = edges_per_face[e_sort] # edge centre, edge point 1, face centre, edge point 2 conn = nm.empty((n_edge * n_fa, 4), dtype=nm.int32) conn[:,0] = e_id conn[:,1] = ee[:,0] conn[:,2] = nm.repeat(nm.arange(n_fa, dtype=nm.int32), n_edge) \ + coor_offset conn[:,3] = ee[:,1] # face centre, edge point 2, edge point 1 tri_conn = nm.ascontiguousarray(conn[:,[2,1,3]]) # Ensure orientation - outward normal. cc = dual_coors[tri_conn] v1 = cc[:,1] - cc[:,0] v2 = cc[:,2] - cc[:,0] normals = nm.cross(v1, v2) nn = nodal_normals[surface.leconn].sum(axis=1).repeat(n_edge, 0) centre_normals = (1.0 / surface.n_fp) * nn centre_normals /= la.norm_l2_along_axis(centre_normals)[:,None] dot = nm.sum(normals * centre_normals, axis=1) assert_((dot > 0.0).all()) # Prepare mapping from reference triangle e_R to a # triangle within reference face e_D. gel = self.gel.surface_facet ref_coors = gel.coors ref_centre = nm.dot(self.bf.squeeze(), ref_coors) cc = nm.r_[ref_coors, ref_centre[None,:]] rconn = nm.empty((n_edge, 3), dtype=nm.int32) rconn[:,0] = gel.n_vertex rconn[:,1] = gel.edges[:,0] rconn[:,2] = gel.edges[:,1] map_er_ed = VolumeMapping(cc, rconn, gel=gel) # Prepare mapping from reference triangle e_R to a # physical triangle e. map_er_e = SurfaceMapping(dual_coors, tri_conn, gel=gel) # Compute triangle basis (edge) vectors. nn = surface.nodes[ueo] edge_coors = mesh_coors[nn] edge_centre_coors = 0.5 * edge_coors.sum(axis=1) edge_normals = 0.5 * nodal_normals[ueo].sum(axis=1) edge_normals /=
la.norm_l2_along_axis(edge_normals)
sfepy.linalg.norm_l2_along_axis
""" Friction-slip model formulated as the implicit complementarity problem. To integrate over a (dual) mesh, one needs: * coordinates of element vertices * element connectivity * local base for each element * constant in each sub-triangle of the dual mesh Data for each dual element: * connectivity of its sub-triangles * base directions t_1, t_2 Normal stresses: * Assemble the rezidual and apply the LCBC operator described below. Solution in \hat{V}_h^c: * construct a restriction operator via LCBC just like in the no-penetration case * use the substitution: u_1 = n_1 * w u_2 = n_2 * w u_3 = n_3 * w The new DOF is `w`. * for the record, no-penetration does: w_1 = - (1 / n_1) * (u_2 * n_2 + u_3 * n_3) w_2 = u_2 w_3 = u_3 """ from sfepy.base.base import * from sfepy.base.compat import unique import sfepy.linalg as la from sfepy.fem import Mesh, Domain, Field, Variables from sfepy.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.fem.fe_surface import FESurface from sfepy.fem.utils import compute_nodal_normals def edge_data_to_output(coors, conn, e_sort, data): out = nm.zeros_like(coors) out[conn[e_sort,0]] = data return Struct(name='output_data', mode='vertex', data=out, dofs=None) class DualMesh(Struct): """Dual mesh corresponding to a (surface) region.""" def __init__(self, region): """ Assume a single GeometryElement type in all groups, linear approximation. Works for one group only for the moment. """ domain = region.domain self.dim = domain.shape.dim self.region = copy(region) self.region.setup_face_indices() self.mesh_coors = domain.mesh.coors # add_to_regions=True due to Field implementation shortcomings. omega = domain.create_region('Omega', 'all', add_to_regions=True) self.field = Field('displacements', nm.float64, (3,), omega, 1) self.gel = domain.geom_els.values()[0] self.sgel = self.gel.surface_facet face_key = 's%d' % self.sgel.n_vertex # Coordinate interpolation to face centres. self.ps = self.gel.interp.poly_spaces[face_key] centre = self.ps.node_coors.sum(axis=0) / self.ps.n_nod self.bf = self.ps.eval_base(centre[None,:]) self.surfaces = surfaces = {} self.dual_surfaces = dual_surfaces = {} for ig, conn in enumerate(domain.mesh.conns): surface = FESurface(None, self.region, self.gel.faces, conn, ig) surfaces[ig] = surface dual_surface = self.describe_dual_surface(surface) dual_surfaces[ig] = dual_surface def describe_dual_surface(self, surface): n_fa, n_edge = surface.n_fa, self.sgel.n_edge mesh_coors = self.mesh_coors # Face centres. fcoors = mesh_coors[surface.econn] centre_coors = nm.dot(self.bf.squeeze(), fcoors) surface_coors = mesh_coors[surface.nodes] dual_coors = nm.r_[surface_coors, centre_coors] coor_offset = surface.nodes.shape[0] # Normals in primary mesh nodes. nodal_normals = compute_nodal_normals(surface.nodes, self.region, self.field) ee = surface.leconn[:,self.sgel.edges].copy() edges_per_face = ee.copy() sh = edges_per_face.shape ee.shape = edges_per_face.shape = (sh[0] * sh[1], sh[2]) edges_per_face.sort(axis=1) eo = nm.empty((sh[0] * sh[1],), dtype=nm.object) eo[:] = [tuple(ii) for ii in edges_per_face] ueo, e_sort, e_id = unique(eo, return_index=True, return_inverse=True) ueo = edges_per_face[e_sort] # edge centre, edge point 1, face centre, edge point 2 conn = nm.empty((n_edge * n_fa, 4), dtype=nm.int32) conn[:,0] = e_id conn[:,1] = ee[:,0] conn[:,2] = nm.repeat(nm.arange(n_fa, dtype=nm.int32), n_edge) \ + coor_offset conn[:,3] = ee[:,1] # face centre, edge point 2, edge point 1 tri_conn = nm.ascontiguousarray(conn[:,[2,1,3]]) # Ensure orientation - outward normal. cc = dual_coors[tri_conn] v1 = cc[:,1] - cc[:,0] v2 = cc[:,2] - cc[:,0] normals = nm.cross(v1, v2) nn = nodal_normals[surface.leconn].sum(axis=1).repeat(n_edge, 0) centre_normals = (1.0 / surface.n_fp) * nn centre_normals /= la.norm_l2_along_axis(centre_normals)[:,None] dot = nm.sum(normals * centre_normals, axis=1) assert_((dot > 0.0).all()) # Prepare mapping from reference triangle e_R to a # triangle within reference face e_D. gel = self.gel.surface_facet ref_coors = gel.coors ref_centre = nm.dot(self.bf.squeeze(), ref_coors) cc = nm.r_[ref_coors, ref_centre[None,:]] rconn = nm.empty((n_edge, 3), dtype=nm.int32) rconn[:,0] = gel.n_vertex rconn[:,1] = gel.edges[:,0] rconn[:,2] = gel.edges[:,1] map_er_ed = VolumeMapping(cc, rconn, gel=gel) # Prepare mapping from reference triangle e_R to a # physical triangle e. map_er_e = SurfaceMapping(dual_coors, tri_conn, gel=gel) # Compute triangle basis (edge) vectors. nn = surface.nodes[ueo] edge_coors = mesh_coors[nn] edge_centre_coors = 0.5 * edge_coors.sum(axis=1) edge_normals = 0.5 * nodal_normals[ueo].sum(axis=1) edge_normals /= la.norm_l2_along_axis(edge_normals)[:,None] nn = surface.nodes[ueo] edge_dirs = edge_coors[:,1] - edge_coors[:,0] edge_dirs /=
la.norm_l2_along_axis(edge_dirs)
sfepy.linalg.norm_l2_along_axis
""" Friction-slip model formulated as the implicit complementarity problem. To integrate over a (dual) mesh, one needs: * coordinates of element vertices * element connectivity * local base for each element * constant in each sub-triangle of the dual mesh Data for each dual element: * connectivity of its sub-triangles * base directions t_1, t_2 Normal stresses: * Assemble the rezidual and apply the LCBC operator described below. Solution in \hat{V}_h^c: * construct a restriction operator via LCBC just like in the no-penetration case * use the substitution: u_1 = n_1 * w u_2 = n_2 * w u_3 = n_3 * w The new DOF is `w`. * for the record, no-penetration does: w_1 = - (1 / n_1) * (u_2 * n_2 + u_3 * n_3) w_2 = u_2 w_3 = u_3 """ from sfepy.base.base import * from sfepy.base.compat import unique import sfepy.linalg as la from sfepy.fem import Mesh, Domain, Field, Variables from sfepy.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.fem.fe_surface import FESurface from sfepy.fem.utils import compute_nodal_normals def edge_data_to_output(coors, conn, e_sort, data): out = nm.zeros_like(coors) out[conn[e_sort,0]] = data return Struct(name='output_data', mode='vertex', data=out, dofs=None) class DualMesh(Struct): """Dual mesh corresponding to a (surface) region.""" def __init__(self, region): """ Assume a single GeometryElement type in all groups, linear approximation. Works for one group only for the moment. """ domain = region.domain self.dim = domain.shape.dim self.region = copy(region) self.region.setup_face_indices() self.mesh_coors = domain.mesh.coors # add_to_regions=True due to Field implementation shortcomings. omega = domain.create_region('Omega', 'all', add_to_regions=True) self.field = Field('displacements', nm.float64, (3,), omega, 1) self.gel = domain.geom_els.values()[0] self.sgel = self.gel.surface_facet face_key = 's%d' % self.sgel.n_vertex # Coordinate interpolation to face centres. self.ps = self.gel.interp.poly_spaces[face_key] centre = self.ps.node_coors.sum(axis=0) / self.ps.n_nod self.bf = self.ps.eval_base(centre[None,:]) self.surfaces = surfaces = {} self.dual_surfaces = dual_surfaces = {} for ig, conn in enumerate(domain.mesh.conns): surface = FESurface(None, self.region, self.gel.faces, conn, ig) surfaces[ig] = surface dual_surface = self.describe_dual_surface(surface) dual_surfaces[ig] = dual_surface def describe_dual_surface(self, surface): n_fa, n_edge = surface.n_fa, self.sgel.n_edge mesh_coors = self.mesh_coors # Face centres. fcoors = mesh_coors[surface.econn] centre_coors = nm.dot(self.bf.squeeze(), fcoors) surface_coors = mesh_coors[surface.nodes] dual_coors = nm.r_[surface_coors, centre_coors] coor_offset = surface.nodes.shape[0] # Normals in primary mesh nodes. nodal_normals = compute_nodal_normals(surface.nodes, self.region, self.field) ee = surface.leconn[:,self.sgel.edges].copy() edges_per_face = ee.copy() sh = edges_per_face.shape ee.shape = edges_per_face.shape = (sh[0] * sh[1], sh[2]) edges_per_face.sort(axis=1) eo = nm.empty((sh[0] * sh[1],), dtype=nm.object) eo[:] = [tuple(ii) for ii in edges_per_face] ueo, e_sort, e_id = unique(eo, return_index=True, return_inverse=True) ueo = edges_per_face[e_sort] # edge centre, edge point 1, face centre, edge point 2 conn = nm.empty((n_edge * n_fa, 4), dtype=nm.int32) conn[:,0] = e_id conn[:,1] = ee[:,0] conn[:,2] = nm.repeat(nm.arange(n_fa, dtype=nm.int32), n_edge) \ + coor_offset conn[:,3] = ee[:,1] # face centre, edge point 2, edge point 1 tri_conn = nm.ascontiguousarray(conn[:,[2,1,3]]) # Ensure orientation - outward normal. cc = dual_coors[tri_conn] v1 = cc[:,1] - cc[:,0] v2 = cc[:,2] - cc[:,0] normals = nm.cross(v1, v2) nn = nodal_normals[surface.leconn].sum(axis=1).repeat(n_edge, 0) centre_normals = (1.0 / surface.n_fp) * nn centre_normals /= la.norm_l2_along_axis(centre_normals)[:,None] dot = nm.sum(normals * centre_normals, axis=1) assert_((dot > 0.0).all()) # Prepare mapping from reference triangle e_R to a # triangle within reference face e_D. gel = self.gel.surface_facet ref_coors = gel.coors ref_centre = nm.dot(self.bf.squeeze(), ref_coors) cc = nm.r_[ref_coors, ref_centre[None,:]] rconn = nm.empty((n_edge, 3), dtype=nm.int32) rconn[:,0] = gel.n_vertex rconn[:,1] = gel.edges[:,0] rconn[:,2] = gel.edges[:,1] map_er_ed = VolumeMapping(cc, rconn, gel=gel) # Prepare mapping from reference triangle e_R to a # physical triangle e. map_er_e = SurfaceMapping(dual_coors, tri_conn, gel=gel) # Compute triangle basis (edge) vectors. nn = surface.nodes[ueo] edge_coors = mesh_coors[nn] edge_centre_coors = 0.5 * edge_coors.sum(axis=1) edge_normals = 0.5 * nodal_normals[ueo].sum(axis=1) edge_normals /= la.norm_l2_along_axis(edge_normals)[:,None] nn = surface.nodes[ueo] edge_dirs = edge_coors[:,1] - edge_coors[:,0] edge_dirs /= la.norm_l2_along_axis(edge_dirs)[:,None] edge_ortho = nm.cross(edge_normals, edge_dirs) edge_ortho /=
la.norm_l2_along_axis(edge_ortho)
sfepy.linalg.norm_l2_along_axis
# -*- coding: utf-8 -*- r""" Linear elasticity with given displacements. Find :math:`\ul{u}` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) = 0 \;, \quad \forall \ul{v} \;, where .. math:: D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) + \lambda \ \delta_{ij} \delta_{kl} \;. This example models a cylinder that is fixed at one end while the second end has a specified displacement of 0.01 in the x direction (this boundary condition is named ``'Displaced'``). There is also a specified displacement of 0.005 in the z direction for points in the region labeled ``'SomewhereTop'``. This boundary condition is named ``'PerturbedSurface'``. The region ``'SomewhereTop'`` is specified as those vertices for which:: (z > 0.017) & (x > 0.03) & (x < 0.07) The displacement field (three DOFs/node) in the ``'Omega region'`` is approximated using P1 (four-node tetrahedral) finite elements. The material is linear elastic and its properties are specified as Lamé parameters :math:`\lambda` and :math:`\mu` (see http://en.wikipedia.org/wiki/Lam%C3%A9_parameters) The output is the displacement for each vertex, saved by default to cylinder.vtk. View the results using:: $ ./postproc.py cylinder.vtk --wireframe -b --only-names=u -d'u,plot_displacements,rel_scaling=1' """ from sfepy import data_dir from sfepy.mechanics.matcoefs import stiffness_from_lame filename_mesh = data_dir + '/meshes/3d/cylinder.mesh' regions = { 'Omega' : 'all', 'Left' : ('vertices in (x < 0.001)', 'facet'), 'Right' : ('vertices in (x > 0.099)', 'facet'), 'SomewhereTop' : ('vertices in (z > 0.017) & (x > 0.03) & (x < 0.07)', 'vertex'), } materials = { 'solid' : ({'D':
stiffness_from_lame(dim=3, lam=1e1, mu=1e0)
sfepy.mechanics.matcoefs.stiffness_from_lame
import os import numpy as nm try: from enthought.tvtk.api import tvtk from enthought.mayavi.sources.vtk_data_source import VTKDataSource from enthought.pyface.timer.api import Timer except: from tvtk.api import tvtk from mayavi.sources.vtk_data_source import VTKDataSource from pyface.timer.api import Timer from dataset_manager import DatasetManager from sfepy.base.base import Struct, basestr from sfepy.postprocess.utils import mlab from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.meshio import MeshIO, vtk_cell_types, supported_formats def create_file_source(filename, watch=False, offscreen=True): """Factory function to create a file source corresponding to the given file format.""" kwargs = {'watch' : watch, 'offscreen' : offscreen} if isinstance(filename, basestr): fmt = os.path.splitext(filename)[1] is_sequence = False else: # A sequence. fmt = os.path.splitext(filename[0])[1] is_sequence = True fmt = fmt.lower() if fmt == '.vtk': # VTK is supported directly by Mayavi, no need to use MeshIO. if is_sequence: return VTKSequenceFileSource(filename, **kwargs) else: return VTKFileSource(filename, **kwargs) elif fmt in supported_formats.keys(): if is_sequence: if fmt == '.h5': raise ValueError('format .h5 does not support file sequences!') else: return GenericSequenceFileSource(filename, **kwargs) else: return GenericFileSource(filename, **kwargs) else: raise ValueError('unknown file format! (%s)' % fmt) class FileSource(Struct): """General file source.""" def __init__(self, filename, watch=False, offscreen=True): """Create a file source using the given file name.""" mlab.options.offscreen = offscreen self.watch = watch self.filename = filename self.reset() def __call__(self, step=0): """Get the file source.""" if self.source is None: self.source = self.create_source() if self.watch: self.timer = Timer(1000, self.poll_file) return self.source def reset(self): """Reset.""" self.mat_id_name = None self.source = None self.notify_obj = None self.steps = [] self.times = [] self.step = 0 self.time = 0.0 if self.watch: self.last_stat = os.stat(self.filename) def setup_mat_id(self, mat_id_name='mat_id', single_color=False): self.mat_id_name = mat_id_name self.single_color = single_color def get_step_time(self, step=None, time=None): """ Set current step and time to the values closest greater or equal to either step or time. Return the found values. """ if (step is not None) and len(self.steps): step = step if step >= 0 else self.steps[-1] + step + 1 ii = nm.searchsorted(self.steps, step) ii = nm.clip(ii, 0, len(self.steps) - 1) self.step = self.steps[ii] if len(self.times): self.time = self.times[ii] elif (time is not None) and len(self.times): ii = nm.searchsorted(self.times, time) ii = nm.clip(ii, 0, len(self.steps) - 1) self.step = self.steps[ii] self.time = self.times[ii] return self.step, self.time def get_ts_info(self): return self.steps, self.times def get_mat_id(self, mat_id_name='mat_id'): """ Get material ID numbers of the underlying mesh elements. """ if self.source is not None: dm = DatasetManager(dataset=self.source.outputs[0]) mat_id = dm.cell_scalars[mat_id_name] return mat_id def file_changed(self): pass def setup_notification(self, obj, attr): """The attribute 'attr' of the object 'obj' will be set to True when the source file is watched and changes.""" self.notify_obj = obj self.notify_attr = attr def poll_file(self): """Check the source file's time stamp and notify the self.notify_obj in case it changed. Subclasses should implement the file_changed() method.""" if not self.notify_obj: return s = os.stat(self.filename) if s[-2] == self.last_stat[-2]: setattr(self.notify_obj, self.notify_attr, False) else: self.file_changed() setattr(self.notify_obj, self.notify_attr, True) self.last_stat = s class VTKFileSource(FileSource): """A thin wrapper around mlab.pipeline.open().""" def create_source(self): """Create a VTK file source """ return
mlab.pipeline.open(self.filename)
sfepy.postprocess.utils.mlab.pipeline.open
import os import numpy as nm try: from enthought.tvtk.api import tvtk from enthought.mayavi.sources.vtk_data_source import VTKDataSource from enthought.pyface.timer.api import Timer except: from tvtk.api import tvtk from mayavi.sources.vtk_data_source import VTKDataSource from pyface.timer.api import Timer from dataset_manager import DatasetManager from sfepy.base.base import Struct, basestr from sfepy.postprocess.utils import mlab from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.meshio import MeshIO, vtk_cell_types, supported_formats def create_file_source(filename, watch=False, offscreen=True): """Factory function to create a file source corresponding to the given file format.""" kwargs = {'watch' : watch, 'offscreen' : offscreen} if isinstance(filename, basestr): fmt = os.path.splitext(filename)[1] is_sequence = False else: # A sequence. fmt = os.path.splitext(filename[0])[1] is_sequence = True fmt = fmt.lower() if fmt == '.vtk': # VTK is supported directly by Mayavi, no need to use MeshIO. if is_sequence: return VTKSequenceFileSource(filename, **kwargs) else: return VTKFileSource(filename, **kwargs) elif fmt in supported_formats.keys(): if is_sequence: if fmt == '.h5': raise ValueError('format .h5 does not support file sequences!') else: return GenericSequenceFileSource(filename, **kwargs) else: return GenericFileSource(filename, **kwargs) else: raise ValueError('unknown file format! (%s)' % fmt) class FileSource(Struct): """General file source.""" def __init__(self, filename, watch=False, offscreen=True): """Create a file source using the given file name.""" mlab.options.offscreen = offscreen self.watch = watch self.filename = filename self.reset() def __call__(self, step=0): """Get the file source.""" if self.source is None: self.source = self.create_source() if self.watch: self.timer = Timer(1000, self.poll_file) return self.source def reset(self): """Reset.""" self.mat_id_name = None self.source = None self.notify_obj = None self.steps = [] self.times = [] self.step = 0 self.time = 0.0 if self.watch: self.last_stat = os.stat(self.filename) def setup_mat_id(self, mat_id_name='mat_id', single_color=False): self.mat_id_name = mat_id_name self.single_color = single_color def get_step_time(self, step=None, time=None): """ Set current step and time to the values closest greater or equal to either step or time. Return the found values. """ if (step is not None) and len(self.steps): step = step if step >= 0 else self.steps[-1] + step + 1 ii = nm.searchsorted(self.steps, step) ii = nm.clip(ii, 0, len(self.steps) - 1) self.step = self.steps[ii] if len(self.times): self.time = self.times[ii] elif (time is not None) and len(self.times): ii = nm.searchsorted(self.times, time) ii = nm.clip(ii, 0, len(self.steps) - 1) self.step = self.steps[ii] self.time = self.times[ii] return self.step, self.time def get_ts_info(self): return self.steps, self.times def get_mat_id(self, mat_id_name='mat_id'): """ Get material ID numbers of the underlying mesh elements. """ if self.source is not None: dm = DatasetManager(dataset=self.source.outputs[0]) mat_id = dm.cell_scalars[mat_id_name] return mat_id def file_changed(self): pass def setup_notification(self, obj, attr): """The attribute 'attr' of the object 'obj' will be set to True when the source file is watched and changes.""" self.notify_obj = obj self.notify_attr = attr def poll_file(self): """Check the source file's time stamp and notify the self.notify_obj in case it changed. Subclasses should implement the file_changed() method.""" if not self.notify_obj: return s = os.stat(self.filename) if s[-2] == self.last_stat[-2]: setattr(self.notify_obj, self.notify_attr, False) else: self.file_changed() setattr(self.notify_obj, self.notify_attr, True) self.last_stat = s class VTKFileSource(FileSource): """A thin wrapper around mlab.pipeline.open().""" def create_source(self): """Create a VTK file source """ return mlab.pipeline.open(self.filename) def get_bounding_box(self): bbox = nm.array(self.source.reader.unstructured_grid_output.bounds) return bbox.reshape((3,2)).T def set_filename(self, filename, vis_source): self.filename = filename vis_source.base_file_name = filename # Force re-read. vis_source.reader.modified() vis_source.update() # Propagate changes in the pipeline. vis_source.data_changed = True class VTKSequenceFileSource(VTKFileSource): """A thin wrapper around mlab.pipeline.open() for VTK file sequences.""" def __init__(self, *args, **kwargs): FileSource.__init__(self, *args, **kwargs) self.steps = nm.arange(len(self.filename), dtype=nm.int32) def create_source(self): """Create a VTK file source """ return
mlab.pipeline.open(self.filename[0])
sfepy.postprocess.utils.mlab.pipeline.open
import os import numpy as nm try: from enthought.tvtk.api import tvtk from enthought.mayavi.sources.vtk_data_source import VTKDataSource from enthought.pyface.timer.api import Timer except: from tvtk.api import tvtk from mayavi.sources.vtk_data_source import VTKDataSource from pyface.timer.api import Timer from dataset_manager import DatasetManager from sfepy.base.base import Struct, basestr from sfepy.postprocess.utils import mlab from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.meshio import MeshIO, vtk_cell_types, supported_formats def create_file_source(filename, watch=False, offscreen=True): """Factory function to create a file source corresponding to the given file format.""" kwargs = {'watch' : watch, 'offscreen' : offscreen} if isinstance(filename, basestr): fmt = os.path.splitext(filename)[1] is_sequence = False else: # A sequence. fmt = os.path.splitext(filename[0])[1] is_sequence = True fmt = fmt.lower() if fmt == '.vtk': # VTK is supported directly by Mayavi, no need to use MeshIO. if is_sequence: return VTKSequenceFileSource(filename, **kwargs) else: return VTKFileSource(filename, **kwargs) elif fmt in supported_formats.keys(): if is_sequence: if fmt == '.h5': raise ValueError('format .h5 does not support file sequences!') else: return GenericSequenceFileSource(filename, **kwargs) else: return GenericFileSource(filename, **kwargs) else: raise ValueError('unknown file format! (%s)' % fmt) class FileSource(Struct): """General file source.""" def __init__(self, filename, watch=False, offscreen=True): """Create a file source using the given file name.""" mlab.options.offscreen = offscreen self.watch = watch self.filename = filename self.reset() def __call__(self, step=0): """Get the file source.""" if self.source is None: self.source = self.create_source() if self.watch: self.timer = Timer(1000, self.poll_file) return self.source def reset(self): """Reset.""" self.mat_id_name = None self.source = None self.notify_obj = None self.steps = [] self.times = [] self.step = 0 self.time = 0.0 if self.watch: self.last_stat = os.stat(self.filename) def setup_mat_id(self, mat_id_name='mat_id', single_color=False): self.mat_id_name = mat_id_name self.single_color = single_color def get_step_time(self, step=None, time=None): """ Set current step and time to the values closest greater or equal to either step or time. Return the found values. """ if (step is not None) and len(self.steps): step = step if step >= 0 else self.steps[-1] + step + 1 ii = nm.searchsorted(self.steps, step) ii = nm.clip(ii, 0, len(self.steps) - 1) self.step = self.steps[ii] if len(self.times): self.time = self.times[ii] elif (time is not None) and len(self.times): ii = nm.searchsorted(self.times, time) ii = nm.clip(ii, 0, len(self.steps) - 1) self.step = self.steps[ii] self.time = self.times[ii] return self.step, self.time def get_ts_info(self): return self.steps, self.times def get_mat_id(self, mat_id_name='mat_id'): """ Get material ID numbers of the underlying mesh elements. """ if self.source is not None: dm = DatasetManager(dataset=self.source.outputs[0]) mat_id = dm.cell_scalars[mat_id_name] return mat_id def file_changed(self): pass def setup_notification(self, obj, attr): """The attribute 'attr' of the object 'obj' will be set to True when the source file is watched and changes.""" self.notify_obj = obj self.notify_attr = attr def poll_file(self): """Check the source file's time stamp and notify the self.notify_obj in case it changed. Subclasses should implement the file_changed() method.""" if not self.notify_obj: return s = os.stat(self.filename) if s[-2] == self.last_stat[-2]: setattr(self.notify_obj, self.notify_attr, False) else: self.file_changed() setattr(self.notify_obj, self.notify_attr, True) self.last_stat = s class VTKFileSource(FileSource): """A thin wrapper around mlab.pipeline.open().""" def create_source(self): """Create a VTK file source """ return mlab.pipeline.open(self.filename) def get_bounding_box(self): bbox = nm.array(self.source.reader.unstructured_grid_output.bounds) return bbox.reshape((3,2)).T def set_filename(self, filename, vis_source): self.filename = filename vis_source.base_file_name = filename # Force re-read. vis_source.reader.modified() vis_source.update() # Propagate changes in the pipeline. vis_source.data_changed = True class VTKSequenceFileSource(VTKFileSource): """A thin wrapper around mlab.pipeline.open() for VTK file sequences.""" def __init__(self, *args, **kwargs): FileSource.__init__(self, *args, **kwargs) self.steps = nm.arange(len(self.filename), dtype=nm.int32) def create_source(self): """Create a VTK file source """ return mlab.pipeline.open(self.filename[0]) def set_filename(self, filename, vis_source): self.filename = filename vis_source.base_file_name = filename[self.step] class GenericFileSource(FileSource): """File source usable with any format supported by MeshIO classes.""" def __init__(self, *args, **kwargs): FileSource.__init__(self, *args, **kwargs) self.read_common(self.filename) def read_common(self, filename): self.io =
MeshIO.any_from_filename(filename)
sfepy.discrete.fem.meshio.MeshIO.any_from_filename
import os import numpy as nm try: from enthought.tvtk.api import tvtk from enthought.mayavi.sources.vtk_data_source import VTKDataSource from enthought.pyface.timer.api import Timer except: from tvtk.api import tvtk from mayavi.sources.vtk_data_source import VTKDataSource from pyface.timer.api import Timer from dataset_manager import DatasetManager from sfepy.base.base import Struct, basestr from sfepy.postprocess.utils import mlab from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.meshio import MeshIO, vtk_cell_types, supported_formats def create_file_source(filename, watch=False, offscreen=True): """Factory function to create a file source corresponding to the given file format.""" kwargs = {'watch' : watch, 'offscreen' : offscreen} if isinstance(filename, basestr): fmt = os.path.splitext(filename)[1] is_sequence = False else: # A sequence. fmt = os.path.splitext(filename[0])[1] is_sequence = True fmt = fmt.lower() if fmt == '.vtk': # VTK is supported directly by Mayavi, no need to use MeshIO. if is_sequence: return VTKSequenceFileSource(filename, **kwargs) else: return VTKFileSource(filename, **kwargs) elif fmt in supported_formats.keys(): if is_sequence: if fmt == '.h5': raise ValueError('format .h5 does not support file sequences!') else: return GenericSequenceFileSource(filename, **kwargs) else: return GenericFileSource(filename, **kwargs) else: raise ValueError('unknown file format! (%s)' % fmt) class FileSource(Struct): """General file source.""" def __init__(self, filename, watch=False, offscreen=True): """Create a file source using the given file name.""" mlab.options.offscreen = offscreen self.watch = watch self.filename = filename self.reset() def __call__(self, step=0): """Get the file source.""" if self.source is None: self.source = self.create_source() if self.watch: self.timer = Timer(1000, self.poll_file) return self.source def reset(self): """Reset.""" self.mat_id_name = None self.source = None self.notify_obj = None self.steps = [] self.times = [] self.step = 0 self.time = 0.0 if self.watch: self.last_stat = os.stat(self.filename) def setup_mat_id(self, mat_id_name='mat_id', single_color=False): self.mat_id_name = mat_id_name self.single_color = single_color def get_step_time(self, step=None, time=None): """ Set current step and time to the values closest greater or equal to either step or time. Return the found values. """ if (step is not None) and len(self.steps): step = step if step >= 0 else self.steps[-1] + step + 1 ii = nm.searchsorted(self.steps, step) ii = nm.clip(ii, 0, len(self.steps) - 1) self.step = self.steps[ii] if len(self.times): self.time = self.times[ii] elif (time is not None) and len(self.times): ii = nm.searchsorted(self.times, time) ii = nm.clip(ii, 0, len(self.steps) - 1) self.step = self.steps[ii] self.time = self.times[ii] return self.step, self.time def get_ts_info(self): return self.steps, self.times def get_mat_id(self, mat_id_name='mat_id'): """ Get material ID numbers of the underlying mesh elements. """ if self.source is not None: dm = DatasetManager(dataset=self.source.outputs[0]) mat_id = dm.cell_scalars[mat_id_name] return mat_id def file_changed(self): pass def setup_notification(self, obj, attr): """The attribute 'attr' of the object 'obj' will be set to True when the source file is watched and changes.""" self.notify_obj = obj self.notify_attr = attr def poll_file(self): """Check the source file's time stamp and notify the self.notify_obj in case it changed. Subclasses should implement the file_changed() method.""" if not self.notify_obj: return s = os.stat(self.filename) if s[-2] == self.last_stat[-2]: setattr(self.notify_obj, self.notify_attr, False) else: self.file_changed() setattr(self.notify_obj, self.notify_attr, True) self.last_stat = s class VTKFileSource(FileSource): """A thin wrapper around mlab.pipeline.open().""" def create_source(self): """Create a VTK file source """ return mlab.pipeline.open(self.filename) def get_bounding_box(self): bbox = nm.array(self.source.reader.unstructured_grid_output.bounds) return bbox.reshape((3,2)).T def set_filename(self, filename, vis_source): self.filename = filename vis_source.base_file_name = filename # Force re-read. vis_source.reader.modified() vis_source.update() # Propagate changes in the pipeline. vis_source.data_changed = True class VTKSequenceFileSource(VTKFileSource): """A thin wrapper around mlab.pipeline.open() for VTK file sequences.""" def __init__(self, *args, **kwargs): FileSource.__init__(self, *args, **kwargs) self.steps = nm.arange(len(self.filename), dtype=nm.int32) def create_source(self): """Create a VTK file source """ return mlab.pipeline.open(self.filename[0]) def set_filename(self, filename, vis_source): self.filename = filename vis_source.base_file_name = filename[self.step] class GenericFileSource(FileSource): """File source usable with any format supported by MeshIO classes.""" def __init__(self, *args, **kwargs): FileSource.__init__(self, *args, **kwargs) self.read_common(self.filename) def read_common(self, filename): self.io = MeshIO.any_from_filename(filename) self.steps, self.times, _ = self.io.read_times() self.mesh =
Mesh.from_file(filename)
sfepy.discrete.fem.Mesh.from_file
import os import numpy as nm try: from enthought.tvtk.api import tvtk from enthought.mayavi.sources.vtk_data_source import VTKDataSource from enthought.pyface.timer.api import Timer except: from tvtk.api import tvtk from mayavi.sources.vtk_data_source import VTKDataSource from pyface.timer.api import Timer from dataset_manager import DatasetManager from sfepy.base.base import Struct, basestr from sfepy.postprocess.utils import mlab from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.meshio import MeshIO, vtk_cell_types, supported_formats def create_file_source(filename, watch=False, offscreen=True): """Factory function to create a file source corresponding to the given file format.""" kwargs = {'watch' : watch, 'offscreen' : offscreen} if isinstance(filename, basestr): fmt = os.path.splitext(filename)[1] is_sequence = False else: # A sequence. fmt = os.path.splitext(filename[0])[1] is_sequence = True fmt = fmt.lower() if fmt == '.vtk': # VTK is supported directly by Mayavi, no need to use MeshIO. if is_sequence: return VTKSequenceFileSource(filename, **kwargs) else: return VTKFileSource(filename, **kwargs) elif fmt in
supported_formats.keys()
sfepy.discrete.fem.meshio.supported_formats.keys
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr from sfepy.base.timing import Timer import six def parse_approx_order(approx_order): """ Parse the uniform approximation order value (str or int). """ ao_msg = 'unsupported approximation order! (%s)' force_bubble = False discontinuous = False if approx_order is None: return 'iga', force_bubble, discontinuous elif isinstance(approx_order, basestr): if approx_order.startswith('iga'): return approx_order, force_bubble, discontinuous try: ao = int(approx_order) except ValueError: mode = approx_order[-1].lower() if mode == 'b': ao = int(approx_order[:-1]) force_bubble = True elif mode == 'd': ao = int(approx_order[:-1]) discontinuous = True else: raise ValueError(ao_msg % approx_order) if ao < 0: raise ValueError(ao_msg % approx_order) elif ao == 0: discontinuous = True return ao, force_bubble, discontinuous def parse_shape(shape, dim): if isinstance(shape, basestr): try: shape = {'scalar' : (1,), 'vector' : (dim,)}[shape] except KeyError: raise ValueError('unsupported field shape! (%s)', shape) elif isinstance(shape, six.integer_types): shape = (int(shape),) return shape def setup_extra_data(conn_info): """ Setup extra data required for non-volume integration. """ for key, ii, info in
iter_dict_of_lists(conn_info, return_keys=True)
sfepy.base.base.iter_dict_of_lists
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr from sfepy.base.timing import Timer import six def parse_approx_order(approx_order): """ Parse the uniform approximation order value (str or int). """ ao_msg = 'unsupported approximation order! (%s)' force_bubble = False discontinuous = False if approx_order is None: return 'iga', force_bubble, discontinuous elif isinstance(approx_order, basestr): if approx_order.startswith('iga'): return approx_order, force_bubble, discontinuous try: ao = int(approx_order) except ValueError: mode = approx_order[-1].lower() if mode == 'b': ao = int(approx_order[:-1]) force_bubble = True elif mode == 'd': ao = int(approx_order[:-1]) discontinuous = True else: raise ValueError(ao_msg % approx_order) if ao < 0: raise ValueError(ao_msg % approx_order) elif ao == 0: discontinuous = True return ao, force_bubble, discontinuous def parse_shape(shape, dim): if isinstance(shape, basestr): try: shape = {'scalar' : (1,), 'vector' : (dim,)}[shape] except KeyError: raise ValueError('unsupported field shape! (%s)', shape) elif isinstance(shape, six.integer_types): shape = (int(shape),) return shape def setup_extra_data(conn_info): """ Setup extra data required for non-volume integration. """ for key, ii, info in iter_dict_of_lists(conn_info, return_keys=True): for var in info.all_vars: field = var.get_field() if var == info.primary: field.setup_extra_data(info.ps_tg, info, info.is_trace) def fields_from_conf(conf, regions): fields = {} for key, val in six.iteritems(conf): field = Field.from_conf(val, regions) fields[field.name] = field return fields class Field(Struct): """ Base class for fields. """ _all = None @staticmethod def from_args(name, dtype, shape, region, approx_order=1, space='H1', poly_space_base='lagrange'): """ Create a Field subclass instance corresponding to a given space. 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/str The FE approximation order, e.g. 0, 1, 2, '1B' (1 with bubble). space : str The function space name. poly_space_base : str The name of polynomial space base. Notes ----- Assumes one cell type for the whole region! """ conf = Struct(name=name, dtype=dtype, shape=shape, region=region.name, approx_order=approx_order, space=space, poly_space_base=poly_space_base) return Field.from_conf(conf, {region.name : region}) @staticmethod def from_conf(conf, regions): """ Create a Field subclass instance based on the configuration. """ if Field._all is None: from sfepy import get_paths from sfepy.base.base import load_classes field_files = [ii for ii in get_paths('sfepy/discrete/fem/fields*.py') if 'fields_base.py' not in ii] field_files += get_paths('sfepy/discrete/iga/fields*.py') field_files += get_paths('sfepy/discrete/structural/fields*.py') Field._all = load_classes(field_files, [Field], ignore_errors=True, name_attr='family_name') table = Field._all space = conf.get('space', 'H1') poly_space_base = conf.get('poly_space_base', 'lagrange') key = space + '_' + poly_space_base approx_order = parse_approx_order(conf.approx_order) ao, force_bubble, discontinuous = approx_order region = regions[conf.region] if region.kind == 'cell': # Volume fields. kind = 'volume' if discontinuous: cls = table[kind + '_' + key + '_discontinuous'] else: cls = table[kind + '_' + key] obj = cls(conf.name, conf.dtype, conf.shape, region, approx_order=approx_order[:2]) else: # Surface fields. kind = 'surface' cls = table[kind + '_' + key] obj = cls(conf.name, conf.dtype, conf.shape, region, approx_order=approx_order[:2]) return obj def _setup_kind(self): name = self.get('family_name', None, 'An abstract Field method called!') aux = name.split('_') self.space = aux[1] self.poly_space_base = aux[2] def clear_mappings(self, clear_all=False): """ Clear current reference mappings. """ self.mappings = {} if clear_all: if hasattr(self, 'mappings0'): self.mappings0.clear() else: self.mappings0 = {} def save_mappings(self): """ Save current reference mappings to `mappings0` attribute. """ import sfepy.base.multiproc as multi if
multi.is_remote_dict(self.mappings0)
sfepy.base.multiproc.is_remote_dict
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr from sfepy.base.timing import Timer import six def parse_approx_order(approx_order): """ Parse the uniform approximation order value (str or int). """ ao_msg = 'unsupported approximation order! (%s)' force_bubble = False discontinuous = False if approx_order is None: return 'iga', force_bubble, discontinuous elif isinstance(approx_order, basestr): if approx_order.startswith('iga'): return approx_order, force_bubble, discontinuous try: ao = int(approx_order) except ValueError: mode = approx_order[-1].lower() if mode == 'b': ao = int(approx_order[:-1]) force_bubble = True elif mode == 'd': ao = int(approx_order[:-1]) discontinuous = True else: raise ValueError(ao_msg % approx_order) if ao < 0: raise ValueError(ao_msg % approx_order) elif ao == 0: discontinuous = True return ao, force_bubble, discontinuous def parse_shape(shape, dim): if isinstance(shape, basestr): try: shape = {'scalar' : (1,), 'vector' : (dim,)}[shape] except KeyError: raise ValueError('unsupported field shape! (%s)', shape) elif isinstance(shape, six.integer_types): shape = (int(shape),) return shape def setup_extra_data(conn_info): """ Setup extra data required for non-volume integration. """ for key, ii, info in iter_dict_of_lists(conn_info, return_keys=True): for var in info.all_vars: field = var.get_field() if var == info.primary: field.setup_extra_data(info.ps_tg, info, info.is_trace) def fields_from_conf(conf, regions): fields = {} for key, val in six.iteritems(conf): field = Field.from_conf(val, regions) fields[field.name] = field return fields class Field(Struct): """ Base class for fields. """ _all = None @staticmethod def from_args(name, dtype, shape, region, approx_order=1, space='H1', poly_space_base='lagrange'): """ Create a Field subclass instance corresponding to a given space. 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/str The FE approximation order, e.g. 0, 1, 2, '1B' (1 with bubble). space : str The function space name. poly_space_base : str The name of polynomial space base. Notes ----- Assumes one cell type for the whole region! """ conf = Struct(name=name, dtype=dtype, shape=shape, region=region.name, approx_order=approx_order, space=space, poly_space_base=poly_space_base) return Field.from_conf(conf, {region.name : region}) @staticmethod def from_conf(conf, regions): """ Create a Field subclass instance based on the configuration. """ if Field._all is None: from sfepy import get_paths from sfepy.base.base import load_classes field_files = [ii for ii in get_paths('sfepy/discrete/fem/fields*.py') if 'fields_base.py' not in ii] field_files += get_paths('sfepy/discrete/iga/fields*.py') field_files += get_paths('sfepy/discrete/structural/fields*.py') Field._all = load_classes(field_files, [Field], ignore_errors=True, name_attr='family_name') table = Field._all space = conf.get('space', 'H1') poly_space_base = conf.get('poly_space_base', 'lagrange') key = space + '_' + poly_space_base approx_order = parse_approx_order(conf.approx_order) ao, force_bubble, discontinuous = approx_order region = regions[conf.region] if region.kind == 'cell': # Volume fields. kind = 'volume' if discontinuous: cls = table[kind + '_' + key + '_discontinuous'] else: cls = table[kind + '_' + key] obj = cls(conf.name, conf.dtype, conf.shape, region, approx_order=approx_order[:2]) else: # Surface fields. kind = 'surface' cls = table[kind + '_' + key] obj = cls(conf.name, conf.dtype, conf.shape, region, approx_order=approx_order[:2]) return obj def _setup_kind(self): name = self.get('family_name', None, 'An abstract Field method called!') aux = name.split('_') self.space = aux[1] self.poly_space_base = aux[2] def clear_mappings(self, clear_all=False): """ Clear current reference mappings. """ self.mappings = {} if clear_all: if hasattr(self, 'mappings0'): self.mappings0.clear() else: self.mappings0 = {} def save_mappings(self): """ Save current reference mappings to `mappings0` attribute. """ import sfepy.base.multiproc as multi if multi.is_remote_dict(self.mappings0): for k, v in six.iteritems(self.mappings): m, _ = self.mappings[k] nv = (m.bf, m.bfg, m.det, m.volume, m.normal) self.mappings0[k] = nv else: self.mappings0 = self.mappings.copy() def get_mapping(self, region, integral, integration, get_saved=False, return_key=False): """ For given region, integral and integration type, get a reference mapping, i.e. jacobians, element volumes and base function derivatives for Volume-type geometries, and jacobians, normals and base function derivatives for Surface-type geometries corresponding to the field approximation. The mappings are cached in the field instance in `mappings` attribute. The mappings can be saved to `mappings0` using `Field.save_mappings`. The saved mapping can be retrieved by passing `get_saved=True`. If the required (saved) mapping is not in cache, a new one is created. Returns ------- geo : CMapping instance The reference mapping. mapping : VolumeMapping or SurfaceMapping instance The mapping. key : tuple The key of the mapping in `mappings` or `mappings0`. """ import sfepy.base.multiproc as multi key = (region.name, integral.order, integration) if get_saved: out = self.mappings0.get(key, None) if multi.is_remote_dict(self.mappings0) and out is not None: m, i = self.create_mapping(region, integral, integration) m.bf[:], m.bfg[:], m.det[:], m.volume[:] = out[0:4] if m.normal is not None: m.normal[:] = m[4] out = m, i else: out = self.mappings.get(key, None) if out is None: out = self.create_mapping(region, integral, integration) self.mappings[key] = out if return_key: out = out + (key,) return out def create_eval_mesh(self): """ Create a mesh for evaluating the field. The default implementation returns None, because this mesh is for most fields the same as the one created by `Field.create_mesh()`. """ def evaluate_at(self, coors, source_vals, mode='val', strategy='general', close_limit=0.1, get_cells_fun=None, cache=None, ret_cells=False, ret_status=False, ret_ref_coors=False, verbose=False): """ Evaluate source DOF values corresponding to the field in the given coordinates using the field interpolation. Parameters ---------- coors : array, shape ``(n_coor, dim)`` The coordinates the source values should be interpolated into. source_vals : array, shape ``(n_nod, n_components)`` The source DOF values corresponding to the field. mode : {'val', 'grad'}, optional The evaluation mode: the field value (default) or the field value gradient. strategy : {'general', 'convex'}, optional The strategy for finding the elements that contain the coordinates. For convex meshes, the 'convex' strategy might be faster than the 'general' one. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. get_cells_fun : callable, optional If given, a function with signature ``get_cells_fun(coors, cmesh, **kwargs)`` returning cells and offsets that potentially contain points with the coordinates `coors`. Applicable only when `strategy` is 'general'. When not given, :func:`get_potential_cells() <sfepy.discrete.common.global_interp.get_potential_cells>` is used. cache : Struct, optional To speed up a sequence of evaluations, the field mesh and other data can be cached. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the mesh related data are ignored. See :func:`Field.get_evaluate_cache() <sfepy.discrete.fem.fields_base.FEField.get_evaluate_cache()>`. ret_ref_coors : bool, optional If True, return also the found reference element coordinates. ret_status : bool, optional If True, return also the enclosing cell status for each point. ret_cells : bool, optional If True, return also the cell indices the coordinates are in. verbose : bool If False, reduce verbosity. Returns ------- vals : array The interpolated values with shape ``(n_coor, n_components)`` or gradients with shape ``(n_coor, n_components, dim)`` according to the `mode`. If `ret_status` is False, the values where the status is greater than one are set to ``numpy.nan``. ref_coors : array The found reference element coordinates, if `ret_ref_coors` is True. cells : array The cell indices, if `ret_ref_coors` or `ret_cells` or `ret_status` are True. status : array The status, if `ret_ref_coors` or `ret_status` are True, with the following meaning: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure, 4 is failure due to non-convergence of the Newton iteration in tensor product cells. If close_limit is 0, then for the 'general' strategy the status 5 indicates points outside of the field domain that had no potential cells. """ from sfepy.discrete.common.global_interp import get_ref_coors from sfepy.discrete.common.extmods.crefcoors import evaluate_in_rc from sfepy.base.base import complex_types
output('evaluating in %d points...' % coors.shape[0], verbose=verbose)
sfepy.base.base.output
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr from sfepy.base.timing import Timer import six def parse_approx_order(approx_order): """ Parse the uniform approximation order value (str or int). """ ao_msg = 'unsupported approximation order! (%s)' force_bubble = False discontinuous = False if approx_order is None: return 'iga', force_bubble, discontinuous elif isinstance(approx_order, basestr): if approx_order.startswith('iga'): return approx_order, force_bubble, discontinuous try: ao = int(approx_order) except ValueError: mode = approx_order[-1].lower() if mode == 'b': ao = int(approx_order[:-1]) force_bubble = True elif mode == 'd': ao = int(approx_order[:-1]) discontinuous = True else: raise ValueError(ao_msg % approx_order) if ao < 0: raise ValueError(ao_msg % approx_order) elif ao == 0: discontinuous = True return ao, force_bubble, discontinuous def parse_shape(shape, dim): if isinstance(shape, basestr): try: shape = {'scalar' : (1,), 'vector' : (dim,)}[shape] except KeyError: raise ValueError('unsupported field shape! (%s)', shape) elif isinstance(shape, six.integer_types): shape = (int(shape),) return shape def setup_extra_data(conn_info): """ Setup extra data required for non-volume integration. """ for key, ii, info in iter_dict_of_lists(conn_info, return_keys=True): for var in info.all_vars: field = var.get_field() if var == info.primary: field.setup_extra_data(info.ps_tg, info, info.is_trace) def fields_from_conf(conf, regions): fields = {} for key, val in six.iteritems(conf): field = Field.from_conf(val, regions) fields[field.name] = field return fields class Field(Struct): """ Base class for fields. """ _all = None @staticmethod def from_args(name, dtype, shape, region, approx_order=1, space='H1', poly_space_base='lagrange'): """ Create a Field subclass instance corresponding to a given space. 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/str The FE approximation order, e.g. 0, 1, 2, '1B' (1 with bubble). space : str The function space name. poly_space_base : str The name of polynomial space base. Notes ----- Assumes one cell type for the whole region! """ conf = Struct(name=name, dtype=dtype, shape=shape, region=region.name, approx_order=approx_order, space=space, poly_space_base=poly_space_base) return Field.from_conf(conf, {region.name : region}) @staticmethod def from_conf(conf, regions): """ Create a Field subclass instance based on the configuration. """ if Field._all is None: from sfepy import get_paths from sfepy.base.base import load_classes field_files = [ii for ii in get_paths('sfepy/discrete/fem/fields*.py') if 'fields_base.py' not in ii] field_files += get_paths('sfepy/discrete/iga/fields*.py') field_files += get_paths('sfepy/discrete/structural/fields*.py') Field._all = load_classes(field_files, [Field], ignore_errors=True, name_attr='family_name') table = Field._all space = conf.get('space', 'H1') poly_space_base = conf.get('poly_space_base', 'lagrange') key = space + '_' + poly_space_base approx_order = parse_approx_order(conf.approx_order) ao, force_bubble, discontinuous = approx_order region = regions[conf.region] if region.kind == 'cell': # Volume fields. kind = 'volume' if discontinuous: cls = table[kind + '_' + key + '_discontinuous'] else: cls = table[kind + '_' + key] obj = cls(conf.name, conf.dtype, conf.shape, region, approx_order=approx_order[:2]) else: # Surface fields. kind = 'surface' cls = table[kind + '_' + key] obj = cls(conf.name, conf.dtype, conf.shape, region, approx_order=approx_order[:2]) return obj def _setup_kind(self): name = self.get('family_name', None, 'An abstract Field method called!') aux = name.split('_') self.space = aux[1] self.poly_space_base = aux[2] def clear_mappings(self, clear_all=False): """ Clear current reference mappings. """ self.mappings = {} if clear_all: if hasattr(self, 'mappings0'): self.mappings0.clear() else: self.mappings0 = {} def save_mappings(self): """ Save current reference mappings to `mappings0` attribute. """ import sfepy.base.multiproc as multi if multi.is_remote_dict(self.mappings0): for k, v in six.iteritems(self.mappings): m, _ = self.mappings[k] nv = (m.bf, m.bfg, m.det, m.volume, m.normal) self.mappings0[k] = nv else: self.mappings0 = self.mappings.copy() def get_mapping(self, region, integral, integration, get_saved=False, return_key=False): """ For given region, integral and integration type, get a reference mapping, i.e. jacobians, element volumes and base function derivatives for Volume-type geometries, and jacobians, normals and base function derivatives for Surface-type geometries corresponding to the field approximation. The mappings are cached in the field instance in `mappings` attribute. The mappings can be saved to `mappings0` using `Field.save_mappings`. The saved mapping can be retrieved by passing `get_saved=True`. If the required (saved) mapping is not in cache, a new one is created. Returns ------- geo : CMapping instance The reference mapping. mapping : VolumeMapping or SurfaceMapping instance The mapping. key : tuple The key of the mapping in `mappings` or `mappings0`. """ import sfepy.base.multiproc as multi key = (region.name, integral.order, integration) if get_saved: out = self.mappings0.get(key, None) if multi.is_remote_dict(self.mappings0) and out is not None: m, i = self.create_mapping(region, integral, integration) m.bf[:], m.bfg[:], m.det[:], m.volume[:] = out[0:4] if m.normal is not None: m.normal[:] = m[4] out = m, i else: out = self.mappings.get(key, None) if out is None: out = self.create_mapping(region, integral, integration) self.mappings[key] = out if return_key: out = out + (key,) return out def create_eval_mesh(self): """ Create a mesh for evaluating the field. The default implementation returns None, because this mesh is for most fields the same as the one created by `Field.create_mesh()`. """ def evaluate_at(self, coors, source_vals, mode='val', strategy='general', close_limit=0.1, get_cells_fun=None, cache=None, ret_cells=False, ret_status=False, ret_ref_coors=False, verbose=False): """ Evaluate source DOF values corresponding to the field in the given coordinates using the field interpolation. Parameters ---------- coors : array, shape ``(n_coor, dim)`` The coordinates the source values should be interpolated into. source_vals : array, shape ``(n_nod, n_components)`` The source DOF values corresponding to the field. mode : {'val', 'grad'}, optional The evaluation mode: the field value (default) or the field value gradient. strategy : {'general', 'convex'}, optional The strategy for finding the elements that contain the coordinates. For convex meshes, the 'convex' strategy might be faster than the 'general' one. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. get_cells_fun : callable, optional If given, a function with signature ``get_cells_fun(coors, cmesh, **kwargs)`` returning cells and offsets that potentially contain points with the coordinates `coors`. Applicable only when `strategy` is 'general'. When not given, :func:`get_potential_cells() <sfepy.discrete.common.global_interp.get_potential_cells>` is used. cache : Struct, optional To speed up a sequence of evaluations, the field mesh and other data can be cached. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the mesh related data are ignored. See :func:`Field.get_evaluate_cache() <sfepy.discrete.fem.fields_base.FEField.get_evaluate_cache()>`. ret_ref_coors : bool, optional If True, return also the found reference element coordinates. ret_status : bool, optional If True, return also the enclosing cell status for each point. ret_cells : bool, optional If True, return also the cell indices the coordinates are in. verbose : bool If False, reduce verbosity. Returns ------- vals : array The interpolated values with shape ``(n_coor, n_components)`` or gradients with shape ``(n_coor, n_components, dim)`` according to the `mode`. If `ret_status` is False, the values where the status is greater than one are set to ``numpy.nan``. ref_coors : array The found reference element coordinates, if `ret_ref_coors` is True. cells : array The cell indices, if `ret_ref_coors` or `ret_cells` or `ret_status` are True. status : array The status, if `ret_ref_coors` or `ret_status` are True, with the following meaning: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure, 4 is failure due to non-convergence of the Newton iteration in tensor product cells. If close_limit is 0, then for the 'general' strategy the status 5 indicates points outside of the field domain that had no potential cells. """ from sfepy.discrete.common.global_interp import get_ref_coors from sfepy.discrete.common.extmods.crefcoors import evaluate_in_rc from sfepy.base.base import complex_types output('evaluating in %d points...' % coors.shape[0], verbose=verbose) ref_coors, cells, status = get_ref_coors(self, coors, strategy=strategy, close_limit=close_limit, get_cells_fun=get_cells_fun, cache=cache, verbose=verbose) timer =
Timer(start=True)
sfepy.base.timing.Timer
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr from sfepy.base.timing import Timer import six def parse_approx_order(approx_order): """ Parse the uniform approximation order value (str or int). """ ao_msg = 'unsupported approximation order! (%s)' force_bubble = False discontinuous = False if approx_order is None: return 'iga', force_bubble, discontinuous elif isinstance(approx_order, basestr): if approx_order.startswith('iga'): return approx_order, force_bubble, discontinuous try: ao = int(approx_order) except ValueError: mode = approx_order[-1].lower() if mode == 'b': ao = int(approx_order[:-1]) force_bubble = True elif mode == 'd': ao = int(approx_order[:-1]) discontinuous = True else: raise ValueError(ao_msg % approx_order) if ao < 0: raise ValueError(ao_msg % approx_order) elif ao == 0: discontinuous = True return ao, force_bubble, discontinuous def parse_shape(shape, dim): if isinstance(shape, basestr): try: shape = {'scalar' : (1,), 'vector' : (dim,)}[shape] except KeyError: raise ValueError('unsupported field shape! (%s)', shape) elif isinstance(shape, six.integer_types): shape = (int(shape),) return shape def setup_extra_data(conn_info): """ Setup extra data required for non-volume integration. """ for key, ii, info in iter_dict_of_lists(conn_info, return_keys=True): for var in info.all_vars: field = var.get_field() if var == info.primary: field.setup_extra_data(info.ps_tg, info, info.is_trace) def fields_from_conf(conf, regions): fields = {} for key, val in six.iteritems(conf): field = Field.from_conf(val, regions) fields[field.name] = field return fields class Field(Struct): """ Base class for fields. """ _all = None @staticmethod def from_args(name, dtype, shape, region, approx_order=1, space='H1', poly_space_base='lagrange'): """ Create a Field subclass instance corresponding to a given space. 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/str The FE approximation order, e.g. 0, 1, 2, '1B' (1 with bubble). space : str The function space name. poly_space_base : str The name of polynomial space base. Notes ----- Assumes one cell type for the whole region! """ conf = Struct(name=name, dtype=dtype, shape=shape, region=region.name, approx_order=approx_order, space=space, poly_space_base=poly_space_base) return Field.from_conf(conf, {region.name : region}) @staticmethod def from_conf(conf, regions): """ Create a Field subclass instance based on the configuration. """ if Field._all is None: from sfepy import get_paths from sfepy.base.base import load_classes field_files = [ii for ii in get_paths('sfepy/discrete/fem/fields*.py') if 'fields_base.py' not in ii] field_files += get_paths('sfepy/discrete/iga/fields*.py') field_files += get_paths('sfepy/discrete/structural/fields*.py') Field._all = load_classes(field_files, [Field], ignore_errors=True, name_attr='family_name') table = Field._all space = conf.get('space', 'H1') poly_space_base = conf.get('poly_space_base', 'lagrange') key = space + '_' + poly_space_base approx_order = parse_approx_order(conf.approx_order) ao, force_bubble, discontinuous = approx_order region = regions[conf.region] if region.kind == 'cell': # Volume fields. kind = 'volume' if discontinuous: cls = table[kind + '_' + key + '_discontinuous'] else: cls = table[kind + '_' + key] obj = cls(conf.name, conf.dtype, conf.shape, region, approx_order=approx_order[:2]) else: # Surface fields. kind = 'surface' cls = table[kind + '_' + key] obj = cls(conf.name, conf.dtype, conf.shape, region, approx_order=approx_order[:2]) return obj def _setup_kind(self): name = self.get('family_name', None, 'An abstract Field method called!') aux = name.split('_') self.space = aux[1] self.poly_space_base = aux[2] def clear_mappings(self, clear_all=False): """ Clear current reference mappings. """ self.mappings = {} if clear_all: if hasattr(self, 'mappings0'): self.mappings0.clear() else: self.mappings0 = {} def save_mappings(self): """ Save current reference mappings to `mappings0` attribute. """ import sfepy.base.multiproc as multi if multi.is_remote_dict(self.mappings0): for k, v in six.iteritems(self.mappings): m, _ = self.mappings[k] nv = (m.bf, m.bfg, m.det, m.volume, m.normal) self.mappings0[k] = nv else: self.mappings0 = self.mappings.copy() def get_mapping(self, region, integral, integration, get_saved=False, return_key=False): """ For given region, integral and integration type, get a reference mapping, i.e. jacobians, element volumes and base function derivatives for Volume-type geometries, and jacobians, normals and base function derivatives for Surface-type geometries corresponding to the field approximation. The mappings are cached in the field instance in `mappings` attribute. The mappings can be saved to `mappings0` using `Field.save_mappings`. The saved mapping can be retrieved by passing `get_saved=True`. If the required (saved) mapping is not in cache, a new one is created. Returns ------- geo : CMapping instance The reference mapping. mapping : VolumeMapping or SurfaceMapping instance The mapping. key : tuple The key of the mapping in `mappings` or `mappings0`. """ import sfepy.base.multiproc as multi key = (region.name, integral.order, integration) if get_saved: out = self.mappings0.get(key, None) if multi.is_remote_dict(self.mappings0) and out is not None: m, i = self.create_mapping(region, integral, integration) m.bf[:], m.bfg[:], m.det[:], m.volume[:] = out[0:4] if m.normal is not None: m.normal[:] = m[4] out = m, i else: out = self.mappings.get(key, None) if out is None: out = self.create_mapping(region, integral, integration) self.mappings[key] = out if return_key: out = out + (key,) return out def create_eval_mesh(self): """ Create a mesh for evaluating the field. The default implementation returns None, because this mesh is for most fields the same as the one created by `Field.create_mesh()`. """ def evaluate_at(self, coors, source_vals, mode='val', strategy='general', close_limit=0.1, get_cells_fun=None, cache=None, ret_cells=False, ret_status=False, ret_ref_coors=False, verbose=False): """ Evaluate source DOF values corresponding to the field in the given coordinates using the field interpolation. Parameters ---------- coors : array, shape ``(n_coor, dim)`` The coordinates the source values should be interpolated into. source_vals : array, shape ``(n_nod, n_components)`` The source DOF values corresponding to the field. mode : {'val', 'grad'}, optional The evaluation mode: the field value (default) or the field value gradient. strategy : {'general', 'convex'}, optional The strategy for finding the elements that contain the coordinates. For convex meshes, the 'convex' strategy might be faster than the 'general' one. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. get_cells_fun : callable, optional If given, a function with signature ``get_cells_fun(coors, cmesh, **kwargs)`` returning cells and offsets that potentially contain points with the coordinates `coors`. Applicable only when `strategy` is 'general'. When not given, :func:`get_potential_cells() <sfepy.discrete.common.global_interp.get_potential_cells>` is used. cache : Struct, optional To speed up a sequence of evaluations, the field mesh and other data can be cached. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the mesh related data are ignored. See :func:`Field.get_evaluate_cache() <sfepy.discrete.fem.fields_base.FEField.get_evaluate_cache()>`. ret_ref_coors : bool, optional If True, return also the found reference element coordinates. ret_status : bool, optional If True, return also the enclosing cell status for each point. ret_cells : bool, optional If True, return also the cell indices the coordinates are in. verbose : bool If False, reduce verbosity. Returns ------- vals : array The interpolated values with shape ``(n_coor, n_components)`` or gradients with shape ``(n_coor, n_components, dim)`` according to the `mode`. If `ret_status` is False, the values where the status is greater than one are set to ``numpy.nan``. ref_coors : array The found reference element coordinates, if `ret_ref_coors` is True. cells : array The cell indices, if `ret_ref_coors` or `ret_cells` or `ret_status` are True. status : array The status, if `ret_ref_coors` or `ret_status` are True, with the following meaning: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure, 4 is failure due to non-convergence of the Newton iteration in tensor product cells. If close_limit is 0, then for the 'general' strategy the status 5 indicates points outside of the field domain that had no potential cells. """ from sfepy.discrete.common.global_interp import get_ref_coors from sfepy.discrete.common.extmods.crefcoors import evaluate_in_rc from sfepy.base.base import complex_types output('evaluating in %d points...' % coors.shape[0], verbose=verbose) ref_coors, cells, status = get_ref_coors(self, coors, strategy=strategy, close_limit=close_limit, get_cells_fun=get_cells_fun, cache=cache, verbose=verbose) timer = Timer(start=True) # Interpolate to the reference coordinates. source_dtype = nm.float64 if source_vals.dtype in complex_types\ else source_vals.dtype if mode == 'val': vals = nm.empty((coors.shape[0], source_vals.shape[1], 1), dtype=source_dtype) cmode = 0 elif mode == 'grad': vals = nm.empty((coors.shape[0], source_vals.shape[1], coors.shape[1]), dtype=source_dtype) cmode = 1 ctx = self.create_basis_context() if source_vals.dtype in complex_types: valsi = vals.copy() evaluate_in_rc(vals, ref_coors, cells, status, nm.ascontiguousarray(source_vals.real), self.get_econn('volume', self.region), cmode, ctx) evaluate_in_rc(valsi, ref_coors, cells, status, nm.ascontiguousarray(source_vals.imag), self.get_econn('volume', self.region), cmode, ctx) vals = vals + valsi * 1j else: evaluate_in_rc(vals, ref_coors, cells, status, source_vals, self.get_econn('volume', self.region), cmode, ctx) output('interpolation: %f s' % timer.stop(),verbose=verbose)
output('...done',verbose=verbose)
sfepy.base.base.output
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr from sfepy.base.timing import Timer import six def parse_approx_order(approx_order): """ Parse the uniform approximation order value (str or int). """ ao_msg = 'unsupported approximation order! (%s)' force_bubble = False discontinuous = False if approx_order is None: return 'iga', force_bubble, discontinuous elif isinstance(approx_order, basestr): if approx_order.startswith('iga'): return approx_order, force_bubble, discontinuous try: ao = int(approx_order) except ValueError: mode = approx_order[-1].lower() if mode == 'b': ao = int(approx_order[:-1]) force_bubble = True elif mode == 'd': ao = int(approx_order[:-1]) discontinuous = True else: raise ValueError(ao_msg % approx_order) if ao < 0: raise ValueError(ao_msg % approx_order) elif ao == 0: discontinuous = True return ao, force_bubble, discontinuous def parse_shape(shape, dim): if isinstance(shape, basestr): try: shape = {'scalar' : (1,), 'vector' : (dim,)}[shape] except KeyError: raise ValueError('unsupported field shape! (%s)', shape) elif isinstance(shape, six.integer_types): shape = (int(shape),) return shape def setup_extra_data(conn_info): """ Setup extra data required for non-volume integration. """ for key, ii, info in iter_dict_of_lists(conn_info, return_keys=True): for var in info.all_vars: field = var.get_field() if var == info.primary: field.setup_extra_data(info.ps_tg, info, info.is_trace) def fields_from_conf(conf, regions): fields = {} for key, val in six.iteritems(conf): field = Field.from_conf(val, regions) fields[field.name] = field return fields class Field(Struct): """ Base class for fields. """ _all = None @staticmethod def from_args(name, dtype, shape, region, approx_order=1, space='H1', poly_space_base='lagrange'): """ Create a Field subclass instance corresponding to a given space. 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/str The FE approximation order, e.g. 0, 1, 2, '1B' (1 with bubble). space : str The function space name. poly_space_base : str The name of polynomial space base. Notes ----- Assumes one cell type for the whole region! """ conf = Struct(name=name, dtype=dtype, shape=shape, region=region.name, approx_order=approx_order, space=space, poly_space_base=poly_space_base) return Field.from_conf(conf, {region.name : region}) @staticmethod def from_conf(conf, regions): """ Create a Field subclass instance based on the configuration. """ if Field._all is None: from sfepy import get_paths from sfepy.base.base import load_classes field_files = [ii for ii in get_paths('sfepy/discrete/fem/fields*.py') if 'fields_base.py' not in ii] field_files +=
get_paths('sfepy/discrete/iga/fields*.py')
sfepy.get_paths
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr from sfepy.base.timing import Timer import six def parse_approx_order(approx_order): """ Parse the uniform approximation order value (str or int). """ ao_msg = 'unsupported approximation order! (%s)' force_bubble = False discontinuous = False if approx_order is None: return 'iga', force_bubble, discontinuous elif isinstance(approx_order, basestr): if approx_order.startswith('iga'): return approx_order, force_bubble, discontinuous try: ao = int(approx_order) except ValueError: mode = approx_order[-1].lower() if mode == 'b': ao = int(approx_order[:-1]) force_bubble = True elif mode == 'd': ao = int(approx_order[:-1]) discontinuous = True else: raise ValueError(ao_msg % approx_order) if ao < 0: raise ValueError(ao_msg % approx_order) elif ao == 0: discontinuous = True return ao, force_bubble, discontinuous def parse_shape(shape, dim): if isinstance(shape, basestr): try: shape = {'scalar' : (1,), 'vector' : (dim,)}[shape] except KeyError: raise ValueError('unsupported field shape! (%s)', shape) elif isinstance(shape, six.integer_types): shape = (int(shape),) return shape def setup_extra_data(conn_info): """ Setup extra data required for non-volume integration. """ for key, ii, info in iter_dict_of_lists(conn_info, return_keys=True): for var in info.all_vars: field = var.get_field() if var == info.primary: field.setup_extra_data(info.ps_tg, info, info.is_trace) def fields_from_conf(conf, regions): fields = {} for key, val in six.iteritems(conf): field = Field.from_conf(val, regions) fields[field.name] = field return fields class Field(Struct): """ Base class for fields. """ _all = None @staticmethod def from_args(name, dtype, shape, region, approx_order=1, space='H1', poly_space_base='lagrange'): """ Create a Field subclass instance corresponding to a given space. 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/str The FE approximation order, e.g. 0, 1, 2, '1B' (1 with bubble). space : str The function space name. poly_space_base : str The name of polynomial space base. Notes ----- Assumes one cell type for the whole region! """ conf = Struct(name=name, dtype=dtype, shape=shape, region=region.name, approx_order=approx_order, space=space, poly_space_base=poly_space_base) return Field.from_conf(conf, {region.name : region}) @staticmethod def from_conf(conf, regions): """ Create a Field subclass instance based on the configuration. """ if Field._all is None: from sfepy import get_paths from sfepy.base.base import load_classes field_files = [ii for ii in get_paths('sfepy/discrete/fem/fields*.py') if 'fields_base.py' not in ii] field_files += get_paths('sfepy/discrete/iga/fields*.py') field_files +=
get_paths('sfepy/discrete/structural/fields*.py')
sfepy.get_paths
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr from sfepy.base.timing import Timer import six def parse_approx_order(approx_order): """ Parse the uniform approximation order value (str or int). """ ao_msg = 'unsupported approximation order! (%s)' force_bubble = False discontinuous = False if approx_order is None: return 'iga', force_bubble, discontinuous elif isinstance(approx_order, basestr): if approx_order.startswith('iga'): return approx_order, force_bubble, discontinuous try: ao = int(approx_order) except ValueError: mode = approx_order[-1].lower() if mode == 'b': ao = int(approx_order[:-1]) force_bubble = True elif mode == 'd': ao = int(approx_order[:-1]) discontinuous = True else: raise ValueError(ao_msg % approx_order) if ao < 0: raise ValueError(ao_msg % approx_order) elif ao == 0: discontinuous = True return ao, force_bubble, discontinuous def parse_shape(shape, dim): if isinstance(shape, basestr): try: shape = {'scalar' : (1,), 'vector' : (dim,)}[shape] except KeyError: raise ValueError('unsupported field shape! (%s)', shape) elif isinstance(shape, six.integer_types): shape = (int(shape),) return shape def setup_extra_data(conn_info): """ Setup extra data required for non-volume integration. """ for key, ii, info in iter_dict_of_lists(conn_info, return_keys=True): for var in info.all_vars: field = var.get_field() if var == info.primary: field.setup_extra_data(info.ps_tg, info, info.is_trace) def fields_from_conf(conf, regions): fields = {} for key, val in six.iteritems(conf): field = Field.from_conf(val, regions) fields[field.name] = field return fields class Field(Struct): """ Base class for fields. """ _all = None @staticmethod def from_args(name, dtype, shape, region, approx_order=1, space='H1', poly_space_base='lagrange'): """ Create a Field subclass instance corresponding to a given space. 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/str The FE approximation order, e.g. 0, 1, 2, '1B' (1 with bubble). space : str The function space name. poly_space_base : str The name of polynomial space base. Notes ----- Assumes one cell type for the whole region! """ conf = Struct(name=name, dtype=dtype, shape=shape, region=region.name, approx_order=approx_order, space=space, poly_space_base=poly_space_base) return Field.from_conf(conf, {region.name : region}) @staticmethod def from_conf(conf, regions): """ Create a Field subclass instance based on the configuration. """ if Field._all is None: from sfepy import get_paths from sfepy.base.base import load_classes field_files = [ii for ii in get_paths('sfepy/discrete/fem/fields*.py') if 'fields_base.py' not in ii] field_files += get_paths('sfepy/discrete/iga/fields*.py') field_files += get_paths('sfepy/discrete/structural/fields*.py') Field._all = load_classes(field_files, [Field], ignore_errors=True, name_attr='family_name') table = Field._all space = conf.get('space', 'H1') poly_space_base = conf.get('poly_space_base', 'lagrange') key = space + '_' + poly_space_base approx_order = parse_approx_order(conf.approx_order) ao, force_bubble, discontinuous = approx_order region = regions[conf.region] if region.kind == 'cell': # Volume fields. kind = 'volume' if discontinuous: cls = table[kind + '_' + key + '_discontinuous'] else: cls = table[kind + '_' + key] obj = cls(conf.name, conf.dtype, conf.shape, region, approx_order=approx_order[:2]) else: # Surface fields. kind = 'surface' cls = table[kind + '_' + key] obj = cls(conf.name, conf.dtype, conf.shape, region, approx_order=approx_order[:2]) return obj def _setup_kind(self): name = self.get('family_name', None, 'An abstract Field method called!') aux = name.split('_') self.space = aux[1] self.poly_space_base = aux[2] def clear_mappings(self, clear_all=False): """ Clear current reference mappings. """ self.mappings = {} if clear_all: if hasattr(self, 'mappings0'): self.mappings0.clear() else: self.mappings0 = {} def save_mappings(self): """ Save current reference mappings to `mappings0` attribute. """ import sfepy.base.multiproc as multi if multi.is_remote_dict(self.mappings0): for k, v in six.iteritems(self.mappings): m, _ = self.mappings[k] nv = (m.bf, m.bfg, m.det, m.volume, m.normal) self.mappings0[k] = nv else: self.mappings0 = self.mappings.copy() def get_mapping(self, region, integral, integration, get_saved=False, return_key=False): """ For given region, integral and integration type, get a reference mapping, i.e. jacobians, element volumes and base function derivatives for Volume-type geometries, and jacobians, normals and base function derivatives for Surface-type geometries corresponding to the field approximation. The mappings are cached in the field instance in `mappings` attribute. The mappings can be saved to `mappings0` using `Field.save_mappings`. The saved mapping can be retrieved by passing `get_saved=True`. If the required (saved) mapping is not in cache, a new one is created. Returns ------- geo : CMapping instance The reference mapping. mapping : VolumeMapping or SurfaceMapping instance The mapping. key : tuple The key of the mapping in `mappings` or `mappings0`. """ import sfepy.base.multiproc as multi key = (region.name, integral.order, integration) if get_saved: out = self.mappings0.get(key, None) if
multi.is_remote_dict(self.mappings0)
sfepy.base.multiproc.is_remote_dict
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr from sfepy.base.timing import Timer import six def parse_approx_order(approx_order): """ Parse the uniform approximation order value (str or int). """ ao_msg = 'unsupported approximation order! (%s)' force_bubble = False discontinuous = False if approx_order is None: return 'iga', force_bubble, discontinuous elif isinstance(approx_order, basestr): if approx_order.startswith('iga'): return approx_order, force_bubble, discontinuous try: ao = int(approx_order) except ValueError: mode = approx_order[-1].lower() if mode == 'b': ao = int(approx_order[:-1]) force_bubble = True elif mode == 'd': ao = int(approx_order[:-1]) discontinuous = True else: raise ValueError(ao_msg % approx_order) if ao < 0: raise ValueError(ao_msg % approx_order) elif ao == 0: discontinuous = True return ao, force_bubble, discontinuous def parse_shape(shape, dim): if isinstance(shape, basestr): try: shape = {'scalar' : (1,), 'vector' : (dim,)}[shape] except KeyError: raise ValueError('unsupported field shape! (%s)', shape) elif isinstance(shape, six.integer_types): shape = (int(shape),) return shape def setup_extra_data(conn_info): """ Setup extra data required for non-volume integration. """ for key, ii, info in iter_dict_of_lists(conn_info, return_keys=True): for var in info.all_vars: field = var.get_field() if var == info.primary: field.setup_extra_data(info.ps_tg, info, info.is_trace) def fields_from_conf(conf, regions): fields = {} for key, val in six.iteritems(conf): field = Field.from_conf(val, regions) fields[field.name] = field return fields class Field(Struct): """ Base class for fields. """ _all = None @staticmethod def from_args(name, dtype, shape, region, approx_order=1, space='H1', poly_space_base='lagrange'): """ Create a Field subclass instance corresponding to a given space. 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/str The FE approximation order, e.g. 0, 1, 2, '1B' (1 with bubble). space : str The function space name. poly_space_base : str The name of polynomial space base. Notes ----- Assumes one cell type for the whole region! """ conf = Struct(name=name, dtype=dtype, shape=shape, region=region.name, approx_order=approx_order, space=space, poly_space_base=poly_space_base) return Field.from_conf(conf, {region.name : region}) @staticmethod def from_conf(conf, regions): """ Create a Field subclass instance based on the configuration. """ if Field._all is None: from sfepy import get_paths from sfepy.base.base import load_classes field_files = [ii for ii in
get_paths('sfepy/discrete/fem/fields*.py')
sfepy.get_paths
import numpy as nm from sfepy.base.base import output, Struct from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.homogenization.coefficients import Coefficients import tables as pt from sfepy.discrete.fem.meshio import HDF5MeshIO import os.path as op def get_homog_coefs_linear(ts, coor, mode, micro_filename=None, regenerate=False, coefs_filename=None): oprefix = output.prefix output.prefix = 'micro:' required, other =
get_standard_keywords()
sfepy.base.conf.get_standard_keywords
import numpy as nm from sfepy.base.base import output, Struct from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.homogenization.coefficients import Coefficients import tables as pt from sfepy.discrete.fem.meshio import HDF5MeshIO import os.path as op def get_homog_coefs_linear(ts, coor, mode, micro_filename=None, regenerate=False, coefs_filename=None): oprefix = output.prefix output.prefix = 'micro:' required, other = get_standard_keywords() required.remove( 'equations' ) conf =
ProblemConf.from_file(micro_filename, required, other, verbose=False)
sfepy.base.conf.ProblemConf.from_file
import numpy as nm from sfepy.base.base import output, Struct from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.homogenization.coefficients import Coefficients import tables as pt from sfepy.discrete.fem.meshio import HDF5MeshIO import os.path as op def get_homog_coefs_linear(ts, coor, mode, micro_filename=None, regenerate=False, coefs_filename=None): oprefix = output.prefix output.prefix = 'micro:' required, other = get_standard_keywords() required.remove( 'equations' ) conf = ProblemConf.from_file(micro_filename, required, other, verbose=False) if coefs_filename is None: coefs_filename = conf.options.get('coefs_filename', 'coefs') coefs_filename = op.join(conf.options.get('output_dir', '.'), coefs_filename) + '.h5' if not regenerate: if op.exists( coefs_filename ): if not pt.isHDF5File( coefs_filename ): regenerate = True else: regenerate = True if regenerate: options = Struct( output_filename_trunk = None ) app = HomogenizationApp( conf, options, 'micro:' ) coefs = app() if type(coefs) is tuple: coefs = coefs[0] coefs.to_file_hdf5( coefs_filename ) else: coefs = Coefficients.from_file_hdf5( coefs_filename ) out = {} if mode == None: for key, val in coefs.__dict__.iteritems(): out[key] = val elif mode == 'qp': for key, val in coefs.__dict__.iteritems(): if type( val ) == nm.ndarray or type(val) == nm.float64: out[key] = nm.tile( val, (coor.shape[0], 1, 1) ) elif type(val) == dict: for key2, val2 in val.iteritems(): if type(val2) == nm.ndarray or type(val2) == nm.float64: out[key+'_'+key2] = \ nm.tile(val2, (coor.shape[0], 1, 1)) else: out = None output.prefix = oprefix return out def get_correctors_from_file( coefs_filename = 'coefs.h5', dump_names = None ): if dump_names == None: coefs = Coefficients.from_file_hdf5( coefs_filename ) if hasattr( coefs, 'dump_names' ): dump_names = coefs.dump_names else: raise ValueError( ' "filenames" coefficient must be used!' ) out = {} for key, val in dump_names.iteritems(): corr_name = op.split( val )[-1] io =
HDF5MeshIO( val+'.h5' )
sfepy.discrete.fem.meshio.HDF5MeshIO
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i =
Mesh.from_region(omega_gi, mesh, localize=True)
sfepy.discrete.fem.Mesh.from_region
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i =
FEDomain('domain_i', mesh_i)
sfepy.discrete.fem.FEDomain
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order)
output('number of local field DOFs:', field_i.n_nod)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i =
FieldVariable('u_i', 'unknown', field_i)
sfepy.discrete.FieldVariable
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i =
FieldVariable('v_i', 'test', field_i, primary_var_name='u_i')
sfepy.discrete.FieldVariable
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral =
Integral('i', order=2*order)
sfepy.discrete.Integral
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat =
Material('m', lam=10, mu=5)
sfepy.discrete.Material
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq =
Equation('balance', t1 - 100 * t2)
sfepy.discrete.Equation
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs =
Equations([eq])
sfepy.discrete.Equations
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb =
Problem('problem_i', equations=eqs, active_only=False)
sfepy.discrete.Problem
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec =
pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose)
sfepy.parallel.parallel.verify_task_dof_maps
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats =
Struct()
sfepy.base.base.Struct
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer =
Timer('solve_timer')
sfepy.base.timing.Timer
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh =
Mesh.from_file(mesh_filename)
sfepy.discrete.fem.Mesh.from_file
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop()
output('creating global domain and field...')
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain =
FEDomain('domain', mesh)
sfepy.discrete.fem.FEDomain
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field =
Field.from_args('fu', nm.float64, 1, omega, approx_order=order)
sfepy.discrete.fem.Field.from_args
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop()
output('...done in', timer.dt)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt)
output('distributing field %s...' % field.name)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop()
output('...done in', timer.dt)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size)
output('creating local problem...')
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi =
Region.from_cells(lfd.cells, field.domain)
sfepy.discrete.common.region.Region.from_cells
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop()
output('...done in', timer.dt)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank)
output('allocating global system...')
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange =
pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1)
sfepy.parallel.parallel.get_sizes
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1)
output('sizes:', sizes)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes)
output('drange:', drange)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs =
pl.get_local_ordering(field_i, lfd.petsc_dofs_conn)
sfepy.parallel.parallel.get_local_ordering
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn)
output('pdofs:', pdofs)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop()
output('...done in', timer.dt)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt)
output('evaluating local problem...')
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state =
State(variables)
sfepy.discrete.State
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop()
output('...done in', timer.dt)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt)
output('assembling global system...')
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start()
apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc)
sfepy.discrete.evaluate.apply_ebc_to_matrix
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop()
output('...done in', timer.dt)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt)
output('creating solver...')
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls =
PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
sfepy.solvers.ls.PETScKrylovSolver
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop()
output('...done in', timer.dt)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt)
output('solving...')
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i =
pl.create_local_petsc_vector(pdofs)
sfepy.parallel.parallel.create_local_petsc_vector
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter =
pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm)
sfepy.parallel.parallel.create_gather_scatter
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop()
output('...done in', timer.dt)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt)
output('saving solution...')
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt) output('saving solution...') timer.start() u_i.set_data(sol0_i) out = u_i.create_output() filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank) pb.domain.mesh.write(filename, io='auto', out=out) gather_to_zero =
pl.create_gather_to_zero(psol)
sfepy.parallel.parallel.create_gather_to_zero
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt) output('saving solution...') timer.start() u_i.set_data(sol0_i) out = u_i.create_output() filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank) pb.domain.mesh.write(filename, io='auto', out=out) gather_to_zero = pl.create_gather_to_zero(psol) psol_full = gather_to_zero(psol) if comm.rank == 0: sol = psol_full[...].copy()[id_map] u = FieldVariable('u', 'parameter', field, primary_var_name='(set-to-None)') filename = os.path.join(options.output_dir, 'sol.h5') if (order == 1) or (options.linearization == 'strip'): out = u.create_output(sol) mesh.write(filename, io='auto', out=out) else: out = u.create_output(sol, linearization=Struct(kind='adaptive', min_level=0, max_level=order, eps=1e-3)) out['u'].mesh.write(filename, io='auto', out=out) stats.t_save_solution = timer.stop()
output('...done in', timer.dt)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt) output('saving solution...') timer.start() u_i.set_data(sol0_i) out = u_i.create_output() filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank) pb.domain.mesh.write(filename, io='auto', out=out) gather_to_zero = pl.create_gather_to_zero(psol) psol_full = gather_to_zero(psol) if comm.rank == 0: sol = psol_full[...].copy()[id_map] u = FieldVariable('u', 'parameter', field, primary_var_name='(set-to-None)') filename = os.path.join(options.output_dir, 'sol.h5') if (order == 1) or (options.linearization == 'strip'): out = u.create_output(sol) mesh.write(filename, io='auto', out=out) else: out = u.create_output(sol, linearization=Struct(kind='adaptive', min_level=0, max_level=order, eps=1e-3)) out['u'].mesh.write(filename, io='auto', out=out) stats.t_save_solution = timer.stop() output('...done in', timer.dt) stats.t_total = timer.total stats.n_dof = sizes[1] stats.n_dof_local = sizes[0] stats.n_cell = omega.shape.n_cell stats.n_cell_local = omega_gi.shape.n_cell if options.show: plt.show() return stats def save_stats(filename, pars, stats, overwrite, rank, comm=None): out = stats.to_dict() names = sorted(out.keys()) shape_dict = {'n%d' % ii : pars.shape[ii] for ii in range(pars.dim)} keys = ['size', 'rank', 'dim'] + list(shape_dict.keys()) + ['order'] + names out['size'] = comm.size out['rank'] = rank out['dim'] = pars.dim out.update(shape_dict) out['order'] = pars.order if rank == 0 and overwrite: with open(filename, 'w') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writeheader() writer.writerow(out) else: with open(filename, 'a') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writerow(out) helps = { 'output_dir' : 'output directory', 'dims' : 'dimensions of the block [default: %(default)s]', 'shape' : 'shape (counts of nodes in x, y, z) of the block [default: %(default)s]', 'centre' : 'centre of the block [default: %(default)s]', '2d' : 'generate a 2D rectangle, the third components of the above' ' options are ignored', 'order' : 'field approximation order', 'linearization' : 'linearization used for storing the results with approximation order > 1' ' [default: %(default)s]', 'metis' : 'use metis for domain partitioning', 'verify' : 'verify domain partitioning, save cells and DOFs of tasks' ' for visualization', 'plot' : 'make partitioning plots', 'save_inter_regions' : 'save inter-task regions for debugging partitioning problems', 'show' : 'show partitioning plots (implies --plot)', 'stats_filename' : 'name of the stats file for storing elapsed time statistics', 'new_stats' : 'create a new stats file with a header line (overwrites existing!)', 'silent' : 'do not print messages to screen', 'clear' : 'clear old solution files from output directory' ' (DANGEROUS - use with care!)', } def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--verify', action='store_true', dest='verify', default=False, help=helps['verify']) parser.add_argument('--plot', action='store_true', dest='plot', default=False, help=helps['plot']) parser.add_argument('--show', action='store_true', dest='show', default=False, help=helps['show']) parser.add_argument('--save-inter-regions', action='store_true', dest='save_inter_regions', default=False, help=helps['save_inter_regions']) parser.add_argument('--stats', metavar='filename', action='store', dest='stats_filename', default=None, help=helps['stats_filename']) parser.add_argument('--new-stats', action='store_true', dest='new_stats', default=False, help=helps['new_stats']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() if options.show: options.plot = True comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank
output.set_output(filename=filename, combined=options.silent == False)
sfepy.base.base.output.set_output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt) output('saving solution...') timer.start() u_i.set_data(sol0_i) out = u_i.create_output() filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank) pb.domain.mesh.write(filename, io='auto', out=out) gather_to_zero = pl.create_gather_to_zero(psol) psol_full = gather_to_zero(psol) if comm.rank == 0: sol = psol_full[...].copy()[id_map] u = FieldVariable('u', 'parameter', field, primary_var_name='(set-to-None)') filename = os.path.join(options.output_dir, 'sol.h5') if (order == 1) or (options.linearization == 'strip'): out = u.create_output(sol) mesh.write(filename, io='auto', out=out) else: out = u.create_output(sol, linearization=Struct(kind='adaptive', min_level=0, max_level=order, eps=1e-3)) out['u'].mesh.write(filename, io='auto', out=out) stats.t_save_solution = timer.stop() output('...done in', timer.dt) stats.t_total = timer.total stats.n_dof = sizes[1] stats.n_dof_local = sizes[0] stats.n_cell = omega.shape.n_cell stats.n_cell_local = omega_gi.shape.n_cell if options.show: plt.show() return stats def save_stats(filename, pars, stats, overwrite, rank, comm=None): out = stats.to_dict() names = sorted(out.keys()) shape_dict = {'n%d' % ii : pars.shape[ii] for ii in range(pars.dim)} keys = ['size', 'rank', 'dim'] + list(shape_dict.keys()) + ['order'] + names out['size'] = comm.size out['rank'] = rank out['dim'] = pars.dim out.update(shape_dict) out['order'] = pars.order if rank == 0 and overwrite: with open(filename, 'w') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writeheader() writer.writerow(out) else: with open(filename, 'a') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writerow(out) helps = { 'output_dir' : 'output directory', 'dims' : 'dimensions of the block [default: %(default)s]', 'shape' : 'shape (counts of nodes in x, y, z) of the block [default: %(default)s]', 'centre' : 'centre of the block [default: %(default)s]', '2d' : 'generate a 2D rectangle, the third components of the above' ' options are ignored', 'order' : 'field approximation order', 'linearization' : 'linearization used for storing the results with approximation order > 1' ' [default: %(default)s]', 'metis' : 'use metis for domain partitioning', 'verify' : 'verify domain partitioning, save cells and DOFs of tasks' ' for visualization', 'plot' : 'make partitioning plots', 'save_inter_regions' : 'save inter-task regions for debugging partitioning problems', 'show' : 'show partitioning plots (implies --plot)', 'stats_filename' : 'name of the stats file for storing elapsed time statistics', 'new_stats' : 'create a new stats file with a header line (overwrites existing!)', 'silent' : 'do not print messages to screen', 'clear' : 'clear old solution files from output directory' ' (DANGEROUS - use with care!)', } def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--verify', action='store_true', dest='verify', default=False, help=helps['verify']) parser.add_argument('--plot', action='store_true', dest='plot', default=False, help=helps['plot']) parser.add_argument('--show', action='store_true', dest='show', default=False, help=helps['show']) parser.add_argument('--save-inter-regions', action='store_true', dest='save_inter_regions', default=False, help=helps['save_inter_regions']) parser.add_argument('--stats', metavar='filename', action='store', dest='stats_filename', default=None, help=helps['stats_filename']) parser.add_argument('--new-stats', action='store_true', dest='new_stats', default=False, help=helps['new_stats']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() if options.show: options.plot = True comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank output.set_output(filename=filename, combined=options.silent == False)
output('petsc options:', petsc_opts)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt) output('saving solution...') timer.start() u_i.set_data(sol0_i) out = u_i.create_output() filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank) pb.domain.mesh.write(filename, io='auto', out=out) gather_to_zero = pl.create_gather_to_zero(psol) psol_full = gather_to_zero(psol) if comm.rank == 0: sol = psol_full[...].copy()[id_map] u = FieldVariable('u', 'parameter', field, primary_var_name='(set-to-None)') filename = os.path.join(options.output_dir, 'sol.h5') if (order == 1) or (options.linearization == 'strip'): out = u.create_output(sol) mesh.write(filename, io='auto', out=out) else: out = u.create_output(sol, linearization=Struct(kind='adaptive', min_level=0, max_level=order, eps=1e-3)) out['u'].mesh.write(filename, io='auto', out=out) stats.t_save_solution = timer.stop() output('...done in', timer.dt) stats.t_total = timer.total stats.n_dof = sizes[1] stats.n_dof_local = sizes[0] stats.n_cell = omega.shape.n_cell stats.n_cell_local = omega_gi.shape.n_cell if options.show: plt.show() return stats def save_stats(filename, pars, stats, overwrite, rank, comm=None): out = stats.to_dict() names = sorted(out.keys()) shape_dict = {'n%d' % ii : pars.shape[ii] for ii in range(pars.dim)} keys = ['size', 'rank', 'dim'] + list(shape_dict.keys()) + ['order'] + names out['size'] = comm.size out['rank'] = rank out['dim'] = pars.dim out.update(shape_dict) out['order'] = pars.order if rank == 0 and overwrite: with open(filename, 'w') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writeheader() writer.writerow(out) else: with open(filename, 'a') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writerow(out) helps = { 'output_dir' : 'output directory', 'dims' : 'dimensions of the block [default: %(default)s]', 'shape' : 'shape (counts of nodes in x, y, z) of the block [default: %(default)s]', 'centre' : 'centre of the block [default: %(default)s]', '2d' : 'generate a 2D rectangle, the third components of the above' ' options are ignored', 'order' : 'field approximation order', 'linearization' : 'linearization used for storing the results with approximation order > 1' ' [default: %(default)s]', 'metis' : 'use metis for domain partitioning', 'verify' : 'verify domain partitioning, save cells and DOFs of tasks' ' for visualization', 'plot' : 'make partitioning plots', 'save_inter_regions' : 'save inter-task regions for debugging partitioning problems', 'show' : 'show partitioning plots (implies --plot)', 'stats_filename' : 'name of the stats file for storing elapsed time statistics', 'new_stats' : 'create a new stats file with a header line (overwrites existing!)', 'silent' : 'do not print messages to screen', 'clear' : 'clear old solution files from output directory' ' (DANGEROUS - use with care!)', } def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--verify', action='store_true', dest='verify', default=False, help=helps['verify']) parser.add_argument('--plot', action='store_true', dest='plot', default=False, help=helps['plot']) parser.add_argument('--show', action='store_true', dest='show', default=False, help=helps['show']) parser.add_argument('--save-inter-regions', action='store_true', dest='save_inter_regions', default=False, help=helps['save_inter_regions']) parser.add_argument('--stats', metavar='filename', action='store', dest='stats_filename', default=None, help=helps['stats_filename']) parser.add_argument('--new-stats', action='store_true', dest='new_stats', default=False, help=helps['new_stats']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() if options.show: options.plot = True comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank output.set_output(filename=filename, combined=options.silent == False) output('petsc options:', petsc_opts) mesh_filename = os.path.join(options.output_dir, 'para.h5') dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim]
output('dimensions:', dims)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt) output('saving solution...') timer.start() u_i.set_data(sol0_i) out = u_i.create_output() filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank) pb.domain.mesh.write(filename, io='auto', out=out) gather_to_zero = pl.create_gather_to_zero(psol) psol_full = gather_to_zero(psol) if comm.rank == 0: sol = psol_full[...].copy()[id_map] u = FieldVariable('u', 'parameter', field, primary_var_name='(set-to-None)') filename = os.path.join(options.output_dir, 'sol.h5') if (order == 1) or (options.linearization == 'strip'): out = u.create_output(sol) mesh.write(filename, io='auto', out=out) else: out = u.create_output(sol, linearization=Struct(kind='adaptive', min_level=0, max_level=order, eps=1e-3)) out['u'].mesh.write(filename, io='auto', out=out) stats.t_save_solution = timer.stop() output('...done in', timer.dt) stats.t_total = timer.total stats.n_dof = sizes[1] stats.n_dof_local = sizes[0] stats.n_cell = omega.shape.n_cell stats.n_cell_local = omega_gi.shape.n_cell if options.show: plt.show() return stats def save_stats(filename, pars, stats, overwrite, rank, comm=None): out = stats.to_dict() names = sorted(out.keys()) shape_dict = {'n%d' % ii : pars.shape[ii] for ii in range(pars.dim)} keys = ['size', 'rank', 'dim'] + list(shape_dict.keys()) + ['order'] + names out['size'] = comm.size out['rank'] = rank out['dim'] = pars.dim out.update(shape_dict) out['order'] = pars.order if rank == 0 and overwrite: with open(filename, 'w') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writeheader() writer.writerow(out) else: with open(filename, 'a') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writerow(out) helps = { 'output_dir' : 'output directory', 'dims' : 'dimensions of the block [default: %(default)s]', 'shape' : 'shape (counts of nodes in x, y, z) of the block [default: %(default)s]', 'centre' : 'centre of the block [default: %(default)s]', '2d' : 'generate a 2D rectangle, the third components of the above' ' options are ignored', 'order' : 'field approximation order', 'linearization' : 'linearization used for storing the results with approximation order > 1' ' [default: %(default)s]', 'metis' : 'use metis for domain partitioning', 'verify' : 'verify domain partitioning, save cells and DOFs of tasks' ' for visualization', 'plot' : 'make partitioning plots', 'save_inter_regions' : 'save inter-task regions for debugging partitioning problems', 'show' : 'show partitioning plots (implies --plot)', 'stats_filename' : 'name of the stats file for storing elapsed time statistics', 'new_stats' : 'create a new stats file with a header line (overwrites existing!)', 'silent' : 'do not print messages to screen', 'clear' : 'clear old solution files from output directory' ' (DANGEROUS - use with care!)', } def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--verify', action='store_true', dest='verify', default=False, help=helps['verify']) parser.add_argument('--plot', action='store_true', dest='plot', default=False, help=helps['plot']) parser.add_argument('--show', action='store_true', dest='show', default=False, help=helps['show']) parser.add_argument('--save-inter-regions', action='store_true', dest='save_inter_regions', default=False, help=helps['save_inter_regions']) parser.add_argument('--stats', metavar='filename', action='store', dest='stats_filename', default=None, help=helps['stats_filename']) parser.add_argument('--new-stats', action='store_true', dest='new_stats', default=False, help=helps['new_stats']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() if options.show: options.plot = True comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank output.set_output(filename=filename, combined=options.silent == False) output('petsc options:', petsc_opts) mesh_filename = os.path.join(options.output_dir, 'para.h5') dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output('dimensions:', dims)
output('shape: ', shape)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt) output('saving solution...') timer.start() u_i.set_data(sol0_i) out = u_i.create_output() filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank) pb.domain.mesh.write(filename, io='auto', out=out) gather_to_zero = pl.create_gather_to_zero(psol) psol_full = gather_to_zero(psol) if comm.rank == 0: sol = psol_full[...].copy()[id_map] u = FieldVariable('u', 'parameter', field, primary_var_name='(set-to-None)') filename = os.path.join(options.output_dir, 'sol.h5') if (order == 1) or (options.linearization == 'strip'): out = u.create_output(sol) mesh.write(filename, io='auto', out=out) else: out = u.create_output(sol, linearization=Struct(kind='adaptive', min_level=0, max_level=order, eps=1e-3)) out['u'].mesh.write(filename, io='auto', out=out) stats.t_save_solution = timer.stop() output('...done in', timer.dt) stats.t_total = timer.total stats.n_dof = sizes[1] stats.n_dof_local = sizes[0] stats.n_cell = omega.shape.n_cell stats.n_cell_local = omega_gi.shape.n_cell if options.show: plt.show() return stats def save_stats(filename, pars, stats, overwrite, rank, comm=None): out = stats.to_dict() names = sorted(out.keys()) shape_dict = {'n%d' % ii : pars.shape[ii] for ii in range(pars.dim)} keys = ['size', 'rank', 'dim'] + list(shape_dict.keys()) + ['order'] + names out['size'] = comm.size out['rank'] = rank out['dim'] = pars.dim out.update(shape_dict) out['order'] = pars.order if rank == 0 and overwrite: with open(filename, 'w') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writeheader() writer.writerow(out) else: with open(filename, 'a') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writerow(out) helps = { 'output_dir' : 'output directory', 'dims' : 'dimensions of the block [default: %(default)s]', 'shape' : 'shape (counts of nodes in x, y, z) of the block [default: %(default)s]', 'centre' : 'centre of the block [default: %(default)s]', '2d' : 'generate a 2D rectangle, the third components of the above' ' options are ignored', 'order' : 'field approximation order', 'linearization' : 'linearization used for storing the results with approximation order > 1' ' [default: %(default)s]', 'metis' : 'use metis for domain partitioning', 'verify' : 'verify domain partitioning, save cells and DOFs of tasks' ' for visualization', 'plot' : 'make partitioning plots', 'save_inter_regions' : 'save inter-task regions for debugging partitioning problems', 'show' : 'show partitioning plots (implies --plot)', 'stats_filename' : 'name of the stats file for storing elapsed time statistics', 'new_stats' : 'create a new stats file with a header line (overwrites existing!)', 'silent' : 'do not print messages to screen', 'clear' : 'clear old solution files from output directory' ' (DANGEROUS - use with care!)', } def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--verify', action='store_true', dest='verify', default=False, help=helps['verify']) parser.add_argument('--plot', action='store_true', dest='plot', default=False, help=helps['plot']) parser.add_argument('--show', action='store_true', dest='show', default=False, help=helps['show']) parser.add_argument('--save-inter-regions', action='store_true', dest='save_inter_regions', default=False, help=helps['save_inter_regions']) parser.add_argument('--stats', metavar='filename', action='store', dest='stats_filename', default=None, help=helps['stats_filename']) parser.add_argument('--new-stats', action='store_true', dest='new_stats', default=False, help=helps['new_stats']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() if options.show: options.plot = True comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank output.set_output(filename=filename, combined=options.silent == False) output('petsc options:', petsc_opts) mesh_filename = os.path.join(options.output_dir, 'para.h5') dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output('dimensions:', dims) output('shape: ', shape)
output('centre: ', centre)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt) output('saving solution...') timer.start() u_i.set_data(sol0_i) out = u_i.create_output() filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank) pb.domain.mesh.write(filename, io='auto', out=out) gather_to_zero = pl.create_gather_to_zero(psol) psol_full = gather_to_zero(psol) if comm.rank == 0: sol = psol_full[...].copy()[id_map] u = FieldVariable('u', 'parameter', field, primary_var_name='(set-to-None)') filename = os.path.join(options.output_dir, 'sol.h5') if (order == 1) or (options.linearization == 'strip'): out = u.create_output(sol) mesh.write(filename, io='auto', out=out) else: out = u.create_output(sol, linearization=Struct(kind='adaptive', min_level=0, max_level=order, eps=1e-3)) out['u'].mesh.write(filename, io='auto', out=out) stats.t_save_solution = timer.stop() output('...done in', timer.dt) stats.t_total = timer.total stats.n_dof = sizes[1] stats.n_dof_local = sizes[0] stats.n_cell = omega.shape.n_cell stats.n_cell_local = omega_gi.shape.n_cell if options.show: plt.show() return stats def save_stats(filename, pars, stats, overwrite, rank, comm=None): out = stats.to_dict() names = sorted(out.keys()) shape_dict = {'n%d' % ii : pars.shape[ii] for ii in range(pars.dim)} keys = ['size', 'rank', 'dim'] + list(shape_dict.keys()) + ['order'] + names out['size'] = comm.size out['rank'] = rank out['dim'] = pars.dim out.update(shape_dict) out['order'] = pars.order if rank == 0 and overwrite: with open(filename, 'w') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writeheader() writer.writerow(out) else: with open(filename, 'a') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writerow(out) helps = { 'output_dir' : 'output directory', 'dims' : 'dimensions of the block [default: %(default)s]', 'shape' : 'shape (counts of nodes in x, y, z) of the block [default: %(default)s]', 'centre' : 'centre of the block [default: %(default)s]', '2d' : 'generate a 2D rectangle, the third components of the above' ' options are ignored', 'order' : 'field approximation order', 'linearization' : 'linearization used for storing the results with approximation order > 1' ' [default: %(default)s]', 'metis' : 'use metis for domain partitioning', 'verify' : 'verify domain partitioning, save cells and DOFs of tasks' ' for visualization', 'plot' : 'make partitioning plots', 'save_inter_regions' : 'save inter-task regions for debugging partitioning problems', 'show' : 'show partitioning plots (implies --plot)', 'stats_filename' : 'name of the stats file for storing elapsed time statistics', 'new_stats' : 'create a new stats file with a header line (overwrites existing!)', 'silent' : 'do not print messages to screen', 'clear' : 'clear old solution files from output directory' ' (DANGEROUS - use with care!)', } def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--verify', action='store_true', dest='verify', default=False, help=helps['verify']) parser.add_argument('--plot', action='store_true', dest='plot', default=False, help=helps['plot']) parser.add_argument('--show', action='store_true', dest='show', default=False, help=helps['show']) parser.add_argument('--save-inter-regions', action='store_true', dest='save_inter_regions', default=False, help=helps['save_inter_regions']) parser.add_argument('--stats', metavar='filename', action='store', dest='stats_filename', default=None, help=helps['stats_filename']) parser.add_argument('--new-stats', action='store_true', dest='new_stats', default=False, help=helps['new_stats']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() if options.show: options.plot = True comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank output.set_output(filename=filename, combined=options.silent == False) output('petsc options:', petsc_opts) mesh_filename = os.path.join(options.output_dir, 'para.h5') dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output('dimensions:', dims) output('shape: ', shape) output('centre: ', centre) if comm.rank == 0: from sfepy.mesh.mesh_generators import gen_block_mesh if options.clear: remove_files_patterns(output_dir, ['*.h5', '*.mesh', '*.txt', '*.png'], ignores=['output_log_%02d.txt' % ii for ii in range(comm.size)], verbose=True) save_options(os.path.join(output_dir, 'options.txt'), [('options', vars(options))]) mesh = gen_block_mesh(dims, shape, centre, name='block-fem', verbose=True) mesh.write(mesh_filename, io='auto') comm.barrier()
output('field order:', options.order)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt) output('saving solution...') timer.start() u_i.set_data(sol0_i) out = u_i.create_output() filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank) pb.domain.mesh.write(filename, io='auto', out=out) gather_to_zero = pl.create_gather_to_zero(psol) psol_full = gather_to_zero(psol) if comm.rank == 0: sol = psol_full[...].copy()[id_map] u = FieldVariable('u', 'parameter', field, primary_var_name='(set-to-None)') filename = os.path.join(options.output_dir, 'sol.h5') if (order == 1) or (options.linearization == 'strip'): out = u.create_output(sol) mesh.write(filename, io='auto', out=out) else: out = u.create_output(sol, linearization=Struct(kind='adaptive', min_level=0, max_level=order, eps=1e-3)) out['u'].mesh.write(filename, io='auto', out=out) stats.t_save_solution = timer.stop() output('...done in', timer.dt) stats.t_total = timer.total stats.n_dof = sizes[1] stats.n_dof_local = sizes[0] stats.n_cell = omega.shape.n_cell stats.n_cell_local = omega_gi.shape.n_cell if options.show: plt.show() return stats def save_stats(filename, pars, stats, overwrite, rank, comm=None): out = stats.to_dict() names = sorted(out.keys()) shape_dict = {'n%d' % ii : pars.shape[ii] for ii in range(pars.dim)} keys = ['size', 'rank', 'dim'] + list(shape_dict.keys()) + ['order'] + names out['size'] = comm.size out['rank'] = rank out['dim'] = pars.dim out.update(shape_dict) out['order'] = pars.order if rank == 0 and overwrite: with open(filename, 'w') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writeheader() writer.writerow(out) else: with open(filename, 'a') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writerow(out) helps = { 'output_dir' : 'output directory', 'dims' : 'dimensions of the block [default: %(default)s]', 'shape' : 'shape (counts of nodes in x, y, z) of the block [default: %(default)s]', 'centre' : 'centre of the block [default: %(default)s]', '2d' : 'generate a 2D rectangle, the third components of the above' ' options are ignored', 'order' : 'field approximation order', 'linearization' : 'linearization used for storing the results with approximation order > 1' ' [default: %(default)s]', 'metis' : 'use metis for domain partitioning', 'verify' : 'verify domain partitioning, save cells and DOFs of tasks' ' for visualization', 'plot' : 'make partitioning plots', 'save_inter_regions' : 'save inter-task regions for debugging partitioning problems', 'show' : 'show partitioning plots (implies --plot)', 'stats_filename' : 'name of the stats file for storing elapsed time statistics', 'new_stats' : 'create a new stats file with a header line (overwrites existing!)', 'silent' : 'do not print messages to screen', 'clear' : 'clear old solution files from output directory' ' (DANGEROUS - use with care!)', } def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--verify', action='store_true', dest='verify', default=False, help=helps['verify']) parser.add_argument('--plot', action='store_true', dest='plot', default=False, help=helps['plot']) parser.add_argument('--show', action='store_true', dest='show', default=False, help=helps['show']) parser.add_argument('--save-inter-regions', action='store_true', dest='save_inter_regions', default=False, help=helps['save_inter_regions']) parser.add_argument('--stats', metavar='filename', action='store', dest='stats_filename', default=None, help=helps['stats_filename']) parser.add_argument('--new-stats', action='store_true', dest='new_stats', default=False, help=helps['new_stats']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() if options.show: options.plot = True comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank output.set_output(filename=filename, combined=options.silent == False) output('petsc options:', petsc_opts) mesh_filename = os.path.join(options.output_dir, 'para.h5') dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output('dimensions:', dims) output('shape: ', shape) output('centre: ', centre) if comm.rank == 0: from sfepy.mesh.mesh_generators import gen_block_mesh if options.clear: remove_files_patterns(output_dir, ['*.h5', '*.mesh', '*.txt', '*.png'], ignores=['output_log_%02d.txt' % ii for ii in range(comm.size)], verbose=True) save_options(os.path.join(output_dir, 'options.txt'), [('options', vars(options))]) mesh = gen_block_mesh(dims, shape, centre, name='block-fem', verbose=True) mesh.write(mesh_filename, io='auto') comm.barrier() output('field order:', options.order) stats = solve_problem(mesh_filename, options, comm)
output(stats)
sfepy.base.base.output
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt) output('saving solution...') timer.start() u_i.set_data(sol0_i) out = u_i.create_output() filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank) pb.domain.mesh.write(filename, io='auto', out=out) gather_to_zero = pl.create_gather_to_zero(psol) psol_full = gather_to_zero(psol) if comm.rank == 0: sol = psol_full[...].copy()[id_map] u = FieldVariable('u', 'parameter', field, primary_var_name='(set-to-None)') filename = os.path.join(options.output_dir, 'sol.h5') if (order == 1) or (options.linearization == 'strip'): out = u.create_output(sol) mesh.write(filename, io='auto', out=out) else: out = u.create_output(sol, linearization=Struct(kind='adaptive', min_level=0, max_level=order, eps=1e-3)) out['u'].mesh.write(filename, io='auto', out=out) stats.t_save_solution = timer.stop() output('...done in', timer.dt) stats.t_total = timer.total stats.n_dof = sizes[1] stats.n_dof_local = sizes[0] stats.n_cell = omega.shape.n_cell stats.n_cell_local = omega_gi.shape.n_cell if options.show: plt.show() return stats def save_stats(filename, pars, stats, overwrite, rank, comm=None): out = stats.to_dict() names = sorted(out.keys()) shape_dict = {'n%d' % ii : pars.shape[ii] for ii in range(pars.dim)} keys = ['size', 'rank', 'dim'] + list(shape_dict.keys()) + ['order'] + names out['size'] = comm.size out['rank'] = rank out['dim'] = pars.dim out.update(shape_dict) out['order'] = pars.order if rank == 0 and overwrite: with open(filename, 'w') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writeheader() writer.writerow(out) else: with open(filename, 'a') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writerow(out) helps = { 'output_dir' : 'output directory', 'dims' : 'dimensions of the block [default: %(default)s]', 'shape' : 'shape (counts of nodes in x, y, z) of the block [default: %(default)s]', 'centre' : 'centre of the block [default: %(default)s]', '2d' : 'generate a 2D rectangle, the third components of the above' ' options are ignored', 'order' : 'field approximation order', 'linearization' : 'linearization used for storing the results with approximation order > 1' ' [default: %(default)s]', 'metis' : 'use metis for domain partitioning', 'verify' : 'verify domain partitioning, save cells and DOFs of tasks' ' for visualization', 'plot' : 'make partitioning plots', 'save_inter_regions' : 'save inter-task regions for debugging partitioning problems', 'show' : 'show partitioning plots (implies --plot)', 'stats_filename' : 'name of the stats file for storing elapsed time statistics', 'new_stats' : 'create a new stats file with a header line (overwrites existing!)', 'silent' : 'do not print messages to screen', 'clear' : 'clear old solution files from output directory' ' (DANGEROUS - use with care!)', } def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--verify', action='store_true', dest='verify', default=False, help=helps['verify']) parser.add_argument('--plot', action='store_true', dest='plot', default=False, help=helps['plot']) parser.add_argument('--show', action='store_true', dest='show', default=False, help=helps['show']) parser.add_argument('--save-inter-regions', action='store_true', dest='save_inter_regions', default=False, help=helps['save_inter_regions']) parser.add_argument('--stats', metavar='filename', action='store', dest='stats_filename', default=None, help=helps['stats_filename']) parser.add_argument('--new-stats', action='store_true', dest='new_stats', default=False, help=helps['new_stats']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() if options.show: options.plot = True comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0:
ensure_path(filename)
sfepy.base.ioutils.ensure_path
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt) output('saving solution...') timer.start() u_i.set_data(sol0_i) out = u_i.create_output() filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank) pb.domain.mesh.write(filename, io='auto', out=out) gather_to_zero = pl.create_gather_to_zero(psol) psol_full = gather_to_zero(psol) if comm.rank == 0: sol = psol_full[...].copy()[id_map] u = FieldVariable('u', 'parameter', field, primary_var_name='(set-to-None)') filename = os.path.join(options.output_dir, 'sol.h5') if (order == 1) or (options.linearization == 'strip'): out = u.create_output(sol) mesh.write(filename, io='auto', out=out) else: out = u.create_output(sol, linearization=Struct(kind='adaptive', min_level=0, max_level=order, eps=1e-3)) out['u'].mesh.write(filename, io='auto', out=out) stats.t_save_solution = timer.stop() output('...done in', timer.dt) stats.t_total = timer.total stats.n_dof = sizes[1] stats.n_dof_local = sizes[0] stats.n_cell = omega.shape.n_cell stats.n_cell_local = omega_gi.shape.n_cell if options.show: plt.show() return stats def save_stats(filename, pars, stats, overwrite, rank, comm=None): out = stats.to_dict() names = sorted(out.keys()) shape_dict = {'n%d' % ii : pars.shape[ii] for ii in range(pars.dim)} keys = ['size', 'rank', 'dim'] + list(shape_dict.keys()) + ['order'] + names out['size'] = comm.size out['rank'] = rank out['dim'] = pars.dim out.update(shape_dict) out['order'] = pars.order if rank == 0 and overwrite: with open(filename, 'w') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writeheader() writer.writerow(out) else: with open(filename, 'a') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writerow(out) helps = { 'output_dir' : 'output directory', 'dims' : 'dimensions of the block [default: %(default)s]', 'shape' : 'shape (counts of nodes in x, y, z) of the block [default: %(default)s]', 'centre' : 'centre of the block [default: %(default)s]', '2d' : 'generate a 2D rectangle, the third components of the above' ' options are ignored', 'order' : 'field approximation order', 'linearization' : 'linearization used for storing the results with approximation order > 1' ' [default: %(default)s]', 'metis' : 'use metis for domain partitioning', 'verify' : 'verify domain partitioning, save cells and DOFs of tasks' ' for visualization', 'plot' : 'make partitioning plots', 'save_inter_regions' : 'save inter-task regions for debugging partitioning problems', 'show' : 'show partitioning plots (implies --plot)', 'stats_filename' : 'name of the stats file for storing elapsed time statistics', 'new_stats' : 'create a new stats file with a header line (overwrites existing!)', 'silent' : 'do not print messages to screen', 'clear' : 'clear old solution files from output directory' ' (DANGEROUS - use with care!)', } def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--verify', action='store_true', dest='verify', default=False, help=helps['verify']) parser.add_argument('--plot', action='store_true', dest='plot', default=False, help=helps['plot']) parser.add_argument('--show', action='store_true', dest='show', default=False, help=helps['show']) parser.add_argument('--save-inter-regions', action='store_true', dest='save_inter_regions', default=False, help=helps['save_inter_regions']) parser.add_argument('--stats', metavar='filename', action='store', dest='stats_filename', default=None, help=helps['stats_filename']) parser.add_argument('--new-stats', action='store_true', dest='new_stats', default=False, help=helps['new_stats']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() if options.show: options.plot = True comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank output.set_output(filename=filename, combined=options.silent == False) output('petsc options:', petsc_opts) mesh_filename = os.path.join(options.output_dir, 'para.h5') dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output('dimensions:', dims) output('shape: ', shape) output('centre: ', centre) if comm.rank == 0: from sfepy.mesh.mesh_generators import gen_block_mesh if options.clear: remove_files_patterns(output_dir, ['*.h5', '*.mesh', '*.txt', '*.png'], ignores=['output_log_%02d.txt' % ii for ii in range(comm.size)], verbose=True) save_options(os.path.join(output_dir, 'options.txt'), [('options', vars(options))]) mesh = gen_block_mesh(dims, shape, centre, name='block-fem', verbose=True) mesh.write(mesh_filename, io='auto') comm.barrier() output('field order:', options.order) stats = solve_problem(mesh_filename, options, comm) output(stats) if options.stats_filename: if comm.rank == 0: ensure_path(options.stats_filename) comm.barrier() pars =
Struct(dim=dim, shape=shape, order=options.order)
sfepy.base.base.Struct
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=
Function('get_load', get_load)
sfepy.discrete.Function
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=
Conditions([ebc1, ebc2])
sfepy.discrete.conditions.Conditions
#!/usr/bin/env python r""" Parallel assembling and solving of a Poisson's equation, using commands for interactive use. Find :math:`u` such that: .. math:: \int_{\Omega} \nabla v \cdot \nabla u = \int_{\Omega} v f \;, \quad \forall s \;. Important Notes --------------- - This example requires petsc4py, mpi4py and (optionally) pymetis with their dependencies installed! - This example generates a number of files - do not use an existing non-empty directory for the ``output_dir`` argument. - Use the ``--clear`` option with care! Notes ----- - Each task is responsible for a subdomain consisting of a set of cells (a cell region). - Each subdomain owns PETSc DOFs within a consecutive range. - When both global and task-local variables exist, the task-local variables have ``_i`` suffix. - This example does not use a nonlinear solver. - This example can serve as a template for solving a linear single-field scalar problem - just replace the equations in :func:`create_local_problem()`. - The command line options are saved into <output_dir>/options.txt file. Usage Examples -------------- See all options:: $ python examples/diffusion/poisson_parallel_interactive.py -h See PETSc options:: $ python examples/diffusion/poisson_parallel_interactive.py -help Single process run useful for debugging with :func:`debug() <sfepy.base.base.debug>`:: $ python examples/diffusion/poisson_parallel_interactive.py output-parallel Parallel runs:: $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 $ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis $ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason View the results using:: $ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar' """ from __future__ import absolute_import from argparse import RawDescriptionHelpFormatter, ArgumentParser import os import sys sys.path.append('.') import csv import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output, Struct from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.timing import Timer from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.discrete.common.region import Region from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.evaluate import apply_ebc_to_matrix from sfepy.terms import Term from sfepy.solvers.ls import PETScKrylovSolver import sfepy.parallel.parallel as pl import sfepy.parallel.plot_parallel_dofs as ppd def create_local_problem(omega_gi, order): """ Local problem definition using a domain corresponding to the global region `omega_gi`. """ mesh = omega_gi.domain.mesh # All tasks have the whole mesh. bbox = mesh.get_bounding_box() min_x, max_x = bbox[:, 0] eps_x = 1e-8 * (max_x - min_x) mesh_i = Mesh.from_region(omega_gi, mesh, localize=True) domain_i = FEDomain('domain_i', mesh_i) omega_i = domain_i.create_region('Omega', 'all') gamma1_i = domain_i.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps_x), 'facet', allow_empty=True) gamma2_i = domain_i.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps_x), 'facet', allow_empty=True) field_i = Field.from_args('fu', nm.float64, 1, omega_i, approx_order=order) output('number of local field DOFs:', field_i.n_nod) u_i = FieldVariable('u_i', 'unknown', field_i) v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i') integral = Integral('i', order=2*order) mat = Material('m', lam=10, mu=5) t1 = Term.new('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i, u_i=u_i) def _get_load(coors): val = nm.ones_like(coors[:, 0]) for coor in coors.T: val *= nm.sin(4 * nm.pi * coor) return val def get_load(ts, coors, mode=None, **kwargs): if mode == 'qp': return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)} load = Material('load', function=Function('get_load', get_load)) t2 = Term.new('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i) eq = Equation('balance', t1 - 100 * t2) eqs = Equations([eq]) ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0}) ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1}) pb = Problem('problem_i', equations=eqs, active_only=False) pb.time_update(ebcs=Conditions([ebc1, ebc2])) pb.update_materials() return pb def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=False): vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose) order = options.order mesh = field.domain.mesh sfield = Field.from_args('aux', nm.float64, 'scalar', field.region, approx_order=order) aux = FieldVariable('aux', 'parameter', sfield, primary_var_name='(set-to-None)') out = aux.create_output(vec, linearization=Struct(kind='adaptive', min_level=order-1, max_level=order-1, eps=1e-8)) filename = os.path.join(options.output_dir, 'para-domains-dofs.h5') if field.is_higher_order(): out['aux'].mesh.write(filename, out=out) else: mesh.write(filename, out=out) out = Struct(name='cells', mode='cell', data=cell_tasks[:, None, None, None]) filename = os.path.join(options.output_dir, 'para-domains-cells.h5') mesh.write(filename, out={'cells' : out}) def solve_problem(mesh_filename, options, comm): order = options.order rank, size = comm.Get_rank(), comm.Get_size() output('rank', rank, 'of', size) stats = Struct() timer = Timer('solve_timer') timer.start() mesh = Mesh.from_file(mesh_filename) stats.t_read_mesh = timer.stop() timer.start() if rank == 0: cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis, verbose=True) else: cell_tasks = None stats.t_partition_mesh = timer.stop() output('creating global domain and field...') timer.start() domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) stats.t_create_global_fields = timer.stop() output('...done in', timer.dt) output('distributing field %s...' % field.name) timer.start() distribute = pl.distribute_fields_dofs lfds, gfds = distribute([field], cell_tasks, is_overlap=True, save_inter_regions=options.save_inter_regions, output_dir=options.output_dir, comm=comm, verbose=True) lfd = lfds[0] stats.t_distribute_fields_dofs = timer.stop() output('...done in', timer.dt) if rank == 0: dof_maps = gfds[0].dof_maps id_map = gfds[0].id_map if options.verify: verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options, verbose=True) if options.plot: ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0], options.output_dir, size) output('creating local problem...') timer.start() omega_gi = Region.from_cells(lfd.cells, field.domain) omega_gi.finalize() omega_gi.update_shape() pb = create_local_problem(omega_gi, order) variables = pb.get_variables() eqs = pb.equations u_i = variables['u_i'] field_i = u_i.field stats.t_create_local_problem = timer.stop() output('...done in', timer.dt) if options.plot: ppd.plot_local_dofs([None, None], field, field_i, omega_gi, options.output_dir, rank) output('allocating global system...') timer.start() sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1) output('sizes:', sizes) output('drange:', drange) pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn) output('pdofs:', pdofs) pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_allocate_global_system = timer.stop() output('...done in', timer.dt) output('evaluating local problem...') timer.start() state = State(variables) state.fill(0.0) state.apply_ebc() rhs_i = eqs.eval_residuals(state()) # This must be after pl.create_petsc_system() call! mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a) stats.t_evaluate_local_problem = timer.stop() output('...done in', timer.dt) output('assembling global system...') timer.start() apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc) pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=comm, verbose=True) stats.t_assemble_global_system = timer.stop() output('...done in', timer.dt) output('creating solver...') timer.start() conf = Struct(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) status = {} ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status) stats.t_create_solver = timer.stop() output('...done in', timer.dt) output('solving...') timer.start() psol = ls(prhs, psol) psol_i = pl.create_local_petsc_vector(pdofs) gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm) scatter(psol_i, psol) sol0_i = state() - psol_i[...] psol_i[...] = sol0_i gather(psol, psol_i) stats.t_solve = timer.stop() output('...done in', timer.dt) output('saving solution...') timer.start() u_i.set_data(sol0_i) out = u_i.create_output() filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank) pb.domain.mesh.write(filename, io='auto', out=out) gather_to_zero = pl.create_gather_to_zero(psol) psol_full = gather_to_zero(psol) if comm.rank == 0: sol = psol_full[...].copy()[id_map] u = FieldVariable('u', 'parameter', field, primary_var_name='(set-to-None)') filename = os.path.join(options.output_dir, 'sol.h5') if (order == 1) or (options.linearization == 'strip'): out = u.create_output(sol) mesh.write(filename, io='auto', out=out) else: out = u.create_output(sol, linearization=Struct(kind='adaptive', min_level=0, max_level=order, eps=1e-3)) out['u'].mesh.write(filename, io='auto', out=out) stats.t_save_solution = timer.stop() output('...done in', timer.dt) stats.t_total = timer.total stats.n_dof = sizes[1] stats.n_dof_local = sizes[0] stats.n_cell = omega.shape.n_cell stats.n_cell_local = omega_gi.shape.n_cell if options.show: plt.show() return stats def save_stats(filename, pars, stats, overwrite, rank, comm=None): out = stats.to_dict() names = sorted(out.keys()) shape_dict = {'n%d' % ii : pars.shape[ii] for ii in range(pars.dim)} keys = ['size', 'rank', 'dim'] + list(shape_dict.keys()) + ['order'] + names out['size'] = comm.size out['rank'] = rank out['dim'] = pars.dim out.update(shape_dict) out['order'] = pars.order if rank == 0 and overwrite: with open(filename, 'w') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writeheader() writer.writerow(out) else: with open(filename, 'a') as fd: writer = csv.DictWriter(fd, fieldnames=keys) writer.writerow(out) helps = { 'output_dir' : 'output directory', 'dims' : 'dimensions of the block [default: %(default)s]', 'shape' : 'shape (counts of nodes in x, y, z) of the block [default: %(default)s]', 'centre' : 'centre of the block [default: %(default)s]', '2d' : 'generate a 2D rectangle, the third components of the above' ' options are ignored', 'order' : 'field approximation order', 'linearization' : 'linearization used for storing the results with approximation order > 1' ' [default: %(default)s]', 'metis' : 'use metis for domain partitioning', 'verify' : 'verify domain partitioning, save cells and DOFs of tasks' ' for visualization', 'plot' : 'make partitioning plots', 'save_inter_regions' : 'save inter-task regions for debugging partitioning problems', 'show' : 'show partitioning plots (implies --plot)', 'stats_filename' : 'name of the stats file for storing elapsed time statistics', 'new_stats' : 'create a new stats file with a header line (overwrites existing!)', 'silent' : 'do not print messages to screen', 'clear' : 'clear old solution files from output directory' ' (DANGEROUS - use with care!)', } def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--verify', action='store_true', dest='verify', default=False, help=helps['verify']) parser.add_argument('--plot', action='store_true', dest='plot', default=False, help=helps['plot']) parser.add_argument('--show', action='store_true', dest='show', default=False, help=helps['show']) parser.add_argument('--save-inter-regions', action='store_true', dest='save_inter_regions', default=False, help=helps['save_inter_regions']) parser.add_argument('--stats', metavar='filename', action='store', dest='stats_filename', default=None, help=helps['stats_filename']) parser.add_argument('--new-stats', action='store_true', dest='new_stats', default=False, help=helps['new_stats']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() if options.show: options.plot = True comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank output.set_output(filename=filename, combined=options.silent == False) output('petsc options:', petsc_opts) mesh_filename = os.path.join(options.output_dir, 'para.h5') dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output('dimensions:', dims) output('shape: ', shape) output('centre: ', centre) if comm.rank == 0: from sfepy.mesh.mesh_generators import gen_block_mesh if options.clear: remove_files_patterns(output_dir, ['*.h5', '*.mesh', '*.txt', '*.png'], ignores=['output_log_%02d.txt' % ii for ii in range(comm.size)], verbose=True) save_options(os.path.join(output_dir, 'options.txt'), [('options', vars(options))]) mesh = gen_block_mesh(dims, shape, centre, name='block-fem', verbose=True) mesh.write(mesh_filename, io='auto') comm.barrier() output('field order:', options.order) stats = solve_problem(mesh_filename, options, comm) output(stats) if options.stats_filename: if comm.rank == 0:
ensure_path(options.stats_filename)
sfepy.base.ioutils.ensure_path
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain =
FEDomain('domain', mesh)
sfepy.discrete.fem.FEDomain
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions =
define_box_regions(3, lbn, rtf)
sfepy.homogenization.utils.define_box_regions
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u =
FieldVariable('u', 'unknown', vector_field, history=1)
sfepy.discrete.FieldVariable
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v =
FieldVariable('v', 'test', vector_field, primary_var_name='u')
sfepy.discrete.FieldVariable
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p =
FieldVariable('p', 'unknown', scalar_field, history=1)
sfepy.discrete.FieldVariable
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p = FieldVariable('p', 'unknown', scalar_field, history=1) q =
FieldVariable('q', 'test', scalar_field, primary_var_name='p')
sfepy.discrete.FieldVariable
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p = FieldVariable('p', 'unknown', scalar_field, history=1) q = FieldVariable('q', 'test', scalar_field, primary_var_name='p') ### Material ### coefficient, exponent = material_parameters m_1 = Material( 'm1', par=[coefficient, exponent], ) ### Boundary conditions ### x_sym = EssentialBC('x_sym', regions['Left'], {'u.0' : 0.0}) y_sym = EssentialBC('y_sym', regions['Near'], {'u.1' : 0.0}) z_sym = EssentialBC('z_sym', regions['Bottom'], {'u.2' : 0.0}) disp_fun =
Function('disp_fun', get_displacement)
sfepy.discrete.Function
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p = FieldVariable('p', 'unknown', scalar_field, history=1) q = FieldVariable('q', 'test', scalar_field, primary_var_name='p') ### Material ### coefficient, exponent = material_parameters m_1 = Material( 'm1', par=[coefficient, exponent], ) ### Boundary conditions ### x_sym = EssentialBC('x_sym', regions['Left'], {'u.0' : 0.0}) y_sym = EssentialBC('y_sym', regions['Near'], {'u.1' : 0.0}) z_sym = EssentialBC('z_sym', regions['Bottom'], {'u.2' : 0.0}) disp_fun = Function('disp_fun', get_displacement) displacement = EssentialBC( 'displacement', regions['Right'], {'u.0' : disp_fun}) ebcs =
Conditions([x_sym, y_sym, z_sym, displacement])
sfepy.discrete.conditions.Conditions
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p = FieldVariable('p', 'unknown', scalar_field, history=1) q = FieldVariable('q', 'test', scalar_field, primary_var_name='p') ### Material ### coefficient, exponent = material_parameters m_1 = Material( 'm1', par=[coefficient, exponent], ) ### Boundary conditions ### x_sym = EssentialBC('x_sym', regions['Left'], {'u.0' : 0.0}) y_sym = EssentialBC('y_sym', regions['Near'], {'u.1' : 0.0}) z_sym = EssentialBC('z_sym', regions['Bottom'], {'u.2' : 0.0}) disp_fun = Function('disp_fun', get_displacement) displacement = EssentialBC( 'displacement', regions['Right'], {'u.0' : disp_fun}) ebcs = Conditions([x_sym, y_sym, z_sym, displacement]) ### Terms and equations ### integral =
Integral('i', order=2*order+1)
sfepy.discrete.Integral
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p = FieldVariable('p', 'unknown', scalar_field, history=1) q = FieldVariable('q', 'test', scalar_field, primary_var_name='p') ### Material ### coefficient, exponent = material_parameters m_1 = Material( 'm1', par=[coefficient, exponent], ) ### Boundary conditions ### x_sym = EssentialBC('x_sym', regions['Left'], {'u.0' : 0.0}) y_sym = EssentialBC('y_sym', regions['Near'], {'u.1' : 0.0}) z_sym = EssentialBC('z_sym', regions['Bottom'], {'u.2' : 0.0}) disp_fun = Function('disp_fun', get_displacement) displacement = EssentialBC( 'displacement', regions['Right'], {'u.0' : disp_fun}) ebcs = Conditions([x_sym, y_sym, z_sym, displacement]) ### Terms and equations ### integral = Integral('i', order=2*order+1) term_1 = Term.new( 'dw_tl_he_genyeoh(m1.par, v, u)', integral, omega, m1=m_1, v=v, u=u) term_pressure = Term.new( 'dw_tl_bulk_pressure(v, u, p)', integral, omega, v=v, u=u, p=p) term_volume_change = Term.new( 'dw_tl_volume(q, u)', integral, omega, q=q, u=u, term_mode='volume') term_volume = Term.new( 'dw_volume_integrate(q)', integral, omega, q=q) eq_balance =
Equation('balance', term_1 + term_pressure)
sfepy.discrete.Equation
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p = FieldVariable('p', 'unknown', scalar_field, history=1) q = FieldVariable('q', 'test', scalar_field, primary_var_name='p') ### Material ### coefficient, exponent = material_parameters m_1 = Material( 'm1', par=[coefficient, exponent], ) ### Boundary conditions ### x_sym = EssentialBC('x_sym', regions['Left'], {'u.0' : 0.0}) y_sym = EssentialBC('y_sym', regions['Near'], {'u.1' : 0.0}) z_sym = EssentialBC('z_sym', regions['Bottom'], {'u.2' : 0.0}) disp_fun = Function('disp_fun', get_displacement) displacement = EssentialBC( 'displacement', regions['Right'], {'u.0' : disp_fun}) ebcs = Conditions([x_sym, y_sym, z_sym, displacement]) ### Terms and equations ### integral = Integral('i', order=2*order+1) term_1 = Term.new( 'dw_tl_he_genyeoh(m1.par, v, u)', integral, omega, m1=m_1, v=v, u=u) term_pressure = Term.new( 'dw_tl_bulk_pressure(v, u, p)', integral, omega, v=v, u=u, p=p) term_volume_change = Term.new( 'dw_tl_volume(q, u)', integral, omega, q=q, u=u, term_mode='volume') term_volume = Term.new( 'dw_volume_integrate(q)', integral, omega, q=q) eq_balance = Equation('balance', term_1 + term_pressure) eq_volume =
Equation('volume', term_volume_change - term_volume)
sfepy.discrete.Equation
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p = FieldVariable('p', 'unknown', scalar_field, history=1) q = FieldVariable('q', 'test', scalar_field, primary_var_name='p') ### Material ### coefficient, exponent = material_parameters m_1 = Material( 'm1', par=[coefficient, exponent], ) ### Boundary conditions ### x_sym = EssentialBC('x_sym', regions['Left'], {'u.0' : 0.0}) y_sym = EssentialBC('y_sym', regions['Near'], {'u.1' : 0.0}) z_sym = EssentialBC('z_sym', regions['Bottom'], {'u.2' : 0.0}) disp_fun = Function('disp_fun', get_displacement) displacement = EssentialBC( 'displacement', regions['Right'], {'u.0' : disp_fun}) ebcs = Conditions([x_sym, y_sym, z_sym, displacement]) ### Terms and equations ### integral = Integral('i', order=2*order+1) term_1 = Term.new( 'dw_tl_he_genyeoh(m1.par, v, u)', integral, omega, m1=m_1, v=v, u=u) term_pressure = Term.new( 'dw_tl_bulk_pressure(v, u, p)', integral, omega, v=v, u=u, p=p) term_volume_change = Term.new( 'dw_tl_volume(q, u)', integral, omega, q=q, u=u, term_mode='volume') term_volume = Term.new( 'dw_volume_integrate(q)', integral, omega, q=q) eq_balance = Equation('balance', term_1 + term_pressure) eq_volume = Equation('volume', term_volume_change - term_volume) equations =
Equations([eq_balance, eq_volume])
sfepy.discrete.Equations
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p = FieldVariable('p', 'unknown', scalar_field, history=1) q = FieldVariable('q', 'test', scalar_field, primary_var_name='p') ### Material ### coefficient, exponent = material_parameters m_1 = Material( 'm1', par=[coefficient, exponent], ) ### Boundary conditions ### x_sym = EssentialBC('x_sym', regions['Left'], {'u.0' : 0.0}) y_sym = EssentialBC('y_sym', regions['Near'], {'u.1' : 0.0}) z_sym = EssentialBC('z_sym', regions['Bottom'], {'u.2' : 0.0}) disp_fun = Function('disp_fun', get_displacement) displacement = EssentialBC( 'displacement', regions['Right'], {'u.0' : disp_fun}) ebcs = Conditions([x_sym, y_sym, z_sym, displacement]) ### Terms and equations ### integral = Integral('i', order=2*order+1) term_1 = Term.new( 'dw_tl_he_genyeoh(m1.par, v, u)', integral, omega, m1=m_1, v=v, u=u) term_pressure = Term.new( 'dw_tl_bulk_pressure(v, u, p)', integral, omega, v=v, u=u, p=p) term_volume_change = Term.new( 'dw_tl_volume(q, u)', integral, omega, q=q, u=u, term_mode='volume') term_volume = Term.new( 'dw_volume_integrate(q)', integral, omega, q=q) eq_balance = Equation('balance', term_1 + term_pressure) eq_volume = Equation('volume', term_volume_change - term_volume) equations = Equations([eq_balance, eq_volume]) ### Solvers ### ls =
ScipyDirect({})
sfepy.solvers.ls.ScipyDirect
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p = FieldVariable('p', 'unknown', scalar_field, history=1) q = FieldVariable('q', 'test', scalar_field, primary_var_name='p') ### Material ### coefficient, exponent = material_parameters m_1 = Material( 'm1', par=[coefficient, exponent], ) ### Boundary conditions ### x_sym = EssentialBC('x_sym', regions['Left'], {'u.0' : 0.0}) y_sym = EssentialBC('y_sym', regions['Near'], {'u.1' : 0.0}) z_sym = EssentialBC('z_sym', regions['Bottom'], {'u.2' : 0.0}) disp_fun = Function('disp_fun', get_displacement) displacement = EssentialBC( 'displacement', regions['Right'], {'u.0' : disp_fun}) ebcs = Conditions([x_sym, y_sym, z_sym, displacement]) ### Terms and equations ### integral = Integral('i', order=2*order+1) term_1 = Term.new( 'dw_tl_he_genyeoh(m1.par, v, u)', integral, omega, m1=m_1, v=v, u=u) term_pressure = Term.new( 'dw_tl_bulk_pressure(v, u, p)', integral, omega, v=v, u=u, p=p) term_volume_change = Term.new( 'dw_tl_volume(q, u)', integral, omega, q=q, u=u, term_mode='volume') term_volume = Term.new( 'dw_volume_integrate(q)', integral, omega, q=q) eq_balance = Equation('balance', term_1 + term_pressure) eq_volume = Equation('volume', term_volume_change - term_volume) equations = Equations([eq_balance, eq_volume]) ### Solvers ### ls = ScipyDirect({}) nls_status =
IndexedStruct()
sfepy.base.base.IndexedStruct
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p = FieldVariable('p', 'unknown', scalar_field, history=1) q = FieldVariable('q', 'test', scalar_field, primary_var_name='p') ### Material ### coefficient, exponent = material_parameters m_1 = Material( 'm1', par=[coefficient, exponent], ) ### Boundary conditions ### x_sym = EssentialBC('x_sym', regions['Left'], {'u.0' : 0.0}) y_sym = EssentialBC('y_sym', regions['Near'], {'u.1' : 0.0}) z_sym = EssentialBC('z_sym', regions['Bottom'], {'u.2' : 0.0}) disp_fun = Function('disp_fun', get_displacement) displacement = EssentialBC( 'displacement', regions['Right'], {'u.0' : disp_fun}) ebcs = Conditions([x_sym, y_sym, z_sym, displacement]) ### Terms and equations ### integral = Integral('i', order=2*order+1) term_1 = Term.new( 'dw_tl_he_genyeoh(m1.par, v, u)', integral, omega, m1=m_1, v=v, u=u) term_pressure = Term.new( 'dw_tl_bulk_pressure(v, u, p)', integral, omega, v=v, u=u, p=p) term_volume_change = Term.new( 'dw_tl_volume(q, u)', integral, omega, q=q, u=u, term_mode='volume') term_volume = Term.new( 'dw_volume_integrate(q)', integral, omega, q=q) eq_balance = Equation('balance', term_1 + term_pressure) eq_volume = Equation('volume', term_volume_change - term_volume) equations = Equations([eq_balance, eq_volume]) ### Solvers ### ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton( {'i_max' : 20}, lin_solver=ls, status=nls_status ) ### Problem ### pb =
Problem('hyper', equations=equations)
sfepy.discrete.Problem
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p = FieldVariable('p', 'unknown', scalar_field, history=1) q = FieldVariable('q', 'test', scalar_field, primary_var_name='p') ### Material ### coefficient, exponent = material_parameters m_1 = Material( 'm1', par=[coefficient, exponent], ) ### Boundary conditions ### x_sym = EssentialBC('x_sym', regions['Left'], {'u.0' : 0.0}) y_sym = EssentialBC('y_sym', regions['Near'], {'u.1' : 0.0}) z_sym = EssentialBC('z_sym', regions['Bottom'], {'u.2' : 0.0}) disp_fun = Function('disp_fun', get_displacement) displacement = EssentialBC( 'displacement', regions['Right'], {'u.0' : disp_fun}) ebcs = Conditions([x_sym, y_sym, z_sym, displacement]) ### Terms and equations ### integral = Integral('i', order=2*order+1) term_1 = Term.new( 'dw_tl_he_genyeoh(m1.par, v, u)', integral, omega, m1=m_1, v=v, u=u) term_pressure = Term.new( 'dw_tl_bulk_pressure(v, u, p)', integral, omega, v=v, u=u, p=p) term_volume_change = Term.new( 'dw_tl_volume(q, u)', integral, omega, q=q, u=u, term_mode='volume') term_volume = Term.new( 'dw_volume_integrate(q)', integral, omega, q=q) eq_balance = Equation('balance', term_1 + term_pressure) eq_volume = Equation('volume', term_volume_change - term_volume) equations = Equations([eq_balance, eq_volume]) ### Solvers ### ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton( {'i_max' : 20}, lin_solver=ls, status=nls_status ) ### Problem ### pb = Problem('hyper', equations=equations) pb.set_bcs(ebcs=ebcs) pb.set_ics(ics=Conditions([])) tss =
SimpleTimeSteppingSolver(ts, nls=nls, context=pb)
sfepy.solvers.ts_solvers.SimpleTimeSteppingSolver