prompt
stringlengths 174
59.5k
| completion
stringlengths 7
228
| api
stringlengths 12
64
|
---|---|---|
from __future__ import absolute_import
import os.path as op
import numpy as nm
from sfepy import data_dir
from sfepy.base.testing import TestCommon
import six
def init_vec(variables):
return nm.random.rand(variables.di.ptr[-1])
def check_vec(self, vec, ii, ok, conds, variables):
from sfepy.discrete.common.dof_info import expand_nodes_to_equations
for var_name, var_conds in six.iteritems(conds.group_by_variables()):
var = variables[var_name]
for cond in var_conds:
cond.canonize_dof_names(var.dofs)
self.report('%d: %s %s: %s %s'
% (ii, var.name,
cond.name, cond.region.name, cond.dofs[0]))
nods = var.field.get_dofs_in_region(cond.region)
eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs)
off = variables.di.indx[var_name].start
n_nod = len(nods)
for cdof, dof_name in enumerate(cond.dofs[0]):
idof = var.dofs.index(dof_name)
eqs = eq[n_nod * cdof : n_nod * (cdof + 1)]
_ok = nm.allclose(vec[off + eqs], idof,
atol=1e-14, rtol=0.0)
if not _ok:
self.report(' %s: failed! (all of %s == %f)'
% (dof_name, vec[off + eqs], idof))
ok = ok and _ok
return ok
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
from sfepy.discrete import FieldVariable, Variables, Problem
from sfepy.discrete.fem import Mesh, FEDomain, Field
mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh')
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
domain.create_region('Left',
'vertices in (x < -0.499)',
'facet')
domain.create_region('LeftStrip',
'vertices in (x < -0.499)'
' & (y > -0.199) & (y < 0.199)',
'facet')
domain.create_region('LeftFix',
'r.Left -v r.LeftStrip',
'facet')
domain.create_region('Right',
'vertices in (x > 0.499)',
'facet')
domain.create_region('RightStrip',
'vertices in (x > 0.499)'
' & (y > -0.199) & (y < 0.199)',
'facet')
domain.create_region('RightFix',
'r.Right -v r.RightStrip',
'facet')
fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2)
u = FieldVariable('u', 'unknown', fu)
fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2)
p = FieldVariable('p', 'unknown', fp)
pb = Problem('test', domain=domain, fields=[fu, fp],
auto_conf=False, auto_solvers=False)
test = Test(problem=pb, variables=Variables([u, p]),
conf=conf, options=options)
return test
def test_ics(self):
from sfepy.discrete.conditions import Conditions, InitialCondition
variables = self.variables
omega = self.problem.domain.regions['Omega']
all_ics = []
all_ics.append(InitialCondition('ic0', omega,
{'p.all' : 0.0}))
all_ics.append(InitialCondition('ic1', omega,
{'u.1' : 1.0}))
all_ics.append(InitialCondition('ic2', omega,
{'u.all' : nm.array([0.0, 1.0])}))
all_ics.append(InitialCondition('ic3', omega,
{'p.0' : 0.0,
'u.0' : 0.0, 'u.1' : 1.0}))
ok = True
for ii, ics in enumerate(all_ics):
if not isinstance(ics, list): ics = [ics]
ics = | Conditions(ics) | sfepy.discrete.conditions.Conditions |
from __future__ import absolute_import
import os.path as op
import numpy as nm
from sfepy import data_dir
from sfepy.base.testing import TestCommon
import six
def init_vec(variables):
return nm.random.rand(variables.di.ptr[-1])
def check_vec(self, vec, ii, ok, conds, variables):
from sfepy.discrete.common.dof_info import expand_nodes_to_equations
for var_name, var_conds in six.iteritems(conds.group_by_variables()):
var = variables[var_name]
for cond in var_conds:
cond.canonize_dof_names(var.dofs)
self.report('%d: %s %s: %s %s'
% (ii, var.name,
cond.name, cond.region.name, cond.dofs[0]))
nods = var.field.get_dofs_in_region(cond.region)
eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs)
off = variables.di.indx[var_name].start
n_nod = len(nods)
for cdof, dof_name in enumerate(cond.dofs[0]):
idof = var.dofs.index(dof_name)
eqs = eq[n_nod * cdof : n_nod * (cdof + 1)]
_ok = nm.allclose(vec[off + eqs], idof,
atol=1e-14, rtol=0.0)
if not _ok:
self.report(' %s: failed! (all of %s == %f)'
% (dof_name, vec[off + eqs], idof))
ok = ok and _ok
return ok
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
from sfepy.discrete import FieldVariable, Variables, Problem
from sfepy.discrete.fem import Mesh, FEDomain, Field
mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh')
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
domain.create_region('Left',
'vertices in (x < -0.499)',
'facet')
domain.create_region('LeftStrip',
'vertices in (x < -0.499)'
' & (y > -0.199) & (y < 0.199)',
'facet')
domain.create_region('LeftFix',
'r.Left -v r.LeftStrip',
'facet')
domain.create_region('Right',
'vertices in (x > 0.499)',
'facet')
domain.create_region('RightStrip',
'vertices in (x > 0.499)'
' & (y > -0.199) & (y < 0.199)',
'facet')
domain.create_region('RightFix',
'r.Right -v r.RightStrip',
'facet')
fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2)
u = FieldVariable('u', 'unknown', fu)
fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2)
p = FieldVariable('p', 'unknown', fp)
pb = Problem('test', domain=domain, fields=[fu, fp],
auto_conf=False, auto_solvers=False)
test = Test(problem=pb, variables=Variables([u, p]),
conf=conf, options=options)
return test
def test_ics(self):
from sfepy.discrete.conditions import Conditions, InitialCondition
variables = self.variables
omega = self.problem.domain.regions['Omega']
all_ics = []
all_ics.append(InitialCondition('ic0', omega,
{'p.all' : 0.0}))
all_ics.append(InitialCondition('ic1', omega,
{'u.1' : 1.0}))
all_ics.append(InitialCondition('ic2', omega,
{'u.all' : nm.array([0.0, 1.0])}))
all_ics.append(InitialCondition('ic3', omega,
{'p.0' : 0.0,
'u.0' : 0.0, 'u.1' : 1.0}))
ok = True
for ii, ics in enumerate(all_ics):
if not isinstance(ics, list): ics = [ics]
ics = Conditions(ics)
variables.setup_initial_conditions(ics, functions=None)
vec = init_vec(variables)
variables.apply_ic(vec)
ok = check_vec(self, vec, ii, ok, ics, variables)
return ok
def test_ebcs(self):
from sfepy.discrete.conditions import Conditions, EssentialBC
variables = self.variables
regions = self.problem.domain.regions
all_ebcs = []
all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'],
{'u.all' : nm.array([0.0, 1.0])}))
all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'],
{'u.0' : 0.0, 'u.1' : 1.0}))
all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'],
{'p.all' : 0.0}))
all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'],
{'p.0' : 0.0}))
all_ebcs.append([EssentialBC('fix_p3', regions['Right'],
{'p.0' : 0.0}),
EssentialBC('fix_u3', regions['Left'],
{'u.0' : 0.0, 'u.1' : 1.0})])
ok = True
for ii, bcs in enumerate(all_ebcs):
if not isinstance(bcs, list): bcs = [bcs]
ebcs = | Conditions(bcs) | sfepy.discrete.conditions.Conditions |
from __future__ import absolute_import
import os.path as op
import numpy as nm
from sfepy import data_dir
from sfepy.base.testing import TestCommon
import six
def init_vec(variables):
return nm.random.rand(variables.di.ptr[-1])
def check_vec(self, vec, ii, ok, conds, variables):
from sfepy.discrete.common.dof_info import expand_nodes_to_equations
for var_name, var_conds in six.iteritems(conds.group_by_variables()):
var = variables[var_name]
for cond in var_conds:
cond.canonize_dof_names(var.dofs)
self.report('%d: %s %s: %s %s'
% (ii, var.name,
cond.name, cond.region.name, cond.dofs[0]))
nods = var.field.get_dofs_in_region(cond.region)
eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs)
off = variables.di.indx[var_name].start
n_nod = len(nods)
for cdof, dof_name in enumerate(cond.dofs[0]):
idof = var.dofs.index(dof_name)
eqs = eq[n_nod * cdof : n_nod * (cdof + 1)]
_ok = nm.allclose(vec[off + eqs], idof,
atol=1e-14, rtol=0.0)
if not _ok:
self.report(' %s: failed! (all of %s == %f)'
% (dof_name, vec[off + eqs], idof))
ok = ok and _ok
return ok
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
from sfepy.discrete import FieldVariable, Variables, Problem
from sfepy.discrete.fem import Mesh, FEDomain, Field
mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh')
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
domain.create_region('Left',
'vertices in (x < -0.499)',
'facet')
domain.create_region('LeftStrip',
'vertices in (x < -0.499)'
' & (y > -0.199) & (y < 0.199)',
'facet')
domain.create_region('LeftFix',
'r.Left -v r.LeftStrip',
'facet')
domain.create_region('Right',
'vertices in (x > 0.499)',
'facet')
domain.create_region('RightStrip',
'vertices in (x > 0.499)'
' & (y > -0.199) & (y < 0.199)',
'facet')
domain.create_region('RightFix',
'r.Right -v r.RightStrip',
'facet')
fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2)
u = FieldVariable('u', 'unknown', fu)
fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2)
p = FieldVariable('p', 'unknown', fp)
pb = Problem('test', domain=domain, fields=[fu, fp],
auto_conf=False, auto_solvers=False)
test = Test(problem=pb, variables= | Variables([u, p]) | sfepy.discrete.Variables |
import numpy as nm
from sfepy.base.conf import transform_functions
from sfepy.base.testing import TestCommon
def get_nodes(coors, domain=None):
x, z = coors[:,0], coors[:,2]
return nm.where((z < 0.1) & (x < 0.1))[0]
def get_elements(coors, domain=None):
return {0 : [1, 4, 5]}
class Test(TestCommon):
@staticmethod
def from_conf( conf, options ):
from sfepy import data_dir
from sfepy.fem import Mesh, Domain, Functions
mesh = Mesh('test mesh',
data_dir + '/meshes/various_formats/abaqus_tet.inp')
domain = | Domain('test domain', mesh) | sfepy.fem.Domain |
import numpy as nm
from sfepy.base.conf import transform_functions
from sfepy.base.testing import TestCommon
def get_nodes(coors, domain=None):
x, z = coors[:,0], coors[:,2]
return nm.where((z < 0.1) & (x < 0.1))[0]
def get_elements(coors, domain=None):
return {0 : [1, 4, 5]}
class Test(TestCommon):
@staticmethod
def from_conf( conf, options ):
from sfepy import data_dir
from sfepy.fem import Mesh, Domain, Functions
mesh = Mesh('test mesh',
data_dir + '/meshes/various_formats/abaqus_tet.inp')
domain = Domain('test domain', mesh)
conf_functions = {
'get_nodes' : (get_nodes,),
'get_elements' : (get_elements,),
}
functions = Functions.from_conf( | transform_functions(conf_functions) | sfepy.base.conf.transform_functions |
from __future__ import absolute_import
from sfepy.discrete.fem import Mesh, FEDomain
import scipy.sparse as sps
import numpy as nm
from sfepy.base.compat import factorial
from sfepy.base.base import output
from six.moves import range
def elems_q2t(el):
nel, nnd = el.shape
if nnd > 4:
q2t = nm.array([[0, 2, 3, 6],
[0, 3, 7, 6],
[0, 7, 4, 6],
[0, 5, 6, 4],
[1, 5, 6, 0],
[1, 6, 2, 0]])
else:
q2t = nm.array([[0, 1, 2],
[0, 2, 3]])
ns, nn = q2t.shape
nel *= ns
out = nm.zeros((nel, nn), dtype=nm.int32);
for ii in range(ns):
idxs = nm.arange(ii, nel, ns)
out[idxs,:] = el[:, q2t[ii,:]]
return nm.ascontiguousarray(out)
def triangulate(mesh, verbose=False):
"""
Triangulate a 2D or 3D tensor product mesh: quadrilaterals->triangles,
hexahedrons->tetrahedrons.
Parameters
----------
mesh : Mesh
The input mesh.
Returns
-------
mesh : Mesh
The triangulated mesh.
"""
conns = None
for k, new_desc in [('3_8', '3_4'), ('2_4', '2_3')]:
if k in mesh.descs:
conns = mesh.get_conn(k)
break
if conns is not None:
nelo = conns.shape[0]
output('initial mesh: %d elements' % nelo, verbose=verbose)
new_conns = elems_q2t(conns)
nn = new_conns.shape[0] // nelo
new_cgroups = nm.repeat(mesh.cmesh.cell_groups, nn)
output('new mesh: %d elements' % new_conns.shape[0], verbose=verbose)
mesh = Mesh.from_data(mesh.name, mesh.coors,
mesh.cmesh.vertex_groups,
[new_conns], [new_cgroups], [new_desc])
return mesh
def smooth_mesh(mesh, n_iter=4, lam=0.6307, mu=-0.6347,
weights=None, bconstr=True,
volume_corr=False):
"""
FE mesh smoothing.
Based on:
[1] <NAME>, <NAME>, Smooth surface meshing for automated
finite element model generation from 3D image data, Journal of
Biomechanics, Volume 39, Issue 7, 2006, Pages 1287-1295,
ISSN 0021-9290, 10.1016/j.jbiomech.2005.03.006.
(http://www.sciencedirect.com/science/article/pii/S0021929005001442)
Parameters
----------
mesh : mesh
FE mesh.
n_iter : integer, optional
Number of iteration steps.
lam : float, optional
Smoothing factor, see [1].
mu : float, optional
Unshrinking factor, see [1].
weights : array, optional
Edge weights, see [1].
bconstr: logical, optional
Boundary constraints, if True only surface smoothing performed.
volume_corr: logical, optional
Correct volume after smoothing process.
Returns
-------
coors : array
Coordinates of mesh nodes.
"""
def laplacian(coors, weights):
n_nod = coors.shape[0]
displ = (weights - sps.identity(n_nod)) * coors
return displ
def taubin(coors0, weights, lam, mu, n_iter):
coors = coors0.copy()
for ii in range(n_iter):
displ = laplacian(coors, weights)
if nm.mod(ii, 2) == 0:
coors += lam * displ
else:
coors += mu * displ
return coors
def get_volume(el, nd):
from sfepy.linalg.utils import dets_fast
dim = nd.shape[1]
nnd = el.shape[1]
etype = '%d_%d' % (dim, nnd)
if etype == '2_4' or etype == '3_8':
el = elems_q2t(el)
nel = el.shape[0]
#bc = nm.zeros((dim, ), dtype=nm.double)
mul = 1.0 / factorial(dim)
if dim == 3:
mul *= -1.0
mtx = nm.ones((nel, dim + 1, dim + 1), dtype=nm.double)
mtx[:,:,:-1] = nd[el,:]
vols = mul * dets_fast(mtx)
vol = vols.sum()
bc = nm.dot(vols, mtx.sum(1)[:,:-1] / nnd)
bc /= vol
return vol, bc
from sfepy.base.timing import Timer
| output('smoothing...') | sfepy.base.base.output |
from __future__ import absolute_import
from sfepy.discrete.fem import Mesh, FEDomain
import scipy.sparse as sps
import numpy as nm
from sfepy.base.compat import factorial
from sfepy.base.base import output
from six.moves import range
def elems_q2t(el):
nel, nnd = el.shape
if nnd > 4:
q2t = nm.array([[0, 2, 3, 6],
[0, 3, 7, 6],
[0, 7, 4, 6],
[0, 5, 6, 4],
[1, 5, 6, 0],
[1, 6, 2, 0]])
else:
q2t = nm.array([[0, 1, 2],
[0, 2, 3]])
ns, nn = q2t.shape
nel *= ns
out = nm.zeros((nel, nn), dtype=nm.int32);
for ii in range(ns):
idxs = nm.arange(ii, nel, ns)
out[idxs,:] = el[:, q2t[ii,:]]
return nm.ascontiguousarray(out)
def triangulate(mesh, verbose=False):
"""
Triangulate a 2D or 3D tensor product mesh: quadrilaterals->triangles,
hexahedrons->tetrahedrons.
Parameters
----------
mesh : Mesh
The input mesh.
Returns
-------
mesh : Mesh
The triangulated mesh.
"""
conns = None
for k, new_desc in [('3_8', '3_4'), ('2_4', '2_3')]:
if k in mesh.descs:
conns = mesh.get_conn(k)
break
if conns is not None:
nelo = conns.shape[0]
output('initial mesh: %d elements' % nelo, verbose=verbose)
new_conns = elems_q2t(conns)
nn = new_conns.shape[0] // nelo
new_cgroups = nm.repeat(mesh.cmesh.cell_groups, nn)
output('new mesh: %d elements' % new_conns.shape[0], verbose=verbose)
mesh = Mesh.from_data(mesh.name, mesh.coors,
mesh.cmesh.vertex_groups,
[new_conns], [new_cgroups], [new_desc])
return mesh
def smooth_mesh(mesh, n_iter=4, lam=0.6307, mu=-0.6347,
weights=None, bconstr=True,
volume_corr=False):
"""
FE mesh smoothing.
Based on:
[1] <NAME>, <NAME>, Smooth surface meshing for automated
finite element model generation from 3D image data, Journal of
Biomechanics, Volume 39, Issue 7, 2006, Pages 1287-1295,
ISSN 0021-9290, 10.1016/j.jbiomech.2005.03.006.
(http://www.sciencedirect.com/science/article/pii/S0021929005001442)
Parameters
----------
mesh : mesh
FE mesh.
n_iter : integer, optional
Number of iteration steps.
lam : float, optional
Smoothing factor, see [1].
mu : float, optional
Unshrinking factor, see [1].
weights : array, optional
Edge weights, see [1].
bconstr: logical, optional
Boundary constraints, if True only surface smoothing performed.
volume_corr: logical, optional
Correct volume after smoothing process.
Returns
-------
coors : array
Coordinates of mesh nodes.
"""
def laplacian(coors, weights):
n_nod = coors.shape[0]
displ = (weights - sps.identity(n_nod)) * coors
return displ
def taubin(coors0, weights, lam, mu, n_iter):
coors = coors0.copy()
for ii in range(n_iter):
displ = laplacian(coors, weights)
if nm.mod(ii, 2) == 0:
coors += lam * displ
else:
coors += mu * displ
return coors
def get_volume(el, nd):
from sfepy.linalg.utils import dets_fast
dim = nd.shape[1]
nnd = el.shape[1]
etype = '%d_%d' % (dim, nnd)
if etype == '2_4' or etype == '3_8':
el = elems_q2t(el)
nel = el.shape[0]
#bc = nm.zeros((dim, ), dtype=nm.double)
mul = 1.0 / factorial(dim)
if dim == 3:
mul *= -1.0
mtx = nm.ones((nel, dim + 1, dim + 1), dtype=nm.double)
mtx[:,:,:-1] = nd[el,:]
vols = mul * dets_fast(mtx)
vol = vols.sum()
bc = nm.dot(vols, mtx.sum(1)[:,:-1] / nnd)
bc /= vol
return vol, bc
from sfepy.base.timing import Timer
output('smoothing...')
timer = | Timer(start=True) | sfepy.base.timing.Timer |
from __future__ import absolute_import
from sfepy.discrete.fem import Mesh, FEDomain
import scipy.sparse as sps
import numpy as nm
from sfepy.base.compat import factorial
from sfepy.base.base import output
from six.moves import range
def elems_q2t(el):
nel, nnd = el.shape
if nnd > 4:
q2t = nm.array([[0, 2, 3, 6],
[0, 3, 7, 6],
[0, 7, 4, 6],
[0, 5, 6, 4],
[1, 5, 6, 0],
[1, 6, 2, 0]])
else:
q2t = nm.array([[0, 1, 2],
[0, 2, 3]])
ns, nn = q2t.shape
nel *= ns
out = nm.zeros((nel, nn), dtype=nm.int32);
for ii in range(ns):
idxs = nm.arange(ii, nel, ns)
out[idxs,:] = el[:, q2t[ii,:]]
return nm.ascontiguousarray(out)
def triangulate(mesh, verbose=False):
"""
Triangulate a 2D or 3D tensor product mesh: quadrilaterals->triangles,
hexahedrons->tetrahedrons.
Parameters
----------
mesh : Mesh
The input mesh.
Returns
-------
mesh : Mesh
The triangulated mesh.
"""
conns = None
for k, new_desc in [('3_8', '3_4'), ('2_4', '2_3')]:
if k in mesh.descs:
conns = mesh.get_conn(k)
break
if conns is not None:
nelo = conns.shape[0]
| output('initial mesh: %d elements' % nelo, verbose=verbose) | sfepy.base.base.output |
from __future__ import absolute_import
from sfepy.discrete.fem import Mesh, FEDomain
import scipy.sparse as sps
import numpy as nm
from sfepy.base.compat import factorial
from sfepy.base.base import output
from six.moves import range
def elems_q2t(el):
nel, nnd = el.shape
if nnd > 4:
q2t = nm.array([[0, 2, 3, 6],
[0, 3, 7, 6],
[0, 7, 4, 6],
[0, 5, 6, 4],
[1, 5, 6, 0],
[1, 6, 2, 0]])
else:
q2t = nm.array([[0, 1, 2],
[0, 2, 3]])
ns, nn = q2t.shape
nel *= ns
out = nm.zeros((nel, nn), dtype=nm.int32);
for ii in range(ns):
idxs = nm.arange(ii, nel, ns)
out[idxs,:] = el[:, q2t[ii,:]]
return nm.ascontiguousarray(out)
def triangulate(mesh, verbose=False):
"""
Triangulate a 2D or 3D tensor product mesh: quadrilaterals->triangles,
hexahedrons->tetrahedrons.
Parameters
----------
mesh : Mesh
The input mesh.
Returns
-------
mesh : Mesh
The triangulated mesh.
"""
conns = None
for k, new_desc in [('3_8', '3_4'), ('2_4', '2_3')]:
if k in mesh.descs:
conns = mesh.get_conn(k)
break
if conns is not None:
nelo = conns.shape[0]
output('initial mesh: %d elements' % nelo, verbose=verbose)
new_conns = elems_q2t(conns)
nn = new_conns.shape[0] // nelo
new_cgroups = nm.repeat(mesh.cmesh.cell_groups, nn)
| output('new mesh: %d elements' % new_conns.shape[0], verbose=verbose) | sfepy.base.base.output |
from __future__ import absolute_import
from sfepy.discrete.fem import Mesh, FEDomain
import scipy.sparse as sps
import numpy as nm
from sfepy.base.compat import factorial
from sfepy.base.base import output
from six.moves import range
def elems_q2t(el):
nel, nnd = el.shape
if nnd > 4:
q2t = nm.array([[0, 2, 3, 6],
[0, 3, 7, 6],
[0, 7, 4, 6],
[0, 5, 6, 4],
[1, 5, 6, 0],
[1, 6, 2, 0]])
else:
q2t = nm.array([[0, 1, 2],
[0, 2, 3]])
ns, nn = q2t.shape
nel *= ns
out = nm.zeros((nel, nn), dtype=nm.int32);
for ii in range(ns):
idxs = nm.arange(ii, nel, ns)
out[idxs,:] = el[:, q2t[ii,:]]
return nm.ascontiguousarray(out)
def triangulate(mesh, verbose=False):
"""
Triangulate a 2D or 3D tensor product mesh: quadrilaterals->triangles,
hexahedrons->tetrahedrons.
Parameters
----------
mesh : Mesh
The input mesh.
Returns
-------
mesh : Mesh
The triangulated mesh.
"""
conns = None
for k, new_desc in [('3_8', '3_4'), ('2_4', '2_3')]:
if k in mesh.descs:
conns = mesh.get_conn(k)
break
if conns is not None:
nelo = conns.shape[0]
output('initial mesh: %d elements' % nelo, verbose=verbose)
new_conns = elems_q2t(conns)
nn = new_conns.shape[0] // nelo
new_cgroups = nm.repeat(mesh.cmesh.cell_groups, nn)
output('new mesh: %d elements' % new_conns.shape[0], verbose=verbose)
mesh = Mesh.from_data(mesh.name, mesh.coors,
mesh.cmesh.vertex_groups,
[new_conns], [new_cgroups], [new_desc])
return mesh
def smooth_mesh(mesh, n_iter=4, lam=0.6307, mu=-0.6347,
weights=None, bconstr=True,
volume_corr=False):
"""
FE mesh smoothing.
Based on:
[1] <NAME>, <NAME>, Smooth surface meshing for automated
finite element model generation from 3D image data, Journal of
Biomechanics, Volume 39, Issue 7, 2006, Pages 1287-1295,
ISSN 0021-9290, 10.1016/j.jbiomech.2005.03.006.
(http://www.sciencedirect.com/science/article/pii/S0021929005001442)
Parameters
----------
mesh : mesh
FE mesh.
n_iter : integer, optional
Number of iteration steps.
lam : float, optional
Smoothing factor, see [1].
mu : float, optional
Unshrinking factor, see [1].
weights : array, optional
Edge weights, see [1].
bconstr: logical, optional
Boundary constraints, if True only surface smoothing performed.
volume_corr: logical, optional
Correct volume after smoothing process.
Returns
-------
coors : array
Coordinates of mesh nodes.
"""
def laplacian(coors, weights):
n_nod = coors.shape[0]
displ = (weights - sps.identity(n_nod)) * coors
return displ
def taubin(coors0, weights, lam, mu, n_iter):
coors = coors0.copy()
for ii in range(n_iter):
displ = laplacian(coors, weights)
if nm.mod(ii, 2) == 0:
coors += lam * displ
else:
coors += mu * displ
return coors
def get_volume(el, nd):
from sfepy.linalg.utils import dets_fast
dim = nd.shape[1]
nnd = el.shape[1]
etype = '%d_%d' % (dim, nnd)
if etype == '2_4' or etype == '3_8':
el = elems_q2t(el)
nel = el.shape[0]
#bc = nm.zeros((dim, ), dtype=nm.double)
mul = 1.0 / factorial(dim)
if dim == 3:
mul *= -1.0
mtx = nm.ones((nel, dim + 1, dim + 1), dtype=nm.double)
mtx[:,:,:-1] = nd[el,:]
vols = mul * dets_fast(mtx)
vol = vols.sum()
bc = nm.dot(vols, mtx.sum(1)[:,:-1] / nnd)
bc /= vol
return vol, bc
from sfepy.base.timing import Timer
output('smoothing...')
timer = Timer(start=True)
if weights is None:
n_nod = mesh.n_nod
domain = | FEDomain('mesh', mesh) | sfepy.discrete.fem.FEDomain |
from __future__ import absolute_import
from sfepy.discrete.fem import Mesh, FEDomain
import scipy.sparse as sps
import numpy as nm
from sfepy.base.compat import factorial
from sfepy.base.base import output
from six.moves import range
def elems_q2t(el):
nel, nnd = el.shape
if nnd > 4:
q2t = nm.array([[0, 2, 3, 6],
[0, 3, 7, 6],
[0, 7, 4, 6],
[0, 5, 6, 4],
[1, 5, 6, 0],
[1, 6, 2, 0]])
else:
q2t = nm.array([[0, 1, 2],
[0, 2, 3]])
ns, nn = q2t.shape
nel *= ns
out = nm.zeros((nel, nn), dtype=nm.int32);
for ii in range(ns):
idxs = nm.arange(ii, nel, ns)
out[idxs,:] = el[:, q2t[ii,:]]
return nm.ascontiguousarray(out)
def triangulate(mesh, verbose=False):
"""
Triangulate a 2D or 3D tensor product mesh: quadrilaterals->triangles,
hexahedrons->tetrahedrons.
Parameters
----------
mesh : Mesh
The input mesh.
Returns
-------
mesh : Mesh
The triangulated mesh.
"""
conns = None
for k, new_desc in [('3_8', '3_4'), ('2_4', '2_3')]:
if k in mesh.descs:
conns = mesh.get_conn(k)
break
if conns is not None:
nelo = conns.shape[0]
output('initial mesh: %d elements' % nelo, verbose=verbose)
new_conns = elems_q2t(conns)
nn = new_conns.shape[0] // nelo
new_cgroups = nm.repeat(mesh.cmesh.cell_groups, nn)
output('new mesh: %d elements' % new_conns.shape[0], verbose=verbose)
mesh = Mesh.from_data(mesh.name, mesh.coors,
mesh.cmesh.vertex_groups,
[new_conns], [new_cgroups], [new_desc])
return mesh
def smooth_mesh(mesh, n_iter=4, lam=0.6307, mu=-0.6347,
weights=None, bconstr=True,
volume_corr=False):
"""
FE mesh smoothing.
Based on:
[1] <NAME>, <NAME>, Smooth surface meshing for automated
finite element model generation from 3D image data, Journal of
Biomechanics, Volume 39, Issue 7, 2006, Pages 1287-1295,
ISSN 0021-9290, 10.1016/j.jbiomech.2005.03.006.
(http://www.sciencedirect.com/science/article/pii/S0021929005001442)
Parameters
----------
mesh : mesh
FE mesh.
n_iter : integer, optional
Number of iteration steps.
lam : float, optional
Smoothing factor, see [1].
mu : float, optional
Unshrinking factor, see [1].
weights : array, optional
Edge weights, see [1].
bconstr: logical, optional
Boundary constraints, if True only surface smoothing performed.
volume_corr: logical, optional
Correct volume after smoothing process.
Returns
-------
coors : array
Coordinates of mesh nodes.
"""
def laplacian(coors, weights):
n_nod = coors.shape[0]
displ = (weights - sps.identity(n_nod)) * coors
return displ
def taubin(coors0, weights, lam, mu, n_iter):
coors = coors0.copy()
for ii in range(n_iter):
displ = laplacian(coors, weights)
if nm.mod(ii, 2) == 0:
coors += lam * displ
else:
coors += mu * displ
return coors
def get_volume(el, nd):
from sfepy.linalg.utils import dets_fast
dim = nd.shape[1]
nnd = el.shape[1]
etype = '%d_%d' % (dim, nnd)
if etype == '2_4' or etype == '3_8':
el = elems_q2t(el)
nel = el.shape[0]
#bc = nm.zeros((dim, ), dtype=nm.double)
mul = 1.0 / factorial(dim)
if dim == 3:
mul *= -1.0
mtx = nm.ones((nel, dim + 1, dim + 1), dtype=nm.double)
mtx[:,:,:-1] = nd[el,:]
vols = mul * dets_fast(mtx)
vol = vols.sum()
bc = nm.dot(vols, mtx.sum(1)[:,:-1] / nnd)
bc /= vol
return vol, bc
from sfepy.base.timing import Timer
output('smoothing...')
timer = Timer(start=True)
if weights is None:
n_nod = mesh.n_nod
domain = FEDomain('mesh', mesh)
cmesh = domain.cmesh
# initiate all vertices as inner - hierarchy = 2
node_group = nm.ones((n_nod,), dtype=nm.int16) * 2
# boundary vertices - set hierarchy = 4
if bconstr:
# get "vertices of surface"
facets = cmesh.get_surface_facets()
f_verts = cmesh.get_incident(0, facets, cmesh.dim - 1)
node_group[f_verts] = 4
# generate costs matrix
e_verts = cmesh.get_conn(1, 0).indices
fc1, fc2 = e_verts[0::2], e_verts[1::2]
idxs = nm.where(node_group[fc2] >= node_group[fc1])
rows1 = fc1[idxs]
cols1 = fc2[idxs]
idxs = nm.where(node_group[fc1] >= node_group[fc2])
rows2 = fc2[idxs]
cols2 = fc1[idxs]
crows = nm.concatenate((rows1, rows2))
ccols = nm.concatenate((cols1, cols2))
costs = sps.coo_matrix((nm.ones_like(crows), (crows, ccols)),
shape=(n_nod, n_nod),
dtype=nm.double)
# generate weights matrix
idxs = list(range(n_nod))
aux = sps.coo_matrix((1.0 / nm.asarray(costs.sum(1)).squeeze(),
(idxs, idxs)),
shape=(n_nod, n_nod),
dtype=nm.double)
#aux.setdiag(1.0 / costs.sum(1))
weights = (aux.tocsc() * costs.tocsc()).tocsr()
coors = taubin(mesh.coors, weights, lam, mu, n_iter)
output('...done in %.2f s' % timer.stop())
if volume_corr:
| output('rescaling...') | sfepy.base.base.output |
from __future__ import absolute_import
from sfepy.discrete.fem import Mesh, FEDomain
import scipy.sparse as sps
import numpy as nm
from sfepy.base.compat import factorial
from sfepy.base.base import output
from six.moves import range
def elems_q2t(el):
nel, nnd = el.shape
if nnd > 4:
q2t = nm.array([[0, 2, 3, 6],
[0, 3, 7, 6],
[0, 7, 4, 6],
[0, 5, 6, 4],
[1, 5, 6, 0],
[1, 6, 2, 0]])
else:
q2t = nm.array([[0, 1, 2],
[0, 2, 3]])
ns, nn = q2t.shape
nel *= ns
out = nm.zeros((nel, nn), dtype=nm.int32);
for ii in range(ns):
idxs = nm.arange(ii, nel, ns)
out[idxs,:] = el[:, q2t[ii,:]]
return nm.ascontiguousarray(out)
def triangulate(mesh, verbose=False):
"""
Triangulate a 2D or 3D tensor product mesh: quadrilaterals->triangles,
hexahedrons->tetrahedrons.
Parameters
----------
mesh : Mesh
The input mesh.
Returns
-------
mesh : Mesh
The triangulated mesh.
"""
conns = None
for k, new_desc in [('3_8', '3_4'), ('2_4', '2_3')]:
if k in mesh.descs:
conns = mesh.get_conn(k)
break
if conns is not None:
nelo = conns.shape[0]
output('initial mesh: %d elements' % nelo, verbose=verbose)
new_conns = elems_q2t(conns)
nn = new_conns.shape[0] // nelo
new_cgroups = nm.repeat(mesh.cmesh.cell_groups, nn)
output('new mesh: %d elements' % new_conns.shape[0], verbose=verbose)
mesh = Mesh.from_data(mesh.name, mesh.coors,
mesh.cmesh.vertex_groups,
[new_conns], [new_cgroups], [new_desc])
return mesh
def smooth_mesh(mesh, n_iter=4, lam=0.6307, mu=-0.6347,
weights=None, bconstr=True,
volume_corr=False):
"""
FE mesh smoothing.
Based on:
[1] <NAME>, <NAME>, Smooth surface meshing for automated
finite element model generation from 3D image data, Journal of
Biomechanics, Volume 39, Issue 7, 2006, Pages 1287-1295,
ISSN 0021-9290, 10.1016/j.jbiomech.2005.03.006.
(http://www.sciencedirect.com/science/article/pii/S0021929005001442)
Parameters
----------
mesh : mesh
FE mesh.
n_iter : integer, optional
Number of iteration steps.
lam : float, optional
Smoothing factor, see [1].
mu : float, optional
Unshrinking factor, see [1].
weights : array, optional
Edge weights, see [1].
bconstr: logical, optional
Boundary constraints, if True only surface smoothing performed.
volume_corr: logical, optional
Correct volume after smoothing process.
Returns
-------
coors : array
Coordinates of mesh nodes.
"""
def laplacian(coors, weights):
n_nod = coors.shape[0]
displ = (weights - sps.identity(n_nod)) * coors
return displ
def taubin(coors0, weights, lam, mu, n_iter):
coors = coors0.copy()
for ii in range(n_iter):
displ = laplacian(coors, weights)
if nm.mod(ii, 2) == 0:
coors += lam * displ
else:
coors += mu * displ
return coors
def get_volume(el, nd):
from sfepy.linalg.utils import dets_fast
dim = nd.shape[1]
nnd = el.shape[1]
etype = '%d_%d' % (dim, nnd)
if etype == '2_4' or etype == '3_8':
el = elems_q2t(el)
nel = el.shape[0]
#bc = nm.zeros((dim, ), dtype=nm.double)
mul = 1.0 / factorial(dim)
if dim == 3:
mul *= -1.0
mtx = nm.ones((nel, dim + 1, dim + 1), dtype=nm.double)
mtx[:,:,:-1] = nd[el,:]
vols = mul * dets_fast(mtx)
vol = vols.sum()
bc = nm.dot(vols, mtx.sum(1)[:,:-1] / nnd)
bc /= vol
return vol, bc
from sfepy.base.timing import Timer
output('smoothing...')
timer = Timer(start=True)
if weights is None:
n_nod = mesh.n_nod
domain = FEDomain('mesh', mesh)
cmesh = domain.cmesh
# initiate all vertices as inner - hierarchy = 2
node_group = nm.ones((n_nod,), dtype=nm.int16) * 2
# boundary vertices - set hierarchy = 4
if bconstr:
# get "vertices of surface"
facets = cmesh.get_surface_facets()
f_verts = cmesh.get_incident(0, facets, cmesh.dim - 1)
node_group[f_verts] = 4
# generate costs matrix
e_verts = cmesh.get_conn(1, 0).indices
fc1, fc2 = e_verts[0::2], e_verts[1::2]
idxs = nm.where(node_group[fc2] >= node_group[fc1])
rows1 = fc1[idxs]
cols1 = fc2[idxs]
idxs = nm.where(node_group[fc1] >= node_group[fc2])
rows2 = fc2[idxs]
cols2 = fc1[idxs]
crows = nm.concatenate((rows1, rows2))
ccols = nm.concatenate((cols1, cols2))
costs = sps.coo_matrix((nm.ones_like(crows), (crows, ccols)),
shape=(n_nod, n_nod),
dtype=nm.double)
# generate weights matrix
idxs = list(range(n_nod))
aux = sps.coo_matrix((1.0 / nm.asarray(costs.sum(1)).squeeze(),
(idxs, idxs)),
shape=(n_nod, n_nod),
dtype=nm.double)
#aux.setdiag(1.0 / costs.sum(1))
weights = (aux.tocsc() * costs.tocsc()).tocsr()
coors = taubin(mesh.coors, weights, lam, mu, n_iter)
output('...done in %.2f s' % timer.stop())
if volume_corr:
output('rescaling...')
timer.start()
volume0, bc = get_volume(mesh.conns[0], mesh.coors)
volume, _ = get_volume(mesh.conns[0], coors)
scale = volume0 / volume
| output('scale factor: %.2f' % scale) | sfepy.base.base.output |
from __future__ import absolute_import
from sfepy.discrete.fem import Mesh, FEDomain
import scipy.sparse as sps
import numpy as nm
from sfepy.base.compat import factorial
from sfepy.base.base import output
from six.moves import range
def elems_q2t(el):
nel, nnd = el.shape
if nnd > 4:
q2t = nm.array([[0, 2, 3, 6],
[0, 3, 7, 6],
[0, 7, 4, 6],
[0, 5, 6, 4],
[1, 5, 6, 0],
[1, 6, 2, 0]])
else:
q2t = nm.array([[0, 1, 2],
[0, 2, 3]])
ns, nn = q2t.shape
nel *= ns
out = nm.zeros((nel, nn), dtype=nm.int32);
for ii in range(ns):
idxs = nm.arange(ii, nel, ns)
out[idxs,:] = el[:, q2t[ii,:]]
return nm.ascontiguousarray(out)
def triangulate(mesh, verbose=False):
"""
Triangulate a 2D or 3D tensor product mesh: quadrilaterals->triangles,
hexahedrons->tetrahedrons.
Parameters
----------
mesh : Mesh
The input mesh.
Returns
-------
mesh : Mesh
The triangulated mesh.
"""
conns = None
for k, new_desc in [('3_8', '3_4'), ('2_4', '2_3')]:
if k in mesh.descs:
conns = mesh.get_conn(k)
break
if conns is not None:
nelo = conns.shape[0]
output('initial mesh: %d elements' % nelo, verbose=verbose)
new_conns = elems_q2t(conns)
nn = new_conns.shape[0] // nelo
new_cgroups = nm.repeat(mesh.cmesh.cell_groups, nn)
output('new mesh: %d elements' % new_conns.shape[0], verbose=verbose)
mesh = Mesh.from_data(mesh.name, mesh.coors,
mesh.cmesh.vertex_groups,
[new_conns], [new_cgroups], [new_desc])
return mesh
def smooth_mesh(mesh, n_iter=4, lam=0.6307, mu=-0.6347,
weights=None, bconstr=True,
volume_corr=False):
"""
FE mesh smoothing.
Based on:
[1] <NAME>, <NAME>, Smooth surface meshing for automated
finite element model generation from 3D image data, Journal of
Biomechanics, Volume 39, Issue 7, 2006, Pages 1287-1295,
ISSN 0021-9290, 10.1016/j.jbiomech.2005.03.006.
(http://www.sciencedirect.com/science/article/pii/S0021929005001442)
Parameters
----------
mesh : mesh
FE mesh.
n_iter : integer, optional
Number of iteration steps.
lam : float, optional
Smoothing factor, see [1].
mu : float, optional
Unshrinking factor, see [1].
weights : array, optional
Edge weights, see [1].
bconstr: logical, optional
Boundary constraints, if True only surface smoothing performed.
volume_corr: logical, optional
Correct volume after smoothing process.
Returns
-------
coors : array
Coordinates of mesh nodes.
"""
def laplacian(coors, weights):
n_nod = coors.shape[0]
displ = (weights - sps.identity(n_nod)) * coors
return displ
def taubin(coors0, weights, lam, mu, n_iter):
coors = coors0.copy()
for ii in range(n_iter):
displ = laplacian(coors, weights)
if nm.mod(ii, 2) == 0:
coors += lam * displ
else:
coors += mu * displ
return coors
def get_volume(el, nd):
from sfepy.linalg.utils import dets_fast
dim = nd.shape[1]
nnd = el.shape[1]
etype = '%d_%d' % (dim, nnd)
if etype == '2_4' or etype == '3_8':
el = elems_q2t(el)
nel = el.shape[0]
#bc = nm.zeros((dim, ), dtype=nm.double)
mul = 1.0 / | factorial(dim) | sfepy.base.compat.factorial |
from __future__ import absolute_import
from sfepy.discrete.fem import Mesh, FEDomain
import scipy.sparse as sps
import numpy as nm
from sfepy.base.compat import factorial
from sfepy.base.base import output
from six.moves import range
def elems_q2t(el):
nel, nnd = el.shape
if nnd > 4:
q2t = nm.array([[0, 2, 3, 6],
[0, 3, 7, 6],
[0, 7, 4, 6],
[0, 5, 6, 4],
[1, 5, 6, 0],
[1, 6, 2, 0]])
else:
q2t = nm.array([[0, 1, 2],
[0, 2, 3]])
ns, nn = q2t.shape
nel *= ns
out = nm.zeros((nel, nn), dtype=nm.int32);
for ii in range(ns):
idxs = nm.arange(ii, nel, ns)
out[idxs,:] = el[:, q2t[ii,:]]
return nm.ascontiguousarray(out)
def triangulate(mesh, verbose=False):
"""
Triangulate a 2D or 3D tensor product mesh: quadrilaterals->triangles,
hexahedrons->tetrahedrons.
Parameters
----------
mesh : Mesh
The input mesh.
Returns
-------
mesh : Mesh
The triangulated mesh.
"""
conns = None
for k, new_desc in [('3_8', '3_4'), ('2_4', '2_3')]:
if k in mesh.descs:
conns = mesh.get_conn(k)
break
if conns is not None:
nelo = conns.shape[0]
output('initial mesh: %d elements' % nelo, verbose=verbose)
new_conns = elems_q2t(conns)
nn = new_conns.shape[0] // nelo
new_cgroups = nm.repeat(mesh.cmesh.cell_groups, nn)
output('new mesh: %d elements' % new_conns.shape[0], verbose=verbose)
mesh = Mesh.from_data(mesh.name, mesh.coors,
mesh.cmesh.vertex_groups,
[new_conns], [new_cgroups], [new_desc])
return mesh
def smooth_mesh(mesh, n_iter=4, lam=0.6307, mu=-0.6347,
weights=None, bconstr=True,
volume_corr=False):
"""
FE mesh smoothing.
Based on:
[1] <NAME>, <NAME>, Smooth surface meshing for automated
finite element model generation from 3D image data, Journal of
Biomechanics, Volume 39, Issue 7, 2006, Pages 1287-1295,
ISSN 0021-9290, 10.1016/j.jbiomech.2005.03.006.
(http://www.sciencedirect.com/science/article/pii/S0021929005001442)
Parameters
----------
mesh : mesh
FE mesh.
n_iter : integer, optional
Number of iteration steps.
lam : float, optional
Smoothing factor, see [1].
mu : float, optional
Unshrinking factor, see [1].
weights : array, optional
Edge weights, see [1].
bconstr: logical, optional
Boundary constraints, if True only surface smoothing performed.
volume_corr: logical, optional
Correct volume after smoothing process.
Returns
-------
coors : array
Coordinates of mesh nodes.
"""
def laplacian(coors, weights):
n_nod = coors.shape[0]
displ = (weights - sps.identity(n_nod)) * coors
return displ
def taubin(coors0, weights, lam, mu, n_iter):
coors = coors0.copy()
for ii in range(n_iter):
displ = laplacian(coors, weights)
if nm.mod(ii, 2) == 0:
coors += lam * displ
else:
coors += mu * displ
return coors
def get_volume(el, nd):
from sfepy.linalg.utils import dets_fast
dim = nd.shape[1]
nnd = el.shape[1]
etype = '%d_%d' % (dim, nnd)
if etype == '2_4' or etype == '3_8':
el = elems_q2t(el)
nel = el.shape[0]
#bc = nm.zeros((dim, ), dtype=nm.double)
mul = 1.0 / factorial(dim)
if dim == 3:
mul *= -1.0
mtx = nm.ones((nel, dim + 1, dim + 1), dtype=nm.double)
mtx[:,:,:-1] = nd[el,:]
vols = mul * | dets_fast(mtx) | sfepy.linalg.utils.dets_fast |
import numpy as nm
from sfepy.base.base import assert_, Struct
from sfepy.terms.terms import terms
from sfepy.terms.terms_hyperelastic_base import HyperElasticBase
class HyperElasticTLBase(HyperElasticBase):
"""
Base class for all hyperelastic terms in TL formulation family.
The subclasses should have the following static method attributes:
- `stress_function()` (the stress)
- `tan_mod_function()` (the tangent modulus)
The common (family) data are cached in the evaluate cache of state
variable.
"""
family_function = staticmethod(terms.dq_finite_strain_tl)
weak_function = staticmethod(terms.dw_he_rtm)
fd_cache_name = 'tl_common'
hyperelastic_mode = 0
def compute_family_data(self, state):
ap, vg = self.get_approximation(state)
vec = self.get_vector(state)
n_el, n_qp, dim, n_en, n_c = self.get_data_shape(state)
sym = dim * (dim + 1) / 2
shapes = {
'mtx_f' : (n_el, n_qp, dim, dim),
'det_f' : (n_el, n_qp, 1, 1),
'sym_c' : (n_el, n_qp, sym, 1),
'tr_c' : (n_el, n_qp, 1, 1),
'in2_c' : (n_el, n_qp, 1, 1),
'sym_inv_c' : (n_el, n_qp, sym, 1),
'green_strain' : (n_el, n_qp, sym, 1),
}
data = | Struct(name='tl_family_data') | sfepy.base.base.Struct |
import numpy as nm
from sfepy.base.base import assert_, Struct
from sfepy.terms.terms import terms
from sfepy.terms.terms_hyperelastic_base import HyperElasticBase
class HyperElasticTLBase(HyperElasticBase):
"""
Base class for all hyperelastic terms in TL formulation family.
The subclasses should have the following static method attributes:
- `stress_function()` (the stress)
- `tan_mod_function()` (the tangent modulus)
The common (family) data are cached in the evaluate cache of state
variable.
"""
family_function = staticmethod(terms.dq_finite_strain_tl)
weak_function = staticmethod(terms.dw_he_rtm)
fd_cache_name = 'tl_common'
hyperelastic_mode = 0
def compute_family_data(self, state):
ap, vg = self.get_approximation(state)
vec = self.get_vector(state)
n_el, n_qp, dim, n_en, n_c = self.get_data_shape(state)
sym = dim * (dim + 1) / 2
shapes = {
'mtx_f' : (n_el, n_qp, dim, dim),
'det_f' : (n_el, n_qp, 1, 1),
'sym_c' : (n_el, n_qp, sym, 1),
'tr_c' : (n_el, n_qp, 1, 1),
'in2_c' : (n_el, n_qp, 1, 1),
'sym_inv_c' : (n_el, n_qp, sym, 1),
'green_strain' : (n_el, n_qp, sym, 1),
}
data = Struct(name='tl_family_data')
for key, shape in shapes.iteritems():
setattr(data, key, nm.zeros(shape, dtype=nm.float64))
self.family_function(data.mtx_f,
data.det_f,
data.sym_c,
data.tr_c,
data.in2_c,
data.sym_inv_c,
data.green_strain,
vec, vg, ap.econn)
return data
class NeoHookeanTLTerm(HyperElasticTLBase):
r"""
Hyperelastic neo-Hookean term. Effective stress
:math:`S_{ij} = \mu J^{-\frac{2}{3}}(\delta_{ij} -
\frac{1}{3}C_{kk}C_{ij}^{-1})`.
:Definition:
.. math::
\int_{\Omega} S_{ij}(\ul{u}) \delta E_{ij}(\ul{u};\ul{v})
:Arguments:
- material : :math:`\mu`
- virtual : :math:`\ul{v}`
- state : :math:`\ul{u}`
"""
name = 'dw_tl_he_neohook'
family_data_names = ['det_f', 'tr_c', 'sym_inv_c']
stress_function = staticmethod(terms.dq_tl_he_stress_neohook)
tan_mod_function = staticmethod(terms.dq_tl_he_tan_mod_neohook)
class MooneyRivlinTLTerm(HyperElasticTLBase):
r"""
Hyperelastic Mooney-Rivlin term. Effective stress
:math:`S_{ij} = \kappa J^{-\frac{4}{3}} (C_{kk} \delta_{ij} - C_{ij}
- \frac{2}{3 } I_2 C_{ij}^{-1})`.
:Definition:
.. math::
\int_{\Omega} S_{ij}(\ul{u}) \delta E_{ij}(\ul{u};\ul{v})
:Arguments:
- material : :math:`\kappa`
- virtual : :math:`\ul{v}`
- state : :math:`\ul{u}`
"""
name = 'dw_tl_he_mooney_rivlin'
family_data_names = ['det_f', 'tr_c', 'sym_inv_c', 'sym_c', 'in2_c']
stress_function = staticmethod(terms.dq_tl_he_stress_mooney_rivlin)
tan_mod_function = staticmethod(terms.dq_tl_he_tan_mod_mooney_rivlin)
class BulkPenaltyTLTerm(HyperElasticTLBase):
r"""
Hyperelastic bulk penalty term. Stress
:math:`S_{ij} = K(J-1)\; J C_{ij}^{-1}`.
:Definition:
.. math::
\int_{\Omega} S_{ij}(\ul{u}) \delta E_{ij}(\ul{u};\ul{v})
:Arguments:
- material : :math:`K`
- virtual : :math:`\ul{v}`
- state : :math:`\ul{u}`
"""
name = 'dw_tl_bulk_penalty'
family_data_names = ['det_f', 'sym_inv_c']
stress_function = staticmethod(terms.dq_tl_he_stress_bulk)
tan_mod_function = staticmethod(terms.dq_tl_he_tan_mod_bulk)
class BulkActiveTLTerm(HyperElasticTLBase):
r"""
Hyperelastic bulk active term. Stress :math:`S_{ij} = A J C_{ij}^{-1}`,
where :math:`A` is the activation in :math:`[0, F_{\rm max}]`.
:Definition:
.. math::
\int_{\Omega} S_{ij}(\ul{u}) \delta E_{ij}(\ul{u};\ul{v})
:Arguments:
- material : :math:`A`
- virtual : :math:`\ul{v}`
- state : :math:`\ul{u}`
"""
name = 'dw_tl_bulk_active'
family_data_names = ['det_f', 'sym_inv_c']
stress_function = staticmethod(terms.dq_tl_he_stress_bulk_active)
tan_mod_function = staticmethod(terms.dq_tl_he_tan_mod_bulk_active)
class BulkPressureTLTerm(HyperElasticTLBase):
r"""
Hyperelastic bulk pressure term. Stress
:math:`S_{ij} = -p J C_{ij}^{-1}`.
:Definition:
.. math::
\int_{\Omega} S_{ij}(p) \delta E_{ij}(\ul{u};\ul{v})
:Arguments:
- virtual : :math:`\ul{v}`
- state : :math:`\ul{u}`
- state_p : :math:`p`
"""
name = 'dw_tl_bulk_pressure'
arg_types = ('virtual', 'state', 'state_p')
arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'state_p' : 1}
family_data_names = ['det_f', 'sym_inv_c']
family_function = staticmethod(terms.dq_finite_strain_tl)
weak_function = staticmethod(terms.dw_he_rtm)
weak_dp_function = staticmethod(terms.dw_tl_volume)
stress_function = staticmethod(terms.dq_tl_stress_bulk_pressure)
tan_mod_u_function = staticmethod(terms.dq_tl_tan_mod_bulk_pressure_u)
def compute_data(self, family_data, mode, **kwargs):
det_f, sym_inv_c = family_data.det_f, family_data.sym_inv_c
p_qp = family_data.p_qp
if mode == 0:
out = nm.empty_like(sym_inv_c)
fun = self.stress_function
elif mode == 1:
shape = list(sym_inv_c.shape)
shape[-1] = shape[-2]
out = nm.empty(shape, dtype=nm.float64)
fun = self.tan_mod_u_function
else:
raise ValueError('bad mode! (%d)' % mode)
fun(out, p_qp, det_f, sym_inv_c)
return out
def get_fargs(self, virtual, state, state_p,
mode=None, term_mode=None, diff_var=None, **kwargs):
vgv, _ = self.get_mapping(state)
fd = self.get_family_data(state, 'tl_common', self.family_data_names)
fd.p_qp = self.get(state_p, 'val')
if mode == 'weak':
if diff_var != state_p.name:
if diff_var is None:
stress = self.compute_data(fd, 0, **kwargs)
self.stress_cache = stress
tan_mod = nm.array([0], ndmin=4, dtype=nm.float64)
fmode = 0
else:
stress = self.stress_cache
if stress is None:
stress = self.compute_data(fd, 0, **kwargs)
tan_mod = self.compute_data(fd, 1, **kwargs)
fmode = 1
fargs = (self.weak_function,
stress, tan_mod, fd.mtx_f, fd.det_f, vgv, fmode, 0)
else:
vgs, _ = self.get_mapping(state_p)
fargs = (self.weak_dp_function,
fd.mtx_f, fd.sym_inv_c, fd.det_f, vgs, vgv, 1, -1)
return fargs
elif mode == 'el_avg':
if term_mode == 'strain':
out_qp = fd.green_strain
elif term_mode == 'stress':
out_qp = self.compute_data(fd, 0, **kwargs)
else:
raise ValueError('unsupported term mode in %s! (%s)'
% (self.name, term_mode))
return self.integrate, out_qp, vgv, 1
else:
raise ValueError('unsupported evaluation mode in %s! (%s)'
% (self.name, mode))
def get_eval_shape(self, virtual, state, state_p,
mode=None, term_mode=None, diff_var=None, **kwargs):
n_el, n_qp, dim, n_en, n_c = self.get_data_shape(state)
sym = dim * (dim + 1) / 2
return (n_el, 1, sym, 1), state.dtype
class VolumeTLTerm(HyperElasticTLBase):
r"""
Volume term (weak form) in the total Lagrangian formulation.
:Definition:
.. math::
\begin{array}{l}
\int_{\Omega} q J(\ul{u}) \\
\mbox{volume mode: vector for } K \from \Ical_h: \int_{T_K}
J(\ul{u}) \\
\mbox{rel\_volume mode: vector for } K \from \Ical_h:
\int_{T_K} J(\ul{u}) / \int_{T_K} 1
\end{array}
:Arguments:
- virtual : :math:`q`
- state : :math:`\ul{u}`
"""
name = 'dw_tl_volume'
arg_types = ('virtual', 'state')
arg_shapes = {'virtual' : (1, None), 'state' : 'D'}
family_data_names = ['mtx_f', 'det_f', 'sym_inv_c']
function = staticmethod(terms.dw_tl_volume)
def get_fargs(self, virtual, state,
mode=None, term_mode=None, diff_var=None, **kwargs):
vgs, _ = self.get_mapping(virtual)
vgv, _ = self.get_mapping(state)
fd = self.get_family_data(state, 'tl_common', self.family_data_names)
if mode == 'weak':
if diff_var is None:
fmode = 0
else:
fmode = 1
elif (mode == 'eval') or (mode == 'el_avg'):
if term_mode == 'volume':
fmode = 2
elif term_mode == 'rel_volume':
fmode = 3
else:
raise ValueError('unsupported term evaluation mode in %s! (%s)'
% (self.name, term_mode))
else:
raise ValueError('unsupported evaluation mode in %s! (%s)'
% (self.name, mode))
return fd.mtx_f, fd.sym_inv_c, fd.det_f, vgs, vgv, 0, fmode
def get_eval_shape(self, virtual, state,
mode=None, term_mode=None, diff_var=None, **kwargs):
n_el, n_qp, dim, n_en, n_c = self.get_data_shape(state)
return (n_el, 1, 1, 1), state.dtype
class DiffusionTLTerm(HyperElasticTLBase):
r"""
Diffusion term in the total Lagrangian formulation with
linearized deformation-dependent permeability
:math:`\ull{K}(\ul{u}) = J \ull{F}^{-1} \ull{k} f(J) \ull{F}^{-T}`,
where :math:`\ul{u}` relates to the previous time step :math:`(n-1)`
and
:math:`f(J) = \max\left(0, \left(1 + \frac{(J - 1)}{N_f}\right)\right)^2`
expresses the dependence on volume compression/expansion.
:Definition:
.. math::
\int_{\Omega} \ull{K}(\ul{u}^{(n-1)}) : \pdiff{q}{\ul{X}}
\pdiff{p}{\ul{X}}
:Arguments:
- material_1 : :math:`\ull{k}`
- material_2 : :math:`N_f`
- virtual : :math:`q`
- state : :math:`p`
- parameter : :math:`\ul{u}^{(n-1)}`
"""
name = 'dw_tl_diffusion'
arg_types = ('material_1', 'material_2', 'virtual', 'state', 'parameter')
arg_shapes = {'material_1' : 'D, D', 'material_2' : '1, 1',
'virtual' : (1, 'state'), 'state' : 1, 'parameter' : 'D'}
family_data_names = ['mtx_f', 'det_f']
function = staticmethod(terms.dw_tl_diffusion)
def get_fargs(self, perm, ref_porosity, virtual, state, parameter,
mode=None, term_mode=None, diff_var=None, **kwargs):
vgv, _ = self.get_mapping(parameter)
fd = self.get_family_data(parameter, 'tl_common',
self.family_data_names)
grad = self.get(state, 'grad')
if mode == 'weak':
if diff_var is None:
fmode = 0
else:
fmode = 1
elif mode == 'el_avg':
if term_mode == 'diffusion_velocity':
fmode = 2
else:
raise ValueError('unsupported term evaluation mode in %s! (%s)'
% (self.name, term_mode))
else:
raise ValueError('unsupported evaluation mode in %s! (%s)'
% (self.name, mode))
return grad, perm, ref_porosity, fd.mtx_f, fd.det_f, vgv, fmode
def get_eval_shape(self, perm, ref_porosity, virtual, state, parameter,
mode=None, term_mode=None, diff_var=None, **kwargs):
n_el, n_qp, dim, n_en, n_c = self.get_data_shape(state)
return (n_el, 1, dim, 1), state.dtype
class HyperElasticSurfaceTLBase(HyperElasticBase):
"""
Base class for all hyperelastic surface terms in TL formulation family.
"""
family_function = staticmethod(terms.dq_tl_finite_strain_surface)
fd_cache_name = 'tl_surface_common'
def compute_family_data(self, state):
ap, sg = self.get_approximation(state)
sd = ap.surface_data[self.region.name]
vec = self.get_vector(state)
n_el, n_qp, dim, n_en, n_c = self.get_data_shape(state)
shapes = {
'mtx_f' : (n_el, n_qp, dim, dim),
'det_f' : (n_el, n_qp, 1, 1),
'inv_f' : (n_el, n_qp, dim, dim),
}
data = | Struct(name='tl_surface_family_data') | sfepy.base.base.Struct |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 9 19:16:05 2021
@author: shrohanmohapatra
"""
r"""
Navier-Stokes equations for incompressible fluid flow in 2D.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}
+ \int_{\Omega} ((\ul{u} \cdot \nabla) \ul{u}) \cdot \ul{v}
- \int_{\Omega} p\ \nabla \cdot \ul{v}
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \nabla \cdot \ul{u}
= 0
\;, \quad \forall q \;.
The mesh is created by ``gen_block_mesh()`` function.
View the results using::
$ ./postproc.py user_block.vtk -b
"""
#from __future__ import absolute_import
from sfepy.discrete.fem.meshio import UserMeshIO
from sfepy.mesh.mesh_generators import gen_block_mesh
import numpy as nm
# Mesh dimensions.
dims = [0.1, 0.1]
# Mesh resolution: increase to improve accuracy.
shape = [75, 75]
def mesh_hook(mesh, mode):
"""
Generate the block mesh.
"""
if mode == 'read':
mesh = gen_block_mesh(dims, shape, [0, 0],
name='user_block', verbose=False)
return mesh
elif mode == 'write':
pass
filename_mesh = | UserMeshIO(mesh_hook) | sfepy.discrete.fem.meshio.UserMeshIO |
from __future__ import absolute_import
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 sfepy.linalg as la
import sfepy.base.multiproc as multi
import os.path as op
import six
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 |
from __future__ import absolute_import
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 sfepy.linalg as la
import sfepy.base.multiproc as multi
import os.path as op
import six
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 |
from __future__ import absolute_import
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 sfepy.linalg as la
import sfepy.base.multiproc as multi
import os.path as op
import six
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.is_hdf5_file( 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 six.iteritems(coefs.__dict__):
out[key] = val
elif mode == 'qp':
for key, val in six.iteritems(coefs.__dict__):
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 six.iteritems(val):
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_homog_coefs_nonlinear(ts, coor, mode, mtx_f=None,
term=None, problem=None,
iteration=None, **kwargs):
if not (mode == 'qp'):
return
oprefix = output.prefix
output.prefix = 'micro:'
if not hasattr(problem, 'homogen_app'):
required, other = | get_standard_keywords() | sfepy.base.conf.get_standard_keywords |
from __future__ import absolute_import
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 sfepy.linalg as la
import sfepy.base.multiproc as multi
import os.path as op
import six
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.is_hdf5_file( 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 six.iteritems(coefs.__dict__):
out[key] = val
elif mode == 'qp':
for key, val in six.iteritems(coefs.__dict__):
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 six.iteritems(val):
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_homog_coefs_nonlinear(ts, coor, mode, mtx_f=None,
term=None, problem=None,
iteration=None, **kwargs):
if not (mode == 'qp'):
return
oprefix = output.prefix
output.prefix = 'micro:'
if not hasattr(problem, 'homogen_app'):
required, other = get_standard_keywords()
required.remove('equations')
micro_file = problem.conf.options.micro_filename
conf = ProblemConf.from_file(micro_file, required, other,
verbose=False)
options = | Struct(output_filename_trunk=None) | sfepy.base.base.Struct |
from __future__ import absolute_import
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 sfepy.linalg as la
import sfepy.base.multiproc as multi
import os.path as op
import six
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.is_hdf5_file( 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 six.iteritems(coefs.__dict__):
out[key] = val
elif mode == 'qp':
for key, val in six.iteritems(coefs.__dict__):
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 six.iteritems(val):
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_homog_coefs_nonlinear(ts, coor, mode, mtx_f=None,
term=None, problem=None,
iteration=None, **kwargs):
if not (mode == 'qp'):
return
oprefix = output.prefix
output.prefix = 'micro:'
if not hasattr(problem, 'homogen_app'):
required, other = get_standard_keywords()
required.remove('equations')
micro_file = problem.conf.options.micro_filename
conf = ProblemConf.from_file(micro_file, required, other,
verbose=False)
options = Struct(output_filename_trunk=None)
app = HomogenizationApp(conf, options, 'micro:',
n_micro=coor.shape[0], update_micro_coors=True)
problem.homogen_app = app
if hasattr(app.app_options, 'use_mpi') and app.app_options.use_mpi:
multiproc, multiproc_mode = multi.get_multiproc(mpi=True)
multi_mpi = multiproc if multiproc_mode == 'mpi' else None
else:
multi_mpi = None
app.multi_mpi = multi_mpi
if multi_mpi is not None:
multi_mpi.master_send_task('init', (micro_file, coor.shape[0]))
else:
app = problem.homogen_app
multi_mpi = app.multi_mpi
def_grad = mtx_f(problem, term) if callable(mtx_f) else mtx_f
if hasattr(problem, 'def_grad_prev'):
rel_def_grad = la.dot_sequences(def_grad,
nm.linalg.inv(problem.def_grad_prev),
'AB')
else:
rel_def_grad = def_grad.copy()
problem.def_grad_prev = def_grad.copy()
app.setup_macro_deformation(rel_def_grad)
if multi_mpi is not None:
multi_mpi.master_send_task('calculate', (rel_def_grad, ts, iteration))
coefs, deps = app(ret_all=True, itime=ts.step, iiter=iteration)
if type(coefs) is tuple:
coefs = coefs[0]
out = {}
for key, val in six.iteritems(coefs.__dict__):
if isinstance(val, list):
out[key] = nm.array(val)
elif isinstance(val, dict):
for key2, val2 in six.iteritems(val):
out[key+'_'+key2] = nm.array(val2)
for key in six.iterkeys(out):
shape = out[key].shape
if len(shape) == 1:
out[key] = out[key].reshape(shape + (1, 1))
elif len(shape) == 2:
out[key] = out[key].reshape(shape + (1,))
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 six.iteritems(dump_names):
corr_name = op.split( val )[-1]
io = | HDF5MeshIO( val+'.h5' ) | sfepy.discrete.fem.meshio.HDF5MeshIO |
from __future__ import absolute_import
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 sfepy.linalg as la
import sfepy.base.multiproc as multi
import os.path as op
import six
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.is_hdf5_file( 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 six.iteritems(coefs.__dict__):
out[key] = val
elif mode == 'qp':
for key, val in six.iteritems(coefs.__dict__):
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 six.iteritems(val):
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_homog_coefs_nonlinear(ts, coor, mode, mtx_f=None,
term=None, problem=None,
iteration=None, **kwargs):
if not (mode == 'qp'):
return
oprefix = output.prefix
output.prefix = 'micro:'
if not hasattr(problem, 'homogen_app'):
required, other = get_standard_keywords()
required.remove('equations')
micro_file = problem.conf.options.micro_filename
conf = ProblemConf.from_file(micro_file, required, other,
verbose=False)
options = Struct(output_filename_trunk=None)
app = HomogenizationApp(conf, options, 'micro:',
n_micro=coor.shape[0], update_micro_coors=True)
problem.homogen_app = app
if hasattr(app.app_options, 'use_mpi') and app.app_options.use_mpi:
multiproc, multiproc_mode = | multi.get_multiproc(mpi=True) | sfepy.base.multiproc.get_multiproc |
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_elastic_constants(self):
import numpy as nm
from sfepy.mechanics.matcoefs import ElasticConstants
ok = True
names = ['bulk', 'lam', 'mu', 'young', 'poisson', 'p_wave']
ec = | ElasticConstants(lam=1.0, mu=1.5) | sfepy.mechanics.matcoefs.ElasticConstants |
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_elastic_constants(self):
import numpy as nm
from sfepy.mechanics.matcoefs import ElasticConstants
ok = True
names = ['bulk', 'lam', 'mu', 'young', 'poisson', 'p_wave']
ec = ElasticConstants(lam=1.0, mu=1.5)
vals = ec.get(names)
self.report('using values:', vals)
for i1 in range(len(names)):
for i2 in range(i1+1, len(names)):
kwargs = {names[i1] : vals[i1], names[i2] : vals[i2]}
try:
ec.init(**kwargs)
except:
_ok = False
else:
_ok = True
ec_vals = ec.get(names)
_ok = _ok and nm.allclose(ec_vals, vals)
self.report(names[i1], names[i2], '->', _ok)
if not _ok:
self.report('correct:', vals)
self.report(' got:', ec_vals)
ok = ok and _ok
return ok
def test_conversion_functions(self):
import numpy as nm
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 1.5
ec = | mc.ElasticConstants(lam=lam, mu=mu) | sfepy.mechanics.matcoefs.ElasticConstants |
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_elastic_constants(self):
import numpy as nm
from sfepy.mechanics.matcoefs import ElasticConstants
ok = True
names = ['bulk', 'lam', 'mu', 'young', 'poisson', 'p_wave']
ec = ElasticConstants(lam=1.0, mu=1.5)
vals = ec.get(names)
self.report('using values:', vals)
for i1 in range(len(names)):
for i2 in range(i1+1, len(names)):
kwargs = {names[i1] : vals[i1], names[i2] : vals[i2]}
try:
ec.init(**kwargs)
except:
_ok = False
else:
_ok = True
ec_vals = ec.get(names)
_ok = _ok and nm.allclose(ec_vals, vals)
self.report(names[i1], names[i2], '->', _ok)
if not _ok:
self.report('correct:', vals)
self.report(' got:', ec_vals)
ok = ok and _ok
return ok
def test_conversion_functions(self):
import numpy as nm
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 1.5
ec = mc.ElasticConstants(lam=lam, mu=mu)
young, poisson, bulk = ec.get(['young', 'poisson', 'bulk'])
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
young = nm.array([young] * 3)
poisson = nm.array([poisson] * 3)
_lam, _mu = | mc.lame_from_youngpoisson(young, poisson) | sfepy.mechanics.matcoefs.lame_from_youngpoisson |
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_elastic_constants(self):
import numpy as nm
from sfepy.mechanics.matcoefs import ElasticConstants
ok = True
names = ['bulk', 'lam', 'mu', 'young', 'poisson', 'p_wave']
ec = ElasticConstants(lam=1.0, mu=1.5)
vals = ec.get(names)
self.report('using values:', vals)
for i1 in range(len(names)):
for i2 in range(i1+1, len(names)):
kwargs = {names[i1] : vals[i1], names[i2] : vals[i2]}
try:
ec.init(**kwargs)
except:
_ok = False
else:
_ok = True
ec_vals = ec.get(names)
_ok = _ok and nm.allclose(ec_vals, vals)
self.report(names[i1], names[i2], '->', _ok)
if not _ok:
self.report('correct:', vals)
self.report(' got:', ec_vals)
ok = ok and _ok
return ok
def test_conversion_functions(self):
import numpy as nm
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 1.5
ec = mc.ElasticConstants(lam=lam, mu=mu)
young, poisson, bulk = ec.get(['young', 'poisson', 'bulk'])
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
young = nm.array([young] * 3)
poisson = nm.array([poisson] * 3)
_lam, _mu = mc.lame_from_youngpoisson(young, poisson)
_ok = (nm.allclose(lam, _lam, rtol=0.0, atol=1e-14) and
nm.allclose(mu, _mu, rtol=0.0, atol=1e-14))
self.report('lame_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', lam, mu)
self.report(' got:', _lam, _mu)
ok = ok and _ok
_bulk = | mc.bulk_from_youngpoisson(young, poisson) | sfepy.mechanics.matcoefs.bulk_from_youngpoisson |
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_elastic_constants(self):
import numpy as nm
from sfepy.mechanics.matcoefs import ElasticConstants
ok = True
names = ['bulk', 'lam', 'mu', 'young', 'poisson', 'p_wave']
ec = ElasticConstants(lam=1.0, mu=1.5)
vals = ec.get(names)
self.report('using values:', vals)
for i1 in range(len(names)):
for i2 in range(i1+1, len(names)):
kwargs = {names[i1] : vals[i1], names[i2] : vals[i2]}
try:
ec.init(**kwargs)
except:
_ok = False
else:
_ok = True
ec_vals = ec.get(names)
_ok = _ok and nm.allclose(ec_vals, vals)
self.report(names[i1], names[i2], '->', _ok)
if not _ok:
self.report('correct:', vals)
self.report(' got:', ec_vals)
ok = ok and _ok
return ok
def test_conversion_functions(self):
import numpy as nm
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 1.5
ec = mc.ElasticConstants(lam=lam, mu=mu)
young, poisson, bulk = ec.get(['young', 'poisson', 'bulk'])
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
young = nm.array([young] * 3)
poisson = nm.array([poisson] * 3)
_lam, _mu = mc.lame_from_youngpoisson(young, poisson)
_ok = (nm.allclose(lam, _lam, rtol=0.0, atol=1e-14) and
nm.allclose(mu, _mu, rtol=0.0, atol=1e-14))
self.report('lame_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', lam, mu)
self.report(' got:', _lam, _mu)
ok = ok and _ok
_bulk = mc.bulk_from_youngpoisson(young, poisson)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
_bulk = | mc.bulk_from_lame(lam, mu) | sfepy.mechanics.matcoefs.bulk_from_lame |
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_elastic_constants(self):
import numpy as nm
from sfepy.mechanics.matcoefs import ElasticConstants
ok = True
names = ['bulk', 'lam', 'mu', 'young', 'poisson', 'p_wave']
ec = ElasticConstants(lam=1.0, mu=1.5)
vals = ec.get(names)
self.report('using values:', vals)
for i1 in range(len(names)):
for i2 in range(i1+1, len(names)):
kwargs = {names[i1] : vals[i1], names[i2] : vals[i2]}
try:
ec.init(**kwargs)
except:
_ok = False
else:
_ok = True
ec_vals = ec.get(names)
_ok = _ok and nm.allclose(ec_vals, vals)
self.report(names[i1], names[i2], '->', _ok)
if not _ok:
self.report('correct:', vals)
self.report(' got:', ec_vals)
ok = ok and _ok
return ok
def test_conversion_functions(self):
import numpy as nm
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 1.5
ec = mc.ElasticConstants(lam=lam, mu=mu)
young, poisson, bulk = ec.get(['young', 'poisson', 'bulk'])
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
young = nm.array([young] * 3)
poisson = nm.array([poisson] * 3)
_lam, _mu = mc.lame_from_youngpoisson(young, poisson)
_ok = (nm.allclose(lam, _lam, rtol=0.0, atol=1e-14) and
nm.allclose(mu, _mu, rtol=0.0, atol=1e-14))
self.report('lame_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', lam, mu)
self.report(' got:', _lam, _mu)
ok = ok and _ok
_bulk = mc.bulk_from_youngpoisson(young, poisson)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
_bulk = mc.bulk_from_lame(lam, mu)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_lame():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
return ok
def test_stiffness_tensors(self):
import numpy as nm
from sfepy.base.base import assert_
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 4.0
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
d = nm.array([[ 9., 1., 1., 0., 0., 0.],
[ 1., 9., 1., 0., 0., 0.],
[ 1., 1., 9., 0., 0., 0.],
[ 0., 0., 0., 4., 0., 0.],
[ 0., 0., 0., 0., 4., 0.],
[ 0., 0., 0., 0., 0., 4.]])
_ds = | mc.stiffness_from_lame(3, lam, mu) | sfepy.mechanics.matcoefs.stiffness_from_lame |
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_elastic_constants(self):
import numpy as nm
from sfepy.mechanics.matcoefs import ElasticConstants
ok = True
names = ['bulk', 'lam', 'mu', 'young', 'poisson', 'p_wave']
ec = ElasticConstants(lam=1.0, mu=1.5)
vals = ec.get(names)
self.report('using values:', vals)
for i1 in range(len(names)):
for i2 in range(i1+1, len(names)):
kwargs = {names[i1] : vals[i1], names[i2] : vals[i2]}
try:
ec.init(**kwargs)
except:
_ok = False
else:
_ok = True
ec_vals = ec.get(names)
_ok = _ok and nm.allclose(ec_vals, vals)
self.report(names[i1], names[i2], '->', _ok)
if not _ok:
self.report('correct:', vals)
self.report(' got:', ec_vals)
ok = ok and _ok
return ok
def test_conversion_functions(self):
import numpy as nm
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 1.5
ec = mc.ElasticConstants(lam=lam, mu=mu)
young, poisson, bulk = ec.get(['young', 'poisson', 'bulk'])
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
young = nm.array([young] * 3)
poisson = nm.array([poisson] * 3)
_lam, _mu = mc.lame_from_youngpoisson(young, poisson)
_ok = (nm.allclose(lam, _lam, rtol=0.0, atol=1e-14) and
nm.allclose(mu, _mu, rtol=0.0, atol=1e-14))
self.report('lame_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', lam, mu)
self.report(' got:', _lam, _mu)
ok = ok and _ok
_bulk = mc.bulk_from_youngpoisson(young, poisson)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
_bulk = mc.bulk_from_lame(lam, mu)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_lame():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
return ok
def test_stiffness_tensors(self):
import numpy as nm
from sfepy.base.base import assert_
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 4.0
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
d = nm.array([[ 9., 1., 1., 0., 0., 0.],
[ 1., 9., 1., 0., 0., 0.],
[ 1., 1., 9., 0., 0., 0.],
[ 0., 0., 0., 4., 0., 0.],
[ 0., 0., 0., 0., 4., 0.],
[ 0., 0., 0., 0., 0., 4.]])
_ds = mc.stiffness_from_lame(3, lam, mu)
| assert_(_ds.shape == (3, 6, 6)) | sfepy.base.base.assert_ |
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_elastic_constants(self):
import numpy as nm
from sfepy.mechanics.matcoefs import ElasticConstants
ok = True
names = ['bulk', 'lam', 'mu', 'young', 'poisson', 'p_wave']
ec = ElasticConstants(lam=1.0, mu=1.5)
vals = ec.get(names)
self.report('using values:', vals)
for i1 in range(len(names)):
for i2 in range(i1+1, len(names)):
kwargs = {names[i1] : vals[i1], names[i2] : vals[i2]}
try:
ec.init(**kwargs)
except:
_ok = False
else:
_ok = True
ec_vals = ec.get(names)
_ok = _ok and nm.allclose(ec_vals, vals)
self.report(names[i1], names[i2], '->', _ok)
if not _ok:
self.report('correct:', vals)
self.report(' got:', ec_vals)
ok = ok and _ok
return ok
def test_conversion_functions(self):
import numpy as nm
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 1.5
ec = mc.ElasticConstants(lam=lam, mu=mu)
young, poisson, bulk = ec.get(['young', 'poisson', 'bulk'])
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
young = nm.array([young] * 3)
poisson = nm.array([poisson] * 3)
_lam, _mu = mc.lame_from_youngpoisson(young, poisson)
_ok = (nm.allclose(lam, _lam, rtol=0.0, atol=1e-14) and
nm.allclose(mu, _mu, rtol=0.0, atol=1e-14))
self.report('lame_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', lam, mu)
self.report(' got:', _lam, _mu)
ok = ok and _ok
_bulk = mc.bulk_from_youngpoisson(young, poisson)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
_bulk = mc.bulk_from_lame(lam, mu)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_lame():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
return ok
def test_stiffness_tensors(self):
import numpy as nm
from sfepy.base.base import assert_
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 4.0
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
d = nm.array([[ 9., 1., 1., 0., 0., 0.],
[ 1., 9., 1., 0., 0., 0.],
[ 1., 1., 9., 0., 0., 0.],
[ 0., 0., 0., 4., 0., 0.],
[ 0., 0., 0., 0., 4., 0.],
[ 0., 0., 0., 0., 0., 4.]])
_ds = mc.stiffness_from_lame(3, lam, mu)
assert_(_ds.shape == (3, 6, 6))
_ok = True
for _d in _ds:
__ok = nm.allclose(_d, d, rtol=0.0, atol=1e-14)
_ok = _ok and __ok
self.report('stiffness_from_lame():', _ok)
ok = ok and _ok
d = 4.0 / 3.0 * nm.array([[ 4., -2., -2., 0., 0., 0.],
[-2., 4., -2., 0., 0., 0.],
[-2., -2., 4., 0., 0., 0.],
[ 0., 0., 0., 3., 0., 0.],
[ 0., 0., 0., 0., 3., 0.],
[ 0., 0., 0., 0., 0., 3.]])
_ds = | mc.stiffness_from_lame_mixed(3, lam, mu) | sfepy.mechanics.matcoefs.stiffness_from_lame_mixed |
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_elastic_constants(self):
import numpy as nm
from sfepy.mechanics.matcoefs import ElasticConstants
ok = True
names = ['bulk', 'lam', 'mu', 'young', 'poisson', 'p_wave']
ec = ElasticConstants(lam=1.0, mu=1.5)
vals = ec.get(names)
self.report('using values:', vals)
for i1 in range(len(names)):
for i2 in range(i1+1, len(names)):
kwargs = {names[i1] : vals[i1], names[i2] : vals[i2]}
try:
ec.init(**kwargs)
except:
_ok = False
else:
_ok = True
ec_vals = ec.get(names)
_ok = _ok and nm.allclose(ec_vals, vals)
self.report(names[i1], names[i2], '->', _ok)
if not _ok:
self.report('correct:', vals)
self.report(' got:', ec_vals)
ok = ok and _ok
return ok
def test_conversion_functions(self):
import numpy as nm
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 1.5
ec = mc.ElasticConstants(lam=lam, mu=mu)
young, poisson, bulk = ec.get(['young', 'poisson', 'bulk'])
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
young = nm.array([young] * 3)
poisson = nm.array([poisson] * 3)
_lam, _mu = mc.lame_from_youngpoisson(young, poisson)
_ok = (nm.allclose(lam, _lam, rtol=0.0, atol=1e-14) and
nm.allclose(mu, _mu, rtol=0.0, atol=1e-14))
self.report('lame_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', lam, mu)
self.report(' got:', _lam, _mu)
ok = ok and _ok
_bulk = mc.bulk_from_youngpoisson(young, poisson)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
_bulk = mc.bulk_from_lame(lam, mu)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_lame():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
return ok
def test_stiffness_tensors(self):
import numpy as nm
from sfepy.base.base import assert_
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 4.0
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
d = nm.array([[ 9., 1., 1., 0., 0., 0.],
[ 1., 9., 1., 0., 0., 0.],
[ 1., 1., 9., 0., 0., 0.],
[ 0., 0., 0., 4., 0., 0.],
[ 0., 0., 0., 0., 4., 0.],
[ 0., 0., 0., 0., 0., 4.]])
_ds = mc.stiffness_from_lame(3, lam, mu)
assert_(_ds.shape == (3, 6, 6))
_ok = True
for _d in _ds:
__ok = nm.allclose(_d, d, rtol=0.0, atol=1e-14)
_ok = _ok and __ok
self.report('stiffness_from_lame():', _ok)
ok = ok and _ok
d = 4.0 / 3.0 * nm.array([[ 4., -2., -2., 0., 0., 0.],
[-2., 4., -2., 0., 0., 0.],
[-2., -2., 4., 0., 0., 0.],
[ 0., 0., 0., 3., 0., 0.],
[ 0., 0., 0., 0., 3., 0.],
[ 0., 0., 0., 0., 0., 3.]])
_ds = mc.stiffness_from_lame_mixed(3, lam, mu)
| assert_(_ds.shape == (3, 6, 6)) | sfepy.base.base.assert_ |
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_elastic_constants(self):
import numpy as nm
from sfepy.mechanics.matcoefs import ElasticConstants
ok = True
names = ['bulk', 'lam', 'mu', 'young', 'poisson', 'p_wave']
ec = ElasticConstants(lam=1.0, mu=1.5)
vals = ec.get(names)
self.report('using values:', vals)
for i1 in range(len(names)):
for i2 in range(i1+1, len(names)):
kwargs = {names[i1] : vals[i1], names[i2] : vals[i2]}
try:
ec.init(**kwargs)
except:
_ok = False
else:
_ok = True
ec_vals = ec.get(names)
_ok = _ok and nm.allclose(ec_vals, vals)
self.report(names[i1], names[i2], '->', _ok)
if not _ok:
self.report('correct:', vals)
self.report(' got:', ec_vals)
ok = ok and _ok
return ok
def test_conversion_functions(self):
import numpy as nm
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 1.5
ec = mc.ElasticConstants(lam=lam, mu=mu)
young, poisson, bulk = ec.get(['young', 'poisson', 'bulk'])
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
young = nm.array([young] * 3)
poisson = nm.array([poisson] * 3)
_lam, _mu = mc.lame_from_youngpoisson(young, poisson)
_ok = (nm.allclose(lam, _lam, rtol=0.0, atol=1e-14) and
nm.allclose(mu, _mu, rtol=0.0, atol=1e-14))
self.report('lame_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', lam, mu)
self.report(' got:', _lam, _mu)
ok = ok and _ok
_bulk = mc.bulk_from_youngpoisson(young, poisson)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
_bulk = mc.bulk_from_lame(lam, mu)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_lame():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
return ok
def test_stiffness_tensors(self):
import numpy as nm
from sfepy.base.base import assert_
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 4.0
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
d = nm.array([[ 9., 1., 1., 0., 0., 0.],
[ 1., 9., 1., 0., 0., 0.],
[ 1., 1., 9., 0., 0., 0.],
[ 0., 0., 0., 4., 0., 0.],
[ 0., 0., 0., 0., 4., 0.],
[ 0., 0., 0., 0., 0., 4.]])
_ds = mc.stiffness_from_lame(3, lam, mu)
assert_(_ds.shape == (3, 6, 6))
_ok = True
for _d in _ds:
__ok = nm.allclose(_d, d, rtol=0.0, atol=1e-14)
_ok = _ok and __ok
self.report('stiffness_from_lame():', _ok)
ok = ok and _ok
d = 4.0 / 3.0 * nm.array([[ 4., -2., -2., 0., 0., 0.],
[-2., 4., -2., 0., 0., 0.],
[-2., -2., 4., 0., 0., 0.],
[ 0., 0., 0., 3., 0., 0.],
[ 0., 0., 0., 0., 3., 0.],
[ 0., 0., 0., 0., 0., 3.]])
_ds = mc.stiffness_from_lame_mixed(3, lam, mu)
assert_(_ds.shape == (3, 6, 6))
_ok = True
for _d in _ds:
__ok = nm.allclose(_d, d, rtol=0.0, atol=1e-14)
_ok = _ok and __ok
self.report('stiffness_from_lame_mixed():', _ok)
ok = ok and _ok
blam = - mu * 2.0 / 3.0
_ds = | mc.stiffness_from_lame(3, blam, mu) | sfepy.mechanics.matcoefs.stiffness_from_lame |
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_elastic_constants(self):
import numpy as nm
from sfepy.mechanics.matcoefs import ElasticConstants
ok = True
names = ['bulk', 'lam', 'mu', 'young', 'poisson', 'p_wave']
ec = ElasticConstants(lam=1.0, mu=1.5)
vals = ec.get(names)
self.report('using values:', vals)
for i1 in range(len(names)):
for i2 in range(i1+1, len(names)):
kwargs = {names[i1] : vals[i1], names[i2] : vals[i2]}
try:
ec.init(**kwargs)
except:
_ok = False
else:
_ok = True
ec_vals = ec.get(names)
_ok = _ok and nm.allclose(ec_vals, vals)
self.report(names[i1], names[i2], '->', _ok)
if not _ok:
self.report('correct:', vals)
self.report(' got:', ec_vals)
ok = ok and _ok
return ok
def test_conversion_functions(self):
import numpy as nm
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 1.5
ec = mc.ElasticConstants(lam=lam, mu=mu)
young, poisson, bulk = ec.get(['young', 'poisson', 'bulk'])
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
young = nm.array([young] * 3)
poisson = nm.array([poisson] * 3)
_lam, _mu = mc.lame_from_youngpoisson(young, poisson)
_ok = (nm.allclose(lam, _lam, rtol=0.0, atol=1e-14) and
nm.allclose(mu, _mu, rtol=0.0, atol=1e-14))
self.report('lame_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', lam, mu)
self.report(' got:', _lam, _mu)
ok = ok and _ok
_bulk = mc.bulk_from_youngpoisson(young, poisson)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_youngpoisson():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
_bulk = mc.bulk_from_lame(lam, mu)
_ok = nm.allclose(bulk, _bulk, rtol=0.0, atol=1e-14)
self.report('bulk_from_lame():', _ok)
if not _ok:
self.report('correct:', bulk)
self.report(' got:', _bulk)
ok = ok and _ok
return ok
def test_stiffness_tensors(self):
import numpy as nm
from sfepy.base.base import assert_
import sfepy.mechanics.matcoefs as mc
ok = True
lam = 1.0
mu = 4.0
lam = nm.array([lam] * 3)
mu = nm.array([mu] * 3)
d = nm.array([[ 9., 1., 1., 0., 0., 0.],
[ 1., 9., 1., 0., 0., 0.],
[ 1., 1., 9., 0., 0., 0.],
[ 0., 0., 0., 4., 0., 0.],
[ 0., 0., 0., 0., 4., 0.],
[ 0., 0., 0., 0., 0., 4.]])
_ds = mc.stiffness_from_lame(3, lam, mu)
assert_(_ds.shape == (3, 6, 6))
_ok = True
for _d in _ds:
__ok = nm.allclose(_d, d, rtol=0.0, atol=1e-14)
_ok = _ok and __ok
self.report('stiffness_from_lame():', _ok)
ok = ok and _ok
d = 4.0 / 3.0 * nm.array([[ 4., -2., -2., 0., 0., 0.],
[-2., 4., -2., 0., 0., 0.],
[-2., -2., 4., 0., 0., 0.],
[ 0., 0., 0., 3., 0., 0.],
[ 0., 0., 0., 0., 3., 0.],
[ 0., 0., 0., 0., 0., 3.]])
_ds = mc.stiffness_from_lame_mixed(3, lam, mu)
assert_(_ds.shape == (3, 6, 6))
_ok = True
for _d in _ds:
__ok = nm.allclose(_d, d, rtol=0.0, atol=1e-14)
_ok = _ok and __ok
self.report('stiffness_from_lame_mixed():', _ok)
ok = ok and _ok
blam = - mu * 2.0 / 3.0
_ds = mc.stiffness_from_lame(3, blam, mu)
| assert_(_ds.shape == (3, 6, 6)) | sfepy.base.base.assert_ |
import numpy as nm
from sfepy.base.base import Struct, assert_
from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping
from poly_spaces import PolySpace
from fe_surface import FESurface
def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False,
clear_all=True):
if actual:
domain.mesh.coors_act = coors.copy()
else:
domain.mesh.coors = coors.copy()
if update_fields:
for field in fields.itervalues():
field.setup_coors(coors)
field.clear_mappings(clear_all=clear_all)
def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space,
econn, ig, only_extra=True):
"""
Compute coordinates of nodes corresponding to `poly_space`, given
mesh coordinates and `geom_poly_space`.
"""
if only_extra:
iex = (poly_space.nts[:,0] > 0).nonzero()[0]
if iex.shape[0] == 0: return
qp_coors = poly_space.node_coors[iex, :]
econn = econn[:, iex].copy()
else:
qp_coors = poly_space.node_coors
##
# Evaluate geometry interpolation base functions in (extra) nodes.
bf = geom_poly_space.eval_base(qp_coors)
bf = bf[:,0,:].copy()
##
# Evaluate extra coordinates with 'bf'.
group = region.domain.groups[ig]
cells = region.get_cells(ig)
ecoors = nm.dot(bf, mesh_coors[group.conn[cells]])
coors[econn] = nm.swapaxes(ecoors, 0, 1)
##
# 04.08.2005, c
def _interp_to_faces( vertex_vals, bfs, faces ):
dim = vertex_vals.shape[1]
n_face = faces.shape[0]
n_qp = bfs.shape[0]
faces_vals = nm.zeros( (n_face, n_qp, dim), nm.float64 )
for ii, face in enumerate( faces ):
vals = vertex_vals[face,:dim]
faces_vals[ii,:,:] = nm.dot( bfs[:,0,:], vals )
return( faces_vals )
class Interpolant( Struct ):
"""A simple wrapper around PolySpace."""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
self.name = name
self.gel = gel
self.poly_spaces = poly_spaces = {}
poly_spaces['v'] = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=force_bubble)
gel = gel.surface_facet
if gel is not None:
ps = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=False)
skey = 's%d' % ps.n_nod
poly_spaces[skey] = ps
def describe_nodes( self ):
ps = self.poly_spaces['v']
node_desc = ps.describe_nodes()
return node_desc
##
# 16.11.2007, c
def get_n_nodes( self ):
nn = {}
for key, ps in self.poly_spaces.iteritems():
nn[key] = ps.nodes.shape[0]
return nn
def get_geom_poly_space(self, key):
if key == 'v':
ps = self.gel.interp.poly_spaces['v']
elif key[0] == 's':
n_v = self.gel.surface_facet.n_vertex
ps = self.gel.interp.poly_spaces['s%d' % n_v]
else:
raise ValueError('bad polynomial space key! (%s)' % key)
return ps
class SurfaceInterpolant(Interpolant):
"""
Like Interpolant, but for use with SurfaceField and
SurfaceApproximation.
"""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
Interpolant.__init__(self, name, gel, space=space, base=base,
approx_order=approx_order,
force_bubble=force_bubble)
# Make alias 'v' <-> 's#'.
ps = self.poly_spaces['v']
self.poly_spaces['s%d' % ps.n_nod] = ps
def get_geom_poly_space(self, key):
| assert_(key[0] == 's') | sfepy.base.base.assert_ |
import numpy as nm
from sfepy.base.base import Struct, assert_
from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping
from poly_spaces import PolySpace
from fe_surface import FESurface
def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False,
clear_all=True):
if actual:
domain.mesh.coors_act = coors.copy()
else:
domain.mesh.coors = coors.copy()
if update_fields:
for field in fields.itervalues():
field.setup_coors(coors)
field.clear_mappings(clear_all=clear_all)
def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space,
econn, ig, only_extra=True):
"""
Compute coordinates of nodes corresponding to `poly_space`, given
mesh coordinates and `geom_poly_space`.
"""
if only_extra:
iex = (poly_space.nts[:,0] > 0).nonzero()[0]
if iex.shape[0] == 0: return
qp_coors = poly_space.node_coors[iex, :]
econn = econn[:, iex].copy()
else:
qp_coors = poly_space.node_coors
##
# Evaluate geometry interpolation base functions in (extra) nodes.
bf = geom_poly_space.eval_base(qp_coors)
bf = bf[:,0,:].copy()
##
# Evaluate extra coordinates with 'bf'.
group = region.domain.groups[ig]
cells = region.get_cells(ig)
ecoors = nm.dot(bf, mesh_coors[group.conn[cells]])
coors[econn] = nm.swapaxes(ecoors, 0, 1)
##
# 04.08.2005, c
def _interp_to_faces( vertex_vals, bfs, faces ):
dim = vertex_vals.shape[1]
n_face = faces.shape[0]
n_qp = bfs.shape[0]
faces_vals = nm.zeros( (n_face, n_qp, dim), nm.float64 )
for ii, face in enumerate( faces ):
vals = vertex_vals[face,:dim]
faces_vals[ii,:,:] = nm.dot( bfs[:,0,:], vals )
return( faces_vals )
class Interpolant( Struct ):
"""A simple wrapper around PolySpace."""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
self.name = name
self.gel = gel
self.poly_spaces = poly_spaces = {}
poly_spaces['v'] = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=force_bubble)
gel = gel.surface_facet
if gel is not None:
ps = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=False)
skey = 's%d' % ps.n_nod
poly_spaces[skey] = ps
def describe_nodes( self ):
ps = self.poly_spaces['v']
node_desc = ps.describe_nodes()
return node_desc
##
# 16.11.2007, c
def get_n_nodes( self ):
nn = {}
for key, ps in self.poly_spaces.iteritems():
nn[key] = ps.nodes.shape[0]
return nn
def get_geom_poly_space(self, key):
if key == 'v':
ps = self.gel.interp.poly_spaces['v']
elif key[0] == 's':
n_v = self.gel.surface_facet.n_vertex
ps = self.gel.interp.poly_spaces['s%d' % n_v]
else:
raise ValueError('bad polynomial space key! (%s)' % key)
return ps
class SurfaceInterpolant(Interpolant):
"""
Like Interpolant, but for use with SurfaceField and
SurfaceApproximation.
"""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
Interpolant.__init__(self, name, gel, space=space, base=base,
approx_order=approx_order,
force_bubble=force_bubble)
# Make alias 'v' <-> 's#'.
ps = self.poly_spaces['v']
self.poly_spaces['s%d' % ps.n_nod] = ps
def get_geom_poly_space(self, key):
assert_(key[0] == 's')
ps = self.gel.interp.poly_spaces['v']
return ps
##
# 18.07.2006, c
class Approximation( Struct ):
##
# 18.07.2006, c
# 10.10.2006
# 11.07.2007
# 17.07.2007
def __init__(self, name, interp, region, ig, is_surface=False):
"""interp, region are borrowed."""
self.name = name
self.interp = interp
self.region = region
self.ig = ig
self.is_surface = is_surface
self.surface_data = {}
self.edge_data = {}
self.point_data = {}
self.n_ep = self.interp.get_n_nodes()
self.ori = None
self.clear_qp_base()
def eval_extra_coor(self, coors, mesh_coors):
"""
Compute coordinates of extra nodes.
"""
gps = self.interp.gel.interp.poly_spaces['v']
ps = self.interp.poly_spaces['v']
eval_nodal_coors(coors, mesh_coors, self.region, ps, gps, self.econn, self.ig)
##
# c: 05.09.2006, r: 09.05.2008
def setup_surface_data( self, region ):
"""nodes[leconn] == econn"""
"""nodes are sorted by node number -> same order as region.vertices"""
sd = FESurface('surface_data_%s' % region.name, region,
self.efaces, self.econn, self.ig)
self.surface_data[region.name] = sd
return sd
##
# 11.07.2007, c
def setup_point_data( self, field, region ):
conn = field.get_dofs_in_region(region, merge=True, igs=region.igs)
## conn = [nods]\
## + [nm.empty( (0,), dtype = nm.int32 )]\
## * (len( region.igs ) - 1)
conn.shape += (1,)
self.point_data[region.name] = conn
def get_connectivity(self, region, integration, is_trace=False):
"""
Return the DOF connectivity for the given geometry type.
Parameters
----------
region : Region instance
The region, used to index surface and volume connectivities.
integration : one of ('volume', 'plate', 'surface', 'surface_extra')
The term integration type.
"""
if integration == 'surface':
sd = self.surface_data[region.name]
conn = sd.get_connectivity(self.is_surface, is_trace=is_trace)
elif integration in ('volume', 'plate', 'surface_extra'):
if region.name == self.region.name:
conn = self.econn
else:
aux = integration in ('volume', 'plate')
cells = region.get_cells(self.ig, true_cells_only=aux)
conn = nm.take(self.econn, cells.astype(nm.int32), axis=0)
else:
raise ValueError('unsupported term integration! (%s)' % integration)
return conn
def get_poly_space(self, key, from_geometry=False):
"""
Get the polynomial space.
Parameters
----------
key : 'v' or 's?'
The key denoting volume or surface.
from_geometry : bool
If True, return the polynomial space for affine geometrical
interpolation.
Returns
-------
ps : PolySpace instance
The polynomial space.
"""
if from_geometry:
ps = self.interp.get_geom_poly_space(key)
else:
ps = self.interp.poly_spaces[key]
return ps
def clear_qp_base(self):
"""
Remove cached quadrature points and base functions.
"""
self.qp_coors = {}
self.bf = {}
def get_qp(self, key, integral):
"""
Get quadrature points and weights corresponding to the given key
and integral. The key is 'v' or 's#', where # is the number of
face vertices.
"""
qpkey = (integral.name, key)
if not self.qp_coors.has_key(qpkey):
interp = self.interp
if (key[0] == 's'):
dim = interp.gel.dim - 1
n_fp = interp.gel.surface_facet.n_vertex
geometry = '%d_%d' % (dim, n_fp)
else:
geometry = interp.gel.name
vals, weights = integral.get_qp(geometry)
self.qp_coors[qpkey] = Struct(vals=vals, weights=weights)
return self.qp_coors[qpkey]
def get_base(self, key, derivative, integral, iels=None,
from_geometry=False, base_only=True):
qp = self.get_qp(key, integral)
ps = self.get_poly_space(key, from_geometry=from_geometry)
_key = key if not from_geometry else 'g' + key
bf_key = (integral.name, _key, derivative)
if not self.bf.has_key(bf_key):
if (iels is not None) and (self.ori is not None):
ori = self.ori[iels]
else:
ori = self.ori
self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori)
if base_only:
return self.bf[bf_key]
else:
return self.bf[bf_key], qp.weights
def describe_geometry(self, field, gtype, region, integral,
return_mapping=False):
"""
Compute jacobians, element volumes and base function derivatives
for Volume-type geometries (volume mappings), and jacobians,
normals and base function derivatives for Surface-type
geometries (surface mappings).
Notes
-----
- volume mappings can be defined on a part of an element group,
although the field has to be defined always on the whole group.
- surface mappings are defined on the surface region
- surface mappings require field order to be > 0
"""
domain = field.domain
group = domain.groups[self.ig]
coors = domain.get_mesh_coors(actual=True)
if gtype == 'volume':
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
geo_ps = self.interp.get_geom_poly_space('v')
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, iels.astype(nm.int32), axis=0)
mapping = VolumeMapping(coors, conn, poly_space=geo_ps)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori)
out = vg
elif gtype == 'plate':
import sfepy.mechanics.membranes as mm
from sfepy.linalg import dot_sequences
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, nm.int32(iels), axis=0)
ccoors = coors[conn]
# Coordinate transformation matrix (transposed!).
mtx_t = mm.create_transformation_matrix(ccoors)
# Transform coordinates to the local coordinate system.
coors_loc = dot_sequences((ccoors - ccoors[:, 0:1, :]), mtx_t)
# Mapping from transformed elements to reference elements.
mapping = mm.create_mapping(coors_loc, field.gel, 1)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori)
vg.mtx_t = mtx_t
out = vg
elif (gtype == 'surface') or (gtype == 'surface_extra'):
assert_(field.approx_order > 0)
if self.ori is not None:
msg = 'surface integrals do not work yet with the' \
' hierarchical basis!'
raise ValueError(msg)
sd = domain.surface_groups[self.ig][region.name]
esd = self.surface_data[region.name]
qp = self.get_qp(sd.face_type, integral)
geo_ps = self.interp.get_geom_poly_space(sd.face_type)
ps = self.interp.poly_spaces[esd.face_type]
bf = self.get_base(esd.face_type, 0, integral)
conn = sd.get_connectivity()
mapping = SurfaceMapping(coors, conn, poly_space=geo_ps)
sg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
mode=gtype)
if gtype == 'surface_extra':
sg.alloc_extra_data(self.n_ep['v'])
self.create_bqp(region.name, integral)
qp = self.qp_coors[(integral.name, esd.bkey)]
v_geo_ps = self.interp.get_geom_poly_space('v')
bf_bg = v_geo_ps.eval_base(qp.vals, diff=True)
ebf_bg = self.get_base(esd.bkey, 1, integral)
sg.evaluate_bfbgm(bf_bg, ebf_bg, coors, sd.fis, group.conn)
out = sg
elif gtype == 'point':
out = mapping = None
else:
raise ValueError('unknown geometry type: %s' % gtype)
if out is not None:
# Store the integral used.
out.integral = integral
out.qp = qp
out.ps = ps
# Update base.
out.bf[:] = bf
if return_mapping:
out = (out, mapping)
return out
def _create_bqp(self, skey, bf_s, weights, integral_name):
interp = self.interp
gel = interp.gel
bkey = 'b%s' % skey[1:]
bqpkey = (integral_name, bkey)
coors, faces = gel.coors, gel.get_surface_entities()
vals = _interp_to_faces(coors, bf_s, faces)
self.qp_coors[bqpkey] = Struct(name = 'BQP_%s' % bkey,
vals = vals, weights = weights)
interp.poly_spaces[bkey] = interp.poly_spaces['v']
return bkey
def create_bqp(self, region_name, integral):
sd = self.surface_data[region_name]
bqpkey = (integral.name, sd.bkey)
if not bqpkey in self.qp_coors:
bf_s = self.get_base(sd.face_type, 0, integral,
from_geometry=True)
qp = self.get_qp(sd.face_type, integral)
bkey = self._create_bqp(sd.face_type, bf_s, qp.weights,
integral.name)
assert_(bkey == sd.bkey)
class DiscontinuousApproximation(Approximation):
def eval_extra_coor(self, coors, mesh_coors):
"""
Compute coordinates of extra nodes. For discontinuous
approximations, all nodes are treated as extra.
"""
gps = self.interp.gel.interp.poly_spaces['v']
ps = self.interp.poly_spaces['v']
eval_nodal_coors(coors, mesh_coors, self.region, ps, gps,
self.econn, self.ig, only_extra=False)
class SurfaceApproximation(Approximation):
def __init__(self, name, interp, region, ig):
Approximation.__init__(self, name, interp, region, ig, is_surface=True)
def get_qp(self, key, integral):
"""
Get quadrature points and weights corresponding to the given key
and integral. The key is 's#', where # is the number of
face vertices.
"""
| assert_(key[0] == 's') | sfepy.base.base.assert_ |
import numpy as nm
from sfepy.base.base import Struct, assert_
from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping
from poly_spaces import PolySpace
from fe_surface import FESurface
def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False,
clear_all=True):
if actual:
domain.mesh.coors_act = coors.copy()
else:
domain.mesh.coors = coors.copy()
if update_fields:
for field in fields.itervalues():
field.setup_coors(coors)
field.clear_mappings(clear_all=clear_all)
def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space,
econn, ig, only_extra=True):
"""
Compute coordinates of nodes corresponding to `poly_space`, given
mesh coordinates and `geom_poly_space`.
"""
if only_extra:
iex = (poly_space.nts[:,0] > 0).nonzero()[0]
if iex.shape[0] == 0: return
qp_coors = poly_space.node_coors[iex, :]
econn = econn[:, iex].copy()
else:
qp_coors = poly_space.node_coors
##
# Evaluate geometry interpolation base functions in (extra) nodes.
bf = geom_poly_space.eval_base(qp_coors)
bf = bf[:,0,:].copy()
##
# Evaluate extra coordinates with 'bf'.
group = region.domain.groups[ig]
cells = region.get_cells(ig)
ecoors = nm.dot(bf, mesh_coors[group.conn[cells]])
coors[econn] = nm.swapaxes(ecoors, 0, 1)
##
# 04.08.2005, c
def _interp_to_faces( vertex_vals, bfs, faces ):
dim = vertex_vals.shape[1]
n_face = faces.shape[0]
n_qp = bfs.shape[0]
faces_vals = nm.zeros( (n_face, n_qp, dim), nm.float64 )
for ii, face in enumerate( faces ):
vals = vertex_vals[face,:dim]
faces_vals[ii,:,:] = nm.dot( bfs[:,0,:], vals )
return( faces_vals )
class Interpolant( Struct ):
"""A simple wrapper around PolySpace."""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
self.name = name
self.gel = gel
self.poly_spaces = poly_spaces = {}
poly_spaces['v'] = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=force_bubble)
gel = gel.surface_facet
if gel is not None:
ps = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=False)
skey = 's%d' % ps.n_nod
poly_spaces[skey] = ps
def describe_nodes( self ):
ps = self.poly_spaces['v']
node_desc = ps.describe_nodes()
return node_desc
##
# 16.11.2007, c
def get_n_nodes( self ):
nn = {}
for key, ps in self.poly_spaces.iteritems():
nn[key] = ps.nodes.shape[0]
return nn
def get_geom_poly_space(self, key):
if key == 'v':
ps = self.gel.interp.poly_spaces['v']
elif key[0] == 's':
n_v = self.gel.surface_facet.n_vertex
ps = self.gel.interp.poly_spaces['s%d' % n_v]
else:
raise ValueError('bad polynomial space key! (%s)' % key)
return ps
class SurfaceInterpolant(Interpolant):
"""
Like Interpolant, but for use with SurfaceField and
SurfaceApproximation.
"""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
Interpolant.__init__(self, name, gel, space=space, base=base,
approx_order=approx_order,
force_bubble=force_bubble)
# Make alias 'v' <-> 's#'.
ps = self.poly_spaces['v']
self.poly_spaces['s%d' % ps.n_nod] = ps
def get_geom_poly_space(self, key):
assert_(key[0] == 's')
ps = self.gel.interp.poly_spaces['v']
return ps
##
# 18.07.2006, c
class Approximation( Struct ):
##
# 18.07.2006, c
# 10.10.2006
# 11.07.2007
# 17.07.2007
def __init__(self, name, interp, region, ig, is_surface=False):
"""interp, region are borrowed."""
self.name = name
self.interp = interp
self.region = region
self.ig = ig
self.is_surface = is_surface
self.surface_data = {}
self.edge_data = {}
self.point_data = {}
self.n_ep = self.interp.get_n_nodes()
self.ori = None
self.clear_qp_base()
def eval_extra_coor(self, coors, mesh_coors):
"""
Compute coordinates of extra nodes.
"""
gps = self.interp.gel.interp.poly_spaces['v']
ps = self.interp.poly_spaces['v']
eval_nodal_coors(coors, mesh_coors, self.region, ps, gps, self.econn, self.ig)
##
# c: 05.09.2006, r: 09.05.2008
def setup_surface_data( self, region ):
"""nodes[leconn] == econn"""
"""nodes are sorted by node number -> same order as region.vertices"""
sd = FESurface('surface_data_%s' % region.name, region,
self.efaces, self.econn, self.ig)
self.surface_data[region.name] = sd
return sd
##
# 11.07.2007, c
def setup_point_data( self, field, region ):
conn = field.get_dofs_in_region(region, merge=True, igs=region.igs)
## conn = [nods]\
## + [nm.empty( (0,), dtype = nm.int32 )]\
## * (len( region.igs ) - 1)
conn.shape += (1,)
self.point_data[region.name] = conn
def get_connectivity(self, region, integration, is_trace=False):
"""
Return the DOF connectivity for the given geometry type.
Parameters
----------
region : Region instance
The region, used to index surface and volume connectivities.
integration : one of ('volume', 'plate', 'surface', 'surface_extra')
The term integration type.
"""
if integration == 'surface':
sd = self.surface_data[region.name]
conn = sd.get_connectivity(self.is_surface, is_trace=is_trace)
elif integration in ('volume', 'plate', 'surface_extra'):
if region.name == self.region.name:
conn = self.econn
else:
aux = integration in ('volume', 'plate')
cells = region.get_cells(self.ig, true_cells_only=aux)
conn = nm.take(self.econn, cells.astype(nm.int32), axis=0)
else:
raise ValueError('unsupported term integration! (%s)' % integration)
return conn
def get_poly_space(self, key, from_geometry=False):
"""
Get the polynomial space.
Parameters
----------
key : 'v' or 's?'
The key denoting volume or surface.
from_geometry : bool
If True, return the polynomial space for affine geometrical
interpolation.
Returns
-------
ps : PolySpace instance
The polynomial space.
"""
if from_geometry:
ps = self.interp.get_geom_poly_space(key)
else:
ps = self.interp.poly_spaces[key]
return ps
def clear_qp_base(self):
"""
Remove cached quadrature points and base functions.
"""
self.qp_coors = {}
self.bf = {}
def get_qp(self, key, integral):
"""
Get quadrature points and weights corresponding to the given key
and integral. The key is 'v' or 's#', where # is the number of
face vertices.
"""
qpkey = (integral.name, key)
if not self.qp_coors.has_key(qpkey):
interp = self.interp
if (key[0] == 's'):
dim = interp.gel.dim - 1
n_fp = interp.gel.surface_facet.n_vertex
geometry = '%d_%d' % (dim, n_fp)
else:
geometry = interp.gel.name
vals, weights = integral.get_qp(geometry)
self.qp_coors[qpkey] = | Struct(vals=vals, weights=weights) | sfepy.base.base.Struct |
import numpy as nm
from sfepy.base.base import Struct, assert_
from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping
from poly_spaces import PolySpace
from fe_surface import FESurface
def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False,
clear_all=True):
if actual:
domain.mesh.coors_act = coors.copy()
else:
domain.mesh.coors = coors.copy()
if update_fields:
for field in fields.itervalues():
field.setup_coors(coors)
field.clear_mappings(clear_all=clear_all)
def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space,
econn, ig, only_extra=True):
"""
Compute coordinates of nodes corresponding to `poly_space`, given
mesh coordinates and `geom_poly_space`.
"""
if only_extra:
iex = (poly_space.nts[:,0] > 0).nonzero()[0]
if iex.shape[0] == 0: return
qp_coors = poly_space.node_coors[iex, :]
econn = econn[:, iex].copy()
else:
qp_coors = poly_space.node_coors
##
# Evaluate geometry interpolation base functions in (extra) nodes.
bf = geom_poly_space.eval_base(qp_coors)
bf = bf[:,0,:].copy()
##
# Evaluate extra coordinates with 'bf'.
group = region.domain.groups[ig]
cells = region.get_cells(ig)
ecoors = nm.dot(bf, mesh_coors[group.conn[cells]])
coors[econn] = nm.swapaxes(ecoors, 0, 1)
##
# 04.08.2005, c
def _interp_to_faces( vertex_vals, bfs, faces ):
dim = vertex_vals.shape[1]
n_face = faces.shape[0]
n_qp = bfs.shape[0]
faces_vals = nm.zeros( (n_face, n_qp, dim), nm.float64 )
for ii, face in enumerate( faces ):
vals = vertex_vals[face,:dim]
faces_vals[ii,:,:] = nm.dot( bfs[:,0,:], vals )
return( faces_vals )
class Interpolant( Struct ):
"""A simple wrapper around PolySpace."""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
self.name = name
self.gel = gel
self.poly_spaces = poly_spaces = {}
poly_spaces['v'] = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=force_bubble)
gel = gel.surface_facet
if gel is not None:
ps = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=False)
skey = 's%d' % ps.n_nod
poly_spaces[skey] = ps
def describe_nodes( self ):
ps = self.poly_spaces['v']
node_desc = ps.describe_nodes()
return node_desc
##
# 16.11.2007, c
def get_n_nodes( self ):
nn = {}
for key, ps in self.poly_spaces.iteritems():
nn[key] = ps.nodes.shape[0]
return nn
def get_geom_poly_space(self, key):
if key == 'v':
ps = self.gel.interp.poly_spaces['v']
elif key[0] == 's':
n_v = self.gel.surface_facet.n_vertex
ps = self.gel.interp.poly_spaces['s%d' % n_v]
else:
raise ValueError('bad polynomial space key! (%s)' % key)
return ps
class SurfaceInterpolant(Interpolant):
"""
Like Interpolant, but for use with SurfaceField and
SurfaceApproximation.
"""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
Interpolant.__init__(self, name, gel, space=space, base=base,
approx_order=approx_order,
force_bubble=force_bubble)
# Make alias 'v' <-> 's#'.
ps = self.poly_spaces['v']
self.poly_spaces['s%d' % ps.n_nod] = ps
def get_geom_poly_space(self, key):
assert_(key[0] == 's')
ps = self.gel.interp.poly_spaces['v']
return ps
##
# 18.07.2006, c
class Approximation( Struct ):
##
# 18.07.2006, c
# 10.10.2006
# 11.07.2007
# 17.07.2007
def __init__(self, name, interp, region, ig, is_surface=False):
"""interp, region are borrowed."""
self.name = name
self.interp = interp
self.region = region
self.ig = ig
self.is_surface = is_surface
self.surface_data = {}
self.edge_data = {}
self.point_data = {}
self.n_ep = self.interp.get_n_nodes()
self.ori = None
self.clear_qp_base()
def eval_extra_coor(self, coors, mesh_coors):
"""
Compute coordinates of extra nodes.
"""
gps = self.interp.gel.interp.poly_spaces['v']
ps = self.interp.poly_spaces['v']
eval_nodal_coors(coors, mesh_coors, self.region, ps, gps, self.econn, self.ig)
##
# c: 05.09.2006, r: 09.05.2008
def setup_surface_data( self, region ):
"""nodes[leconn] == econn"""
"""nodes are sorted by node number -> same order as region.vertices"""
sd = FESurface('surface_data_%s' % region.name, region,
self.efaces, self.econn, self.ig)
self.surface_data[region.name] = sd
return sd
##
# 11.07.2007, c
def setup_point_data( self, field, region ):
conn = field.get_dofs_in_region(region, merge=True, igs=region.igs)
## conn = [nods]\
## + [nm.empty( (0,), dtype = nm.int32 )]\
## * (len( region.igs ) - 1)
conn.shape += (1,)
self.point_data[region.name] = conn
def get_connectivity(self, region, integration, is_trace=False):
"""
Return the DOF connectivity for the given geometry type.
Parameters
----------
region : Region instance
The region, used to index surface and volume connectivities.
integration : one of ('volume', 'plate', 'surface', 'surface_extra')
The term integration type.
"""
if integration == 'surface':
sd = self.surface_data[region.name]
conn = sd.get_connectivity(self.is_surface, is_trace=is_trace)
elif integration in ('volume', 'plate', 'surface_extra'):
if region.name == self.region.name:
conn = self.econn
else:
aux = integration in ('volume', 'plate')
cells = region.get_cells(self.ig, true_cells_only=aux)
conn = nm.take(self.econn, cells.astype(nm.int32), axis=0)
else:
raise ValueError('unsupported term integration! (%s)' % integration)
return conn
def get_poly_space(self, key, from_geometry=False):
"""
Get the polynomial space.
Parameters
----------
key : 'v' or 's?'
The key denoting volume or surface.
from_geometry : bool
If True, return the polynomial space for affine geometrical
interpolation.
Returns
-------
ps : PolySpace instance
The polynomial space.
"""
if from_geometry:
ps = self.interp.get_geom_poly_space(key)
else:
ps = self.interp.poly_spaces[key]
return ps
def clear_qp_base(self):
"""
Remove cached quadrature points and base functions.
"""
self.qp_coors = {}
self.bf = {}
def get_qp(self, key, integral):
"""
Get quadrature points and weights corresponding to the given key
and integral. The key is 'v' or 's#', where # is the number of
face vertices.
"""
qpkey = (integral.name, key)
if not self.qp_coors.has_key(qpkey):
interp = self.interp
if (key[0] == 's'):
dim = interp.gel.dim - 1
n_fp = interp.gel.surface_facet.n_vertex
geometry = '%d_%d' % (dim, n_fp)
else:
geometry = interp.gel.name
vals, weights = integral.get_qp(geometry)
self.qp_coors[qpkey] = Struct(vals=vals, weights=weights)
return self.qp_coors[qpkey]
def get_base(self, key, derivative, integral, iels=None,
from_geometry=False, base_only=True):
qp = self.get_qp(key, integral)
ps = self.get_poly_space(key, from_geometry=from_geometry)
_key = key if not from_geometry else 'g' + key
bf_key = (integral.name, _key, derivative)
if not self.bf.has_key(bf_key):
if (iels is not None) and (self.ori is not None):
ori = self.ori[iels]
else:
ori = self.ori
self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori)
if base_only:
return self.bf[bf_key]
else:
return self.bf[bf_key], qp.weights
def describe_geometry(self, field, gtype, region, integral,
return_mapping=False):
"""
Compute jacobians, element volumes and base function derivatives
for Volume-type geometries (volume mappings), and jacobians,
normals and base function derivatives for Surface-type
geometries (surface mappings).
Notes
-----
- volume mappings can be defined on a part of an element group,
although the field has to be defined always on the whole group.
- surface mappings are defined on the surface region
- surface mappings require field order to be > 0
"""
domain = field.domain
group = domain.groups[self.ig]
coors = domain.get_mesh_coors(actual=True)
if gtype == 'volume':
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
geo_ps = self.interp.get_geom_poly_space('v')
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, iels.astype(nm.int32), axis=0)
mapping = | VolumeMapping(coors, conn, poly_space=geo_ps) | sfepy.discrete.fem.mappings.VolumeMapping |
import numpy as nm
from sfepy.base.base import Struct, assert_
from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping
from poly_spaces import PolySpace
from fe_surface import FESurface
def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False,
clear_all=True):
if actual:
domain.mesh.coors_act = coors.copy()
else:
domain.mesh.coors = coors.copy()
if update_fields:
for field in fields.itervalues():
field.setup_coors(coors)
field.clear_mappings(clear_all=clear_all)
def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space,
econn, ig, only_extra=True):
"""
Compute coordinates of nodes corresponding to `poly_space`, given
mesh coordinates and `geom_poly_space`.
"""
if only_extra:
iex = (poly_space.nts[:,0] > 0).nonzero()[0]
if iex.shape[0] == 0: return
qp_coors = poly_space.node_coors[iex, :]
econn = econn[:, iex].copy()
else:
qp_coors = poly_space.node_coors
##
# Evaluate geometry interpolation base functions in (extra) nodes.
bf = geom_poly_space.eval_base(qp_coors)
bf = bf[:,0,:].copy()
##
# Evaluate extra coordinates with 'bf'.
group = region.domain.groups[ig]
cells = region.get_cells(ig)
ecoors = nm.dot(bf, mesh_coors[group.conn[cells]])
coors[econn] = nm.swapaxes(ecoors, 0, 1)
##
# 04.08.2005, c
def _interp_to_faces( vertex_vals, bfs, faces ):
dim = vertex_vals.shape[1]
n_face = faces.shape[0]
n_qp = bfs.shape[0]
faces_vals = nm.zeros( (n_face, n_qp, dim), nm.float64 )
for ii, face in enumerate( faces ):
vals = vertex_vals[face,:dim]
faces_vals[ii,:,:] = nm.dot( bfs[:,0,:], vals )
return( faces_vals )
class Interpolant( Struct ):
"""A simple wrapper around PolySpace."""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
self.name = name
self.gel = gel
self.poly_spaces = poly_spaces = {}
poly_spaces['v'] = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=force_bubble)
gel = gel.surface_facet
if gel is not None:
ps = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=False)
skey = 's%d' % ps.n_nod
poly_spaces[skey] = ps
def describe_nodes( self ):
ps = self.poly_spaces['v']
node_desc = ps.describe_nodes()
return node_desc
##
# 16.11.2007, c
def get_n_nodes( self ):
nn = {}
for key, ps in self.poly_spaces.iteritems():
nn[key] = ps.nodes.shape[0]
return nn
def get_geom_poly_space(self, key):
if key == 'v':
ps = self.gel.interp.poly_spaces['v']
elif key[0] == 's':
n_v = self.gel.surface_facet.n_vertex
ps = self.gel.interp.poly_spaces['s%d' % n_v]
else:
raise ValueError('bad polynomial space key! (%s)' % key)
return ps
class SurfaceInterpolant(Interpolant):
"""
Like Interpolant, but for use with SurfaceField and
SurfaceApproximation.
"""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
Interpolant.__init__(self, name, gel, space=space, base=base,
approx_order=approx_order,
force_bubble=force_bubble)
# Make alias 'v' <-> 's#'.
ps = self.poly_spaces['v']
self.poly_spaces['s%d' % ps.n_nod] = ps
def get_geom_poly_space(self, key):
assert_(key[0] == 's')
ps = self.gel.interp.poly_spaces['v']
return ps
##
# 18.07.2006, c
class Approximation( Struct ):
##
# 18.07.2006, c
# 10.10.2006
# 11.07.2007
# 17.07.2007
def __init__(self, name, interp, region, ig, is_surface=False):
"""interp, region are borrowed."""
self.name = name
self.interp = interp
self.region = region
self.ig = ig
self.is_surface = is_surface
self.surface_data = {}
self.edge_data = {}
self.point_data = {}
self.n_ep = self.interp.get_n_nodes()
self.ori = None
self.clear_qp_base()
def eval_extra_coor(self, coors, mesh_coors):
"""
Compute coordinates of extra nodes.
"""
gps = self.interp.gel.interp.poly_spaces['v']
ps = self.interp.poly_spaces['v']
eval_nodal_coors(coors, mesh_coors, self.region, ps, gps, self.econn, self.ig)
##
# c: 05.09.2006, r: 09.05.2008
def setup_surface_data( self, region ):
"""nodes[leconn] == econn"""
"""nodes are sorted by node number -> same order as region.vertices"""
sd = FESurface('surface_data_%s' % region.name, region,
self.efaces, self.econn, self.ig)
self.surface_data[region.name] = sd
return sd
##
# 11.07.2007, c
def setup_point_data( self, field, region ):
conn = field.get_dofs_in_region(region, merge=True, igs=region.igs)
## conn = [nods]\
## + [nm.empty( (0,), dtype = nm.int32 )]\
## * (len( region.igs ) - 1)
conn.shape += (1,)
self.point_data[region.name] = conn
def get_connectivity(self, region, integration, is_trace=False):
"""
Return the DOF connectivity for the given geometry type.
Parameters
----------
region : Region instance
The region, used to index surface and volume connectivities.
integration : one of ('volume', 'plate', 'surface', 'surface_extra')
The term integration type.
"""
if integration == 'surface':
sd = self.surface_data[region.name]
conn = sd.get_connectivity(self.is_surface, is_trace=is_trace)
elif integration in ('volume', 'plate', 'surface_extra'):
if region.name == self.region.name:
conn = self.econn
else:
aux = integration in ('volume', 'plate')
cells = region.get_cells(self.ig, true_cells_only=aux)
conn = nm.take(self.econn, cells.astype(nm.int32), axis=0)
else:
raise ValueError('unsupported term integration! (%s)' % integration)
return conn
def get_poly_space(self, key, from_geometry=False):
"""
Get the polynomial space.
Parameters
----------
key : 'v' or 's?'
The key denoting volume or surface.
from_geometry : bool
If True, return the polynomial space for affine geometrical
interpolation.
Returns
-------
ps : PolySpace instance
The polynomial space.
"""
if from_geometry:
ps = self.interp.get_geom_poly_space(key)
else:
ps = self.interp.poly_spaces[key]
return ps
def clear_qp_base(self):
"""
Remove cached quadrature points and base functions.
"""
self.qp_coors = {}
self.bf = {}
def get_qp(self, key, integral):
"""
Get quadrature points and weights corresponding to the given key
and integral. The key is 'v' or 's#', where # is the number of
face vertices.
"""
qpkey = (integral.name, key)
if not self.qp_coors.has_key(qpkey):
interp = self.interp
if (key[0] == 's'):
dim = interp.gel.dim - 1
n_fp = interp.gel.surface_facet.n_vertex
geometry = '%d_%d' % (dim, n_fp)
else:
geometry = interp.gel.name
vals, weights = integral.get_qp(geometry)
self.qp_coors[qpkey] = Struct(vals=vals, weights=weights)
return self.qp_coors[qpkey]
def get_base(self, key, derivative, integral, iels=None,
from_geometry=False, base_only=True):
qp = self.get_qp(key, integral)
ps = self.get_poly_space(key, from_geometry=from_geometry)
_key = key if not from_geometry else 'g' + key
bf_key = (integral.name, _key, derivative)
if not self.bf.has_key(bf_key):
if (iels is not None) and (self.ori is not None):
ori = self.ori[iels]
else:
ori = self.ori
self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori)
if base_only:
return self.bf[bf_key]
else:
return self.bf[bf_key], qp.weights
def describe_geometry(self, field, gtype, region, integral,
return_mapping=False):
"""
Compute jacobians, element volumes and base function derivatives
for Volume-type geometries (volume mappings), and jacobians,
normals and base function derivatives for Surface-type
geometries (surface mappings).
Notes
-----
- volume mappings can be defined on a part of an element group,
although the field has to be defined always on the whole group.
- surface mappings are defined on the surface region
- surface mappings require field order to be > 0
"""
domain = field.domain
group = domain.groups[self.ig]
coors = domain.get_mesh_coors(actual=True)
if gtype == 'volume':
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
geo_ps = self.interp.get_geom_poly_space('v')
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, iels.astype(nm.int32), axis=0)
mapping = VolumeMapping(coors, conn, poly_space=geo_ps)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori)
out = vg
elif gtype == 'plate':
import sfepy.mechanics.membranes as mm
from sfepy.linalg import dot_sequences
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, nm.int32(iels), axis=0)
ccoors = coors[conn]
# Coordinate transformation matrix (transposed!).
mtx_t = mm.create_transformation_matrix(ccoors)
# Transform coordinates to the local coordinate system.
coors_loc = dot_sequences((ccoors - ccoors[:, 0:1, :]), mtx_t)
# Mapping from transformed elements to reference elements.
mapping = mm.create_mapping(coors_loc, field.gel, 1)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori)
vg.mtx_t = mtx_t
out = vg
elif (gtype == 'surface') or (gtype == 'surface_extra'):
assert_(field.approx_order > 0)
if self.ori is not None:
msg = 'surface integrals do not work yet with the' \
' hierarchical basis!'
raise ValueError(msg)
sd = domain.surface_groups[self.ig][region.name]
esd = self.surface_data[region.name]
qp = self.get_qp(sd.face_type, integral)
geo_ps = self.interp.get_geom_poly_space(sd.face_type)
ps = self.interp.poly_spaces[esd.face_type]
bf = self.get_base(esd.face_type, 0, integral)
conn = sd.get_connectivity()
mapping = SurfaceMapping(coors, conn, poly_space=geo_ps)
sg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
mode=gtype)
if gtype == 'surface_extra':
sg.alloc_extra_data(self.n_ep['v'])
self.create_bqp(region.name, integral)
qp = self.qp_coors[(integral.name, esd.bkey)]
v_geo_ps = self.interp.get_geom_poly_space('v')
bf_bg = v_geo_ps.eval_base(qp.vals, diff=True)
ebf_bg = self.get_base(esd.bkey, 1, integral)
sg.evaluate_bfbgm(bf_bg, ebf_bg, coors, sd.fis, group.conn)
out = sg
elif gtype == 'point':
out = mapping = None
else:
raise ValueError('unknown geometry type: %s' % gtype)
if out is not None:
# Store the integral used.
out.integral = integral
out.qp = qp
out.ps = ps
# Update base.
out.bf[:] = bf
if return_mapping:
out = (out, mapping)
return out
def _create_bqp(self, skey, bf_s, weights, integral_name):
interp = self.interp
gel = interp.gel
bkey = 'b%s' % skey[1:]
bqpkey = (integral_name, bkey)
coors, faces = gel.coors, gel.get_surface_entities()
vals = _interp_to_faces(coors, bf_s, faces)
self.qp_coors[bqpkey] = Struct(name = 'BQP_%s' % bkey,
vals = vals, weights = weights)
interp.poly_spaces[bkey] = interp.poly_spaces['v']
return bkey
def create_bqp(self, region_name, integral):
sd = self.surface_data[region_name]
bqpkey = (integral.name, sd.bkey)
if not bqpkey in self.qp_coors:
bf_s = self.get_base(sd.face_type, 0, integral,
from_geometry=True)
qp = self.get_qp(sd.face_type, integral)
bkey = self._create_bqp(sd.face_type, bf_s, qp.weights,
integral.name)
| assert_(bkey == sd.bkey) | sfepy.base.base.assert_ |
import numpy as nm
from sfepy.base.base import Struct, assert_
from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping
from poly_spaces import PolySpace
from fe_surface import FESurface
def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False,
clear_all=True):
if actual:
domain.mesh.coors_act = coors.copy()
else:
domain.mesh.coors = coors.copy()
if update_fields:
for field in fields.itervalues():
field.setup_coors(coors)
field.clear_mappings(clear_all=clear_all)
def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space,
econn, ig, only_extra=True):
"""
Compute coordinates of nodes corresponding to `poly_space`, given
mesh coordinates and `geom_poly_space`.
"""
if only_extra:
iex = (poly_space.nts[:,0] > 0).nonzero()[0]
if iex.shape[0] == 0: return
qp_coors = poly_space.node_coors[iex, :]
econn = econn[:, iex].copy()
else:
qp_coors = poly_space.node_coors
##
# Evaluate geometry interpolation base functions in (extra) nodes.
bf = geom_poly_space.eval_base(qp_coors)
bf = bf[:,0,:].copy()
##
# Evaluate extra coordinates with 'bf'.
group = region.domain.groups[ig]
cells = region.get_cells(ig)
ecoors = nm.dot(bf, mesh_coors[group.conn[cells]])
coors[econn] = nm.swapaxes(ecoors, 0, 1)
##
# 04.08.2005, c
def _interp_to_faces( vertex_vals, bfs, faces ):
dim = vertex_vals.shape[1]
n_face = faces.shape[0]
n_qp = bfs.shape[0]
faces_vals = nm.zeros( (n_face, n_qp, dim), nm.float64 )
for ii, face in enumerate( faces ):
vals = vertex_vals[face,:dim]
faces_vals[ii,:,:] = nm.dot( bfs[:,0,:], vals )
return( faces_vals )
class Interpolant( Struct ):
"""A simple wrapper around PolySpace."""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
self.name = name
self.gel = gel
self.poly_spaces = poly_spaces = {}
poly_spaces['v'] = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=force_bubble)
gel = gel.surface_facet
if gel is not None:
ps = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=False)
skey = 's%d' % ps.n_nod
poly_spaces[skey] = ps
def describe_nodes( self ):
ps = self.poly_spaces['v']
node_desc = ps.describe_nodes()
return node_desc
##
# 16.11.2007, c
def get_n_nodes( self ):
nn = {}
for key, ps in self.poly_spaces.iteritems():
nn[key] = ps.nodes.shape[0]
return nn
def get_geom_poly_space(self, key):
if key == 'v':
ps = self.gel.interp.poly_spaces['v']
elif key[0] == 's':
n_v = self.gel.surface_facet.n_vertex
ps = self.gel.interp.poly_spaces['s%d' % n_v]
else:
raise ValueError('bad polynomial space key! (%s)' % key)
return ps
class SurfaceInterpolant(Interpolant):
"""
Like Interpolant, but for use with SurfaceField and
SurfaceApproximation.
"""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
Interpolant.__init__(self, name, gel, space=space, base=base,
approx_order=approx_order,
force_bubble=force_bubble)
# Make alias 'v' <-> 's#'.
ps = self.poly_spaces['v']
self.poly_spaces['s%d' % ps.n_nod] = ps
def get_geom_poly_space(self, key):
assert_(key[0] == 's')
ps = self.gel.interp.poly_spaces['v']
return ps
##
# 18.07.2006, c
class Approximation( Struct ):
##
# 18.07.2006, c
# 10.10.2006
# 11.07.2007
# 17.07.2007
def __init__(self, name, interp, region, ig, is_surface=False):
"""interp, region are borrowed."""
self.name = name
self.interp = interp
self.region = region
self.ig = ig
self.is_surface = is_surface
self.surface_data = {}
self.edge_data = {}
self.point_data = {}
self.n_ep = self.interp.get_n_nodes()
self.ori = None
self.clear_qp_base()
def eval_extra_coor(self, coors, mesh_coors):
"""
Compute coordinates of extra nodes.
"""
gps = self.interp.gel.interp.poly_spaces['v']
ps = self.interp.poly_spaces['v']
eval_nodal_coors(coors, mesh_coors, self.region, ps, gps, self.econn, self.ig)
##
# c: 05.09.2006, r: 09.05.2008
def setup_surface_data( self, region ):
"""nodes[leconn] == econn"""
"""nodes are sorted by node number -> same order as region.vertices"""
sd = FESurface('surface_data_%s' % region.name, region,
self.efaces, self.econn, self.ig)
self.surface_data[region.name] = sd
return sd
##
# 11.07.2007, c
def setup_point_data( self, field, region ):
conn = field.get_dofs_in_region(region, merge=True, igs=region.igs)
## conn = [nods]\
## + [nm.empty( (0,), dtype = nm.int32 )]\
## * (len( region.igs ) - 1)
conn.shape += (1,)
self.point_data[region.name] = conn
def get_connectivity(self, region, integration, is_trace=False):
"""
Return the DOF connectivity for the given geometry type.
Parameters
----------
region : Region instance
The region, used to index surface and volume connectivities.
integration : one of ('volume', 'plate', 'surface', 'surface_extra')
The term integration type.
"""
if integration == 'surface':
sd = self.surface_data[region.name]
conn = sd.get_connectivity(self.is_surface, is_trace=is_trace)
elif integration in ('volume', 'plate', 'surface_extra'):
if region.name == self.region.name:
conn = self.econn
else:
aux = integration in ('volume', 'plate')
cells = region.get_cells(self.ig, true_cells_only=aux)
conn = nm.take(self.econn, cells.astype(nm.int32), axis=0)
else:
raise ValueError('unsupported term integration! (%s)' % integration)
return conn
def get_poly_space(self, key, from_geometry=False):
"""
Get the polynomial space.
Parameters
----------
key : 'v' or 's?'
The key denoting volume or surface.
from_geometry : bool
If True, return the polynomial space for affine geometrical
interpolation.
Returns
-------
ps : PolySpace instance
The polynomial space.
"""
if from_geometry:
ps = self.interp.get_geom_poly_space(key)
else:
ps = self.interp.poly_spaces[key]
return ps
def clear_qp_base(self):
"""
Remove cached quadrature points and base functions.
"""
self.qp_coors = {}
self.bf = {}
def get_qp(self, key, integral):
"""
Get quadrature points and weights corresponding to the given key
and integral. The key is 'v' or 's#', where # is the number of
face vertices.
"""
qpkey = (integral.name, key)
if not self.qp_coors.has_key(qpkey):
interp = self.interp
if (key[0] == 's'):
dim = interp.gel.dim - 1
n_fp = interp.gel.surface_facet.n_vertex
geometry = '%d_%d' % (dim, n_fp)
else:
geometry = interp.gel.name
vals, weights = integral.get_qp(geometry)
self.qp_coors[qpkey] = Struct(vals=vals, weights=weights)
return self.qp_coors[qpkey]
def get_base(self, key, derivative, integral, iels=None,
from_geometry=False, base_only=True):
qp = self.get_qp(key, integral)
ps = self.get_poly_space(key, from_geometry=from_geometry)
_key = key if not from_geometry else 'g' + key
bf_key = (integral.name, _key, derivative)
if not self.bf.has_key(bf_key):
if (iels is not None) and (self.ori is not None):
ori = self.ori[iels]
else:
ori = self.ori
self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori)
if base_only:
return self.bf[bf_key]
else:
return self.bf[bf_key], qp.weights
def describe_geometry(self, field, gtype, region, integral,
return_mapping=False):
"""
Compute jacobians, element volumes and base function derivatives
for Volume-type geometries (volume mappings), and jacobians,
normals and base function derivatives for Surface-type
geometries (surface mappings).
Notes
-----
- volume mappings can be defined on a part of an element group,
although the field has to be defined always on the whole group.
- surface mappings are defined on the surface region
- surface mappings require field order to be > 0
"""
domain = field.domain
group = domain.groups[self.ig]
coors = domain.get_mesh_coors(actual=True)
if gtype == 'volume':
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
geo_ps = self.interp.get_geom_poly_space('v')
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, iels.astype(nm.int32), axis=0)
mapping = VolumeMapping(coors, conn, poly_space=geo_ps)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori)
out = vg
elif gtype == 'plate':
import sfepy.mechanics.membranes as mm
from sfepy.linalg import dot_sequences
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, nm.int32(iels), axis=0)
ccoors = coors[conn]
# Coordinate transformation matrix (transposed!).
mtx_t = mm.create_transformation_matrix(ccoors)
# Transform coordinates to the local coordinate system.
coors_loc = dot_sequences((ccoors - ccoors[:, 0:1, :]), mtx_t)
# Mapping from transformed elements to reference elements.
mapping = mm.create_mapping(coors_loc, field.gel, 1)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori)
vg.mtx_t = mtx_t
out = vg
elif (gtype == 'surface') or (gtype == 'surface_extra'):
assert_(field.approx_order > 0)
if self.ori is not None:
msg = 'surface integrals do not work yet with the' \
' hierarchical basis!'
raise ValueError(msg)
sd = domain.surface_groups[self.ig][region.name]
esd = self.surface_data[region.name]
qp = self.get_qp(sd.face_type, integral)
geo_ps = self.interp.get_geom_poly_space(sd.face_type)
ps = self.interp.poly_spaces[esd.face_type]
bf = self.get_base(esd.face_type, 0, integral)
conn = sd.get_connectivity()
mapping = SurfaceMapping(coors, conn, poly_space=geo_ps)
sg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
mode=gtype)
if gtype == 'surface_extra':
sg.alloc_extra_data(self.n_ep['v'])
self.create_bqp(region.name, integral)
qp = self.qp_coors[(integral.name, esd.bkey)]
v_geo_ps = self.interp.get_geom_poly_space('v')
bf_bg = v_geo_ps.eval_base(qp.vals, diff=True)
ebf_bg = self.get_base(esd.bkey, 1, integral)
sg.evaluate_bfbgm(bf_bg, ebf_bg, coors, sd.fis, group.conn)
out = sg
elif gtype == 'point':
out = mapping = None
else:
raise ValueError('unknown geometry type: %s' % gtype)
if out is not None:
# Store the integral used.
out.integral = integral
out.qp = qp
out.ps = ps
# Update base.
out.bf[:] = bf
if return_mapping:
out = (out, mapping)
return out
def _create_bqp(self, skey, bf_s, weights, integral_name):
interp = self.interp
gel = interp.gel
bkey = 'b%s' % skey[1:]
bqpkey = (integral_name, bkey)
coors, faces = gel.coors, gel.get_surface_entities()
vals = _interp_to_faces(coors, bf_s, faces)
self.qp_coors[bqpkey] = Struct(name = 'BQP_%s' % bkey,
vals = vals, weights = weights)
interp.poly_spaces[bkey] = interp.poly_spaces['v']
return bkey
def create_bqp(self, region_name, integral):
sd = self.surface_data[region_name]
bqpkey = (integral.name, sd.bkey)
if not bqpkey in self.qp_coors:
bf_s = self.get_base(sd.face_type, 0, integral,
from_geometry=True)
qp = self.get_qp(sd.face_type, integral)
bkey = self._create_bqp(sd.face_type, bf_s, qp.weights,
integral.name)
assert_(bkey == sd.bkey)
class DiscontinuousApproximation(Approximation):
def eval_extra_coor(self, coors, mesh_coors):
"""
Compute coordinates of extra nodes. For discontinuous
approximations, all nodes are treated as extra.
"""
gps = self.interp.gel.interp.poly_spaces['v']
ps = self.interp.poly_spaces['v']
eval_nodal_coors(coors, mesh_coors, self.region, ps, gps,
self.econn, self.ig, only_extra=False)
class SurfaceApproximation(Approximation):
def __init__(self, name, interp, region, ig):
Approximation.__init__(self, name, interp, region, ig, is_surface=True)
def get_qp(self, key, integral):
"""
Get quadrature points and weights corresponding to the given key
and integral. The key is 's#', where # is the number of
face vertices.
"""
assert_(key[0] == 's')
qpkey = (integral.name, key)
if not self.qp_coors.has_key(qpkey):
interp = self.interp
geometry = interp.gel.name
vals, weights = integral.get_qp(geometry)
self.qp_coors[qpkey] = | Struct(vals=vals, weights=weights) | sfepy.base.base.Struct |
import numpy as nm
from sfepy.base.base import Struct, assert_
from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping
from poly_spaces import PolySpace
from fe_surface import FESurface
def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False,
clear_all=True):
if actual:
domain.mesh.coors_act = coors.copy()
else:
domain.mesh.coors = coors.copy()
if update_fields:
for field in fields.itervalues():
field.setup_coors(coors)
field.clear_mappings(clear_all=clear_all)
def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space,
econn, ig, only_extra=True):
"""
Compute coordinates of nodes corresponding to `poly_space`, given
mesh coordinates and `geom_poly_space`.
"""
if only_extra:
iex = (poly_space.nts[:,0] > 0).nonzero()[0]
if iex.shape[0] == 0: return
qp_coors = poly_space.node_coors[iex, :]
econn = econn[:, iex].copy()
else:
qp_coors = poly_space.node_coors
##
# Evaluate geometry interpolation base functions in (extra) nodes.
bf = geom_poly_space.eval_base(qp_coors)
bf = bf[:,0,:].copy()
##
# Evaluate extra coordinates with 'bf'.
group = region.domain.groups[ig]
cells = region.get_cells(ig)
ecoors = nm.dot(bf, mesh_coors[group.conn[cells]])
coors[econn] = nm.swapaxes(ecoors, 0, 1)
##
# 04.08.2005, c
def _interp_to_faces( vertex_vals, bfs, faces ):
dim = vertex_vals.shape[1]
n_face = faces.shape[0]
n_qp = bfs.shape[0]
faces_vals = nm.zeros( (n_face, n_qp, dim), nm.float64 )
for ii, face in enumerate( faces ):
vals = vertex_vals[face,:dim]
faces_vals[ii,:,:] = nm.dot( bfs[:,0,:], vals )
return( faces_vals )
class Interpolant( Struct ):
"""A simple wrapper around PolySpace."""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
self.name = name
self.gel = gel
self.poly_spaces = poly_spaces = {}
poly_spaces['v'] = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=force_bubble)
gel = gel.surface_facet
if gel is not None:
ps = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=False)
skey = 's%d' % ps.n_nod
poly_spaces[skey] = ps
def describe_nodes( self ):
ps = self.poly_spaces['v']
node_desc = ps.describe_nodes()
return node_desc
##
# 16.11.2007, c
def get_n_nodes( self ):
nn = {}
for key, ps in self.poly_spaces.iteritems():
nn[key] = ps.nodes.shape[0]
return nn
def get_geom_poly_space(self, key):
if key == 'v':
ps = self.gel.interp.poly_spaces['v']
elif key[0] == 's':
n_v = self.gel.surface_facet.n_vertex
ps = self.gel.interp.poly_spaces['s%d' % n_v]
else:
raise ValueError('bad polynomial space key! (%s)' % key)
return ps
class SurfaceInterpolant(Interpolant):
"""
Like Interpolant, but for use with SurfaceField and
SurfaceApproximation.
"""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
Interpolant.__init__(self, name, gel, space=space, base=base,
approx_order=approx_order,
force_bubble=force_bubble)
# Make alias 'v' <-> 's#'.
ps = self.poly_spaces['v']
self.poly_spaces['s%d' % ps.n_nod] = ps
def get_geom_poly_space(self, key):
assert_(key[0] == 's')
ps = self.gel.interp.poly_spaces['v']
return ps
##
# 18.07.2006, c
class Approximation( Struct ):
##
# 18.07.2006, c
# 10.10.2006
# 11.07.2007
# 17.07.2007
def __init__(self, name, interp, region, ig, is_surface=False):
"""interp, region are borrowed."""
self.name = name
self.interp = interp
self.region = region
self.ig = ig
self.is_surface = is_surface
self.surface_data = {}
self.edge_data = {}
self.point_data = {}
self.n_ep = self.interp.get_n_nodes()
self.ori = None
self.clear_qp_base()
def eval_extra_coor(self, coors, mesh_coors):
"""
Compute coordinates of extra nodes.
"""
gps = self.interp.gel.interp.poly_spaces['v']
ps = self.interp.poly_spaces['v']
eval_nodal_coors(coors, mesh_coors, self.region, ps, gps, self.econn, self.ig)
##
# c: 05.09.2006, r: 09.05.2008
def setup_surface_data( self, region ):
"""nodes[leconn] == econn"""
"""nodes are sorted by node number -> same order as region.vertices"""
sd = FESurface('surface_data_%s' % region.name, region,
self.efaces, self.econn, self.ig)
self.surface_data[region.name] = sd
return sd
##
# 11.07.2007, c
def setup_point_data( self, field, region ):
conn = field.get_dofs_in_region(region, merge=True, igs=region.igs)
## conn = [nods]\
## + [nm.empty( (0,), dtype = nm.int32 )]\
## * (len( region.igs ) - 1)
conn.shape += (1,)
self.point_data[region.name] = conn
def get_connectivity(self, region, integration, is_trace=False):
"""
Return the DOF connectivity for the given geometry type.
Parameters
----------
region : Region instance
The region, used to index surface and volume connectivities.
integration : one of ('volume', 'plate', 'surface', 'surface_extra')
The term integration type.
"""
if integration == 'surface':
sd = self.surface_data[region.name]
conn = sd.get_connectivity(self.is_surface, is_trace=is_trace)
elif integration in ('volume', 'plate', 'surface_extra'):
if region.name == self.region.name:
conn = self.econn
else:
aux = integration in ('volume', 'plate')
cells = region.get_cells(self.ig, true_cells_only=aux)
conn = nm.take(self.econn, cells.astype(nm.int32), axis=0)
else:
raise ValueError('unsupported term integration! (%s)' % integration)
return conn
def get_poly_space(self, key, from_geometry=False):
"""
Get the polynomial space.
Parameters
----------
key : 'v' or 's?'
The key denoting volume or surface.
from_geometry : bool
If True, return the polynomial space for affine geometrical
interpolation.
Returns
-------
ps : PolySpace instance
The polynomial space.
"""
if from_geometry:
ps = self.interp.get_geom_poly_space(key)
else:
ps = self.interp.poly_spaces[key]
return ps
def clear_qp_base(self):
"""
Remove cached quadrature points and base functions.
"""
self.qp_coors = {}
self.bf = {}
def get_qp(self, key, integral):
"""
Get quadrature points and weights corresponding to the given key
and integral. The key is 'v' or 's#', where # is the number of
face vertices.
"""
qpkey = (integral.name, key)
if not self.qp_coors.has_key(qpkey):
interp = self.interp
if (key[0] == 's'):
dim = interp.gel.dim - 1
n_fp = interp.gel.surface_facet.n_vertex
geometry = '%d_%d' % (dim, n_fp)
else:
geometry = interp.gel.name
vals, weights = integral.get_qp(geometry)
self.qp_coors[qpkey] = Struct(vals=vals, weights=weights)
return self.qp_coors[qpkey]
def get_base(self, key, derivative, integral, iels=None,
from_geometry=False, base_only=True):
qp = self.get_qp(key, integral)
ps = self.get_poly_space(key, from_geometry=from_geometry)
_key = key if not from_geometry else 'g' + key
bf_key = (integral.name, _key, derivative)
if not self.bf.has_key(bf_key):
if (iels is not None) and (self.ori is not None):
ori = self.ori[iels]
else:
ori = self.ori
self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori)
if base_only:
return self.bf[bf_key]
else:
return self.bf[bf_key], qp.weights
def describe_geometry(self, field, gtype, region, integral,
return_mapping=False):
"""
Compute jacobians, element volumes and base function derivatives
for Volume-type geometries (volume mappings), and jacobians,
normals and base function derivatives for Surface-type
geometries (surface mappings).
Notes
-----
- volume mappings can be defined on a part of an element group,
although the field has to be defined always on the whole group.
- surface mappings are defined on the surface region
- surface mappings require field order to be > 0
"""
domain = field.domain
group = domain.groups[self.ig]
coors = domain.get_mesh_coors(actual=True)
if gtype == 'volume':
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
geo_ps = self.interp.get_geom_poly_space('v')
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, iels.astype(nm.int32), axis=0)
mapping = VolumeMapping(coors, conn, poly_space=geo_ps)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori)
out = vg
elif gtype == 'plate':
import sfepy.mechanics.membranes as mm
from sfepy.linalg import dot_sequences
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, nm.int32(iels), axis=0)
ccoors = coors[conn]
# Coordinate transformation matrix (transposed!).
mtx_t = | mm.create_transformation_matrix(ccoors) | sfepy.mechanics.membranes.create_transformation_matrix |
import numpy as nm
from sfepy.base.base import Struct, assert_
from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping
from poly_spaces import PolySpace
from fe_surface import FESurface
def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False,
clear_all=True):
if actual:
domain.mesh.coors_act = coors.copy()
else:
domain.mesh.coors = coors.copy()
if update_fields:
for field in fields.itervalues():
field.setup_coors(coors)
field.clear_mappings(clear_all=clear_all)
def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space,
econn, ig, only_extra=True):
"""
Compute coordinates of nodes corresponding to `poly_space`, given
mesh coordinates and `geom_poly_space`.
"""
if only_extra:
iex = (poly_space.nts[:,0] > 0).nonzero()[0]
if iex.shape[0] == 0: return
qp_coors = poly_space.node_coors[iex, :]
econn = econn[:, iex].copy()
else:
qp_coors = poly_space.node_coors
##
# Evaluate geometry interpolation base functions in (extra) nodes.
bf = geom_poly_space.eval_base(qp_coors)
bf = bf[:,0,:].copy()
##
# Evaluate extra coordinates with 'bf'.
group = region.domain.groups[ig]
cells = region.get_cells(ig)
ecoors = nm.dot(bf, mesh_coors[group.conn[cells]])
coors[econn] = nm.swapaxes(ecoors, 0, 1)
##
# 04.08.2005, c
def _interp_to_faces( vertex_vals, bfs, faces ):
dim = vertex_vals.shape[1]
n_face = faces.shape[0]
n_qp = bfs.shape[0]
faces_vals = nm.zeros( (n_face, n_qp, dim), nm.float64 )
for ii, face in enumerate( faces ):
vals = vertex_vals[face,:dim]
faces_vals[ii,:,:] = nm.dot( bfs[:,0,:], vals )
return( faces_vals )
class Interpolant( Struct ):
"""A simple wrapper around PolySpace."""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
self.name = name
self.gel = gel
self.poly_spaces = poly_spaces = {}
poly_spaces['v'] = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=force_bubble)
gel = gel.surface_facet
if gel is not None:
ps = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=False)
skey = 's%d' % ps.n_nod
poly_spaces[skey] = ps
def describe_nodes( self ):
ps = self.poly_spaces['v']
node_desc = ps.describe_nodes()
return node_desc
##
# 16.11.2007, c
def get_n_nodes( self ):
nn = {}
for key, ps in self.poly_spaces.iteritems():
nn[key] = ps.nodes.shape[0]
return nn
def get_geom_poly_space(self, key):
if key == 'v':
ps = self.gel.interp.poly_spaces['v']
elif key[0] == 's':
n_v = self.gel.surface_facet.n_vertex
ps = self.gel.interp.poly_spaces['s%d' % n_v]
else:
raise ValueError('bad polynomial space key! (%s)' % key)
return ps
class SurfaceInterpolant(Interpolant):
"""
Like Interpolant, but for use with SurfaceField and
SurfaceApproximation.
"""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
Interpolant.__init__(self, name, gel, space=space, base=base,
approx_order=approx_order,
force_bubble=force_bubble)
# Make alias 'v' <-> 's#'.
ps = self.poly_spaces['v']
self.poly_spaces['s%d' % ps.n_nod] = ps
def get_geom_poly_space(self, key):
assert_(key[0] == 's')
ps = self.gel.interp.poly_spaces['v']
return ps
##
# 18.07.2006, c
class Approximation( Struct ):
##
# 18.07.2006, c
# 10.10.2006
# 11.07.2007
# 17.07.2007
def __init__(self, name, interp, region, ig, is_surface=False):
"""interp, region are borrowed."""
self.name = name
self.interp = interp
self.region = region
self.ig = ig
self.is_surface = is_surface
self.surface_data = {}
self.edge_data = {}
self.point_data = {}
self.n_ep = self.interp.get_n_nodes()
self.ori = None
self.clear_qp_base()
def eval_extra_coor(self, coors, mesh_coors):
"""
Compute coordinates of extra nodes.
"""
gps = self.interp.gel.interp.poly_spaces['v']
ps = self.interp.poly_spaces['v']
eval_nodal_coors(coors, mesh_coors, self.region, ps, gps, self.econn, self.ig)
##
# c: 05.09.2006, r: 09.05.2008
def setup_surface_data( self, region ):
"""nodes[leconn] == econn"""
"""nodes are sorted by node number -> same order as region.vertices"""
sd = FESurface('surface_data_%s' % region.name, region,
self.efaces, self.econn, self.ig)
self.surface_data[region.name] = sd
return sd
##
# 11.07.2007, c
def setup_point_data( self, field, region ):
conn = field.get_dofs_in_region(region, merge=True, igs=region.igs)
## conn = [nods]\
## + [nm.empty( (0,), dtype = nm.int32 )]\
## * (len( region.igs ) - 1)
conn.shape += (1,)
self.point_data[region.name] = conn
def get_connectivity(self, region, integration, is_trace=False):
"""
Return the DOF connectivity for the given geometry type.
Parameters
----------
region : Region instance
The region, used to index surface and volume connectivities.
integration : one of ('volume', 'plate', 'surface', 'surface_extra')
The term integration type.
"""
if integration == 'surface':
sd = self.surface_data[region.name]
conn = sd.get_connectivity(self.is_surface, is_trace=is_trace)
elif integration in ('volume', 'plate', 'surface_extra'):
if region.name == self.region.name:
conn = self.econn
else:
aux = integration in ('volume', 'plate')
cells = region.get_cells(self.ig, true_cells_only=aux)
conn = nm.take(self.econn, cells.astype(nm.int32), axis=0)
else:
raise ValueError('unsupported term integration! (%s)' % integration)
return conn
def get_poly_space(self, key, from_geometry=False):
"""
Get the polynomial space.
Parameters
----------
key : 'v' or 's?'
The key denoting volume or surface.
from_geometry : bool
If True, return the polynomial space for affine geometrical
interpolation.
Returns
-------
ps : PolySpace instance
The polynomial space.
"""
if from_geometry:
ps = self.interp.get_geom_poly_space(key)
else:
ps = self.interp.poly_spaces[key]
return ps
def clear_qp_base(self):
"""
Remove cached quadrature points and base functions.
"""
self.qp_coors = {}
self.bf = {}
def get_qp(self, key, integral):
"""
Get quadrature points and weights corresponding to the given key
and integral. The key is 'v' or 's#', where # is the number of
face vertices.
"""
qpkey = (integral.name, key)
if not self.qp_coors.has_key(qpkey):
interp = self.interp
if (key[0] == 's'):
dim = interp.gel.dim - 1
n_fp = interp.gel.surface_facet.n_vertex
geometry = '%d_%d' % (dim, n_fp)
else:
geometry = interp.gel.name
vals, weights = integral.get_qp(geometry)
self.qp_coors[qpkey] = Struct(vals=vals, weights=weights)
return self.qp_coors[qpkey]
def get_base(self, key, derivative, integral, iels=None,
from_geometry=False, base_only=True):
qp = self.get_qp(key, integral)
ps = self.get_poly_space(key, from_geometry=from_geometry)
_key = key if not from_geometry else 'g' + key
bf_key = (integral.name, _key, derivative)
if not self.bf.has_key(bf_key):
if (iels is not None) and (self.ori is not None):
ori = self.ori[iels]
else:
ori = self.ori
self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori)
if base_only:
return self.bf[bf_key]
else:
return self.bf[bf_key], qp.weights
def describe_geometry(self, field, gtype, region, integral,
return_mapping=False):
"""
Compute jacobians, element volumes and base function derivatives
for Volume-type geometries (volume mappings), and jacobians,
normals and base function derivatives for Surface-type
geometries (surface mappings).
Notes
-----
- volume mappings can be defined on a part of an element group,
although the field has to be defined always on the whole group.
- surface mappings are defined on the surface region
- surface mappings require field order to be > 0
"""
domain = field.domain
group = domain.groups[self.ig]
coors = domain.get_mesh_coors(actual=True)
if gtype == 'volume':
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
geo_ps = self.interp.get_geom_poly_space('v')
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, iels.astype(nm.int32), axis=0)
mapping = VolumeMapping(coors, conn, poly_space=geo_ps)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori)
out = vg
elif gtype == 'plate':
import sfepy.mechanics.membranes as mm
from sfepy.linalg import dot_sequences
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, nm.int32(iels), axis=0)
ccoors = coors[conn]
# Coordinate transformation matrix (transposed!).
mtx_t = mm.create_transformation_matrix(ccoors)
# Transform coordinates to the local coordinate system.
coors_loc = dot_sequences((ccoors - ccoors[:, 0:1, :]), mtx_t)
# Mapping from transformed elements to reference elements.
mapping = | mm.create_mapping(coors_loc, field.gel, 1) | sfepy.mechanics.membranes.create_mapping |
import numpy as nm
from sfepy.base.base import Struct, assert_
from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping
from poly_spaces import PolySpace
from fe_surface import FESurface
def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False,
clear_all=True):
if actual:
domain.mesh.coors_act = coors.copy()
else:
domain.mesh.coors = coors.copy()
if update_fields:
for field in fields.itervalues():
field.setup_coors(coors)
field.clear_mappings(clear_all=clear_all)
def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space,
econn, ig, only_extra=True):
"""
Compute coordinates of nodes corresponding to `poly_space`, given
mesh coordinates and `geom_poly_space`.
"""
if only_extra:
iex = (poly_space.nts[:,0] > 0).nonzero()[0]
if iex.shape[0] == 0: return
qp_coors = poly_space.node_coors[iex, :]
econn = econn[:, iex].copy()
else:
qp_coors = poly_space.node_coors
##
# Evaluate geometry interpolation base functions in (extra) nodes.
bf = geom_poly_space.eval_base(qp_coors)
bf = bf[:,0,:].copy()
##
# Evaluate extra coordinates with 'bf'.
group = region.domain.groups[ig]
cells = region.get_cells(ig)
ecoors = nm.dot(bf, mesh_coors[group.conn[cells]])
coors[econn] = nm.swapaxes(ecoors, 0, 1)
##
# 04.08.2005, c
def _interp_to_faces( vertex_vals, bfs, faces ):
dim = vertex_vals.shape[1]
n_face = faces.shape[0]
n_qp = bfs.shape[0]
faces_vals = nm.zeros( (n_face, n_qp, dim), nm.float64 )
for ii, face in enumerate( faces ):
vals = vertex_vals[face,:dim]
faces_vals[ii,:,:] = nm.dot( bfs[:,0,:], vals )
return( faces_vals )
class Interpolant( Struct ):
"""A simple wrapper around PolySpace."""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
self.name = name
self.gel = gel
self.poly_spaces = poly_spaces = {}
poly_spaces['v'] = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=force_bubble)
gel = gel.surface_facet
if gel is not None:
ps = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=False)
skey = 's%d' % ps.n_nod
poly_spaces[skey] = ps
def describe_nodes( self ):
ps = self.poly_spaces['v']
node_desc = ps.describe_nodes()
return node_desc
##
# 16.11.2007, c
def get_n_nodes( self ):
nn = {}
for key, ps in self.poly_spaces.iteritems():
nn[key] = ps.nodes.shape[0]
return nn
def get_geom_poly_space(self, key):
if key == 'v':
ps = self.gel.interp.poly_spaces['v']
elif key[0] == 's':
n_v = self.gel.surface_facet.n_vertex
ps = self.gel.interp.poly_spaces['s%d' % n_v]
else:
raise ValueError('bad polynomial space key! (%s)' % key)
return ps
class SurfaceInterpolant(Interpolant):
"""
Like Interpolant, but for use with SurfaceField and
SurfaceApproximation.
"""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
Interpolant.__init__(self, name, gel, space=space, base=base,
approx_order=approx_order,
force_bubble=force_bubble)
# Make alias 'v' <-> 's#'.
ps = self.poly_spaces['v']
self.poly_spaces['s%d' % ps.n_nod] = ps
def get_geom_poly_space(self, key):
assert_(key[0] == 's')
ps = self.gel.interp.poly_spaces['v']
return ps
##
# 18.07.2006, c
class Approximation( Struct ):
##
# 18.07.2006, c
# 10.10.2006
# 11.07.2007
# 17.07.2007
def __init__(self, name, interp, region, ig, is_surface=False):
"""interp, region are borrowed."""
self.name = name
self.interp = interp
self.region = region
self.ig = ig
self.is_surface = is_surface
self.surface_data = {}
self.edge_data = {}
self.point_data = {}
self.n_ep = self.interp.get_n_nodes()
self.ori = None
self.clear_qp_base()
def eval_extra_coor(self, coors, mesh_coors):
"""
Compute coordinates of extra nodes.
"""
gps = self.interp.gel.interp.poly_spaces['v']
ps = self.interp.poly_spaces['v']
eval_nodal_coors(coors, mesh_coors, self.region, ps, gps, self.econn, self.ig)
##
# c: 05.09.2006, r: 09.05.2008
def setup_surface_data( self, region ):
"""nodes[leconn] == econn"""
"""nodes are sorted by node number -> same order as region.vertices"""
sd = FESurface('surface_data_%s' % region.name, region,
self.efaces, self.econn, self.ig)
self.surface_data[region.name] = sd
return sd
##
# 11.07.2007, c
def setup_point_data( self, field, region ):
conn = field.get_dofs_in_region(region, merge=True, igs=region.igs)
## conn = [nods]\
## + [nm.empty( (0,), dtype = nm.int32 )]\
## * (len( region.igs ) - 1)
conn.shape += (1,)
self.point_data[region.name] = conn
def get_connectivity(self, region, integration, is_trace=False):
"""
Return the DOF connectivity for the given geometry type.
Parameters
----------
region : Region instance
The region, used to index surface and volume connectivities.
integration : one of ('volume', 'plate', 'surface', 'surface_extra')
The term integration type.
"""
if integration == 'surface':
sd = self.surface_data[region.name]
conn = sd.get_connectivity(self.is_surface, is_trace=is_trace)
elif integration in ('volume', 'plate', 'surface_extra'):
if region.name == self.region.name:
conn = self.econn
else:
aux = integration in ('volume', 'plate')
cells = region.get_cells(self.ig, true_cells_only=aux)
conn = nm.take(self.econn, cells.astype(nm.int32), axis=0)
else:
raise ValueError('unsupported term integration! (%s)' % integration)
return conn
def get_poly_space(self, key, from_geometry=False):
"""
Get the polynomial space.
Parameters
----------
key : 'v' or 's?'
The key denoting volume or surface.
from_geometry : bool
If True, return the polynomial space for affine geometrical
interpolation.
Returns
-------
ps : PolySpace instance
The polynomial space.
"""
if from_geometry:
ps = self.interp.get_geom_poly_space(key)
else:
ps = self.interp.poly_spaces[key]
return ps
def clear_qp_base(self):
"""
Remove cached quadrature points and base functions.
"""
self.qp_coors = {}
self.bf = {}
def get_qp(self, key, integral):
"""
Get quadrature points and weights corresponding to the given key
and integral. The key is 'v' or 's#', where # is the number of
face vertices.
"""
qpkey = (integral.name, key)
if not self.qp_coors.has_key(qpkey):
interp = self.interp
if (key[0] == 's'):
dim = interp.gel.dim - 1
n_fp = interp.gel.surface_facet.n_vertex
geometry = '%d_%d' % (dim, n_fp)
else:
geometry = interp.gel.name
vals, weights = integral.get_qp(geometry)
self.qp_coors[qpkey] = Struct(vals=vals, weights=weights)
return self.qp_coors[qpkey]
def get_base(self, key, derivative, integral, iels=None,
from_geometry=False, base_only=True):
qp = self.get_qp(key, integral)
ps = self.get_poly_space(key, from_geometry=from_geometry)
_key = key if not from_geometry else 'g' + key
bf_key = (integral.name, _key, derivative)
if not self.bf.has_key(bf_key):
if (iels is not None) and (self.ori is not None):
ori = self.ori[iels]
else:
ori = self.ori
self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori)
if base_only:
return self.bf[bf_key]
else:
return self.bf[bf_key], qp.weights
def describe_geometry(self, field, gtype, region, integral,
return_mapping=False):
"""
Compute jacobians, element volumes and base function derivatives
for Volume-type geometries (volume mappings), and jacobians,
normals and base function derivatives for Surface-type
geometries (surface mappings).
Notes
-----
- volume mappings can be defined on a part of an element group,
although the field has to be defined always on the whole group.
- surface mappings are defined on the surface region
- surface mappings require field order to be > 0
"""
domain = field.domain
group = domain.groups[self.ig]
coors = domain.get_mesh_coors(actual=True)
if gtype == 'volume':
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
geo_ps = self.interp.get_geom_poly_space('v')
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, iels.astype(nm.int32), axis=0)
mapping = VolumeMapping(coors, conn, poly_space=geo_ps)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori)
out = vg
elif gtype == 'plate':
import sfepy.mechanics.membranes as mm
from sfepy.linalg import dot_sequences
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, nm.int32(iels), axis=0)
ccoors = coors[conn]
# Coordinate transformation matrix (transposed!).
mtx_t = mm.create_transformation_matrix(ccoors)
# Transform coordinates to the local coordinate system.
coors_loc = dot_sequences((ccoors - ccoors[:, 0:1, :]), mtx_t)
# Mapping from transformed elements to reference elements.
mapping = mm.create_mapping(coors_loc, field.gel, 1)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori)
vg.mtx_t = mtx_t
out = vg
elif (gtype == 'surface') or (gtype == 'surface_extra'):
| assert_(field.approx_order > 0) | sfepy.base.base.assert_ |
import numpy as nm
from sfepy.base.base import Struct, assert_
from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping
from poly_spaces import PolySpace
from fe_surface import FESurface
def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False,
clear_all=True):
if actual:
domain.mesh.coors_act = coors.copy()
else:
domain.mesh.coors = coors.copy()
if update_fields:
for field in fields.itervalues():
field.setup_coors(coors)
field.clear_mappings(clear_all=clear_all)
def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space,
econn, ig, only_extra=True):
"""
Compute coordinates of nodes corresponding to `poly_space`, given
mesh coordinates and `geom_poly_space`.
"""
if only_extra:
iex = (poly_space.nts[:,0] > 0).nonzero()[0]
if iex.shape[0] == 0: return
qp_coors = poly_space.node_coors[iex, :]
econn = econn[:, iex].copy()
else:
qp_coors = poly_space.node_coors
##
# Evaluate geometry interpolation base functions in (extra) nodes.
bf = geom_poly_space.eval_base(qp_coors)
bf = bf[:,0,:].copy()
##
# Evaluate extra coordinates with 'bf'.
group = region.domain.groups[ig]
cells = region.get_cells(ig)
ecoors = nm.dot(bf, mesh_coors[group.conn[cells]])
coors[econn] = nm.swapaxes(ecoors, 0, 1)
##
# 04.08.2005, c
def _interp_to_faces( vertex_vals, bfs, faces ):
dim = vertex_vals.shape[1]
n_face = faces.shape[0]
n_qp = bfs.shape[0]
faces_vals = nm.zeros( (n_face, n_qp, dim), nm.float64 )
for ii, face in enumerate( faces ):
vals = vertex_vals[face,:dim]
faces_vals[ii,:,:] = nm.dot( bfs[:,0,:], vals )
return( faces_vals )
class Interpolant( Struct ):
"""A simple wrapper around PolySpace."""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
self.name = name
self.gel = gel
self.poly_spaces = poly_spaces = {}
poly_spaces['v'] = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=force_bubble)
gel = gel.surface_facet
if gel is not None:
ps = PolySpace.any_from_args(name, gel, approx_order,
base=base,
force_bubble=False)
skey = 's%d' % ps.n_nod
poly_spaces[skey] = ps
def describe_nodes( self ):
ps = self.poly_spaces['v']
node_desc = ps.describe_nodes()
return node_desc
##
# 16.11.2007, c
def get_n_nodes( self ):
nn = {}
for key, ps in self.poly_spaces.iteritems():
nn[key] = ps.nodes.shape[0]
return nn
def get_geom_poly_space(self, key):
if key == 'v':
ps = self.gel.interp.poly_spaces['v']
elif key[0] == 's':
n_v = self.gel.surface_facet.n_vertex
ps = self.gel.interp.poly_spaces['s%d' % n_v]
else:
raise ValueError('bad polynomial space key! (%s)' % key)
return ps
class SurfaceInterpolant(Interpolant):
"""
Like Interpolant, but for use with SurfaceField and
SurfaceApproximation.
"""
def __init__(self, name, gel, space='H1', base='lagrange',
approx_order=1, force_bubble=False):
Interpolant.__init__(self, name, gel, space=space, base=base,
approx_order=approx_order,
force_bubble=force_bubble)
# Make alias 'v' <-> 's#'.
ps = self.poly_spaces['v']
self.poly_spaces['s%d' % ps.n_nod] = ps
def get_geom_poly_space(self, key):
assert_(key[0] == 's')
ps = self.gel.interp.poly_spaces['v']
return ps
##
# 18.07.2006, c
class Approximation( Struct ):
##
# 18.07.2006, c
# 10.10.2006
# 11.07.2007
# 17.07.2007
def __init__(self, name, interp, region, ig, is_surface=False):
"""interp, region are borrowed."""
self.name = name
self.interp = interp
self.region = region
self.ig = ig
self.is_surface = is_surface
self.surface_data = {}
self.edge_data = {}
self.point_data = {}
self.n_ep = self.interp.get_n_nodes()
self.ori = None
self.clear_qp_base()
def eval_extra_coor(self, coors, mesh_coors):
"""
Compute coordinates of extra nodes.
"""
gps = self.interp.gel.interp.poly_spaces['v']
ps = self.interp.poly_spaces['v']
eval_nodal_coors(coors, mesh_coors, self.region, ps, gps, self.econn, self.ig)
##
# c: 05.09.2006, r: 09.05.2008
def setup_surface_data( self, region ):
"""nodes[leconn] == econn"""
"""nodes are sorted by node number -> same order as region.vertices"""
sd = FESurface('surface_data_%s' % region.name, region,
self.efaces, self.econn, self.ig)
self.surface_data[region.name] = sd
return sd
##
# 11.07.2007, c
def setup_point_data( self, field, region ):
conn = field.get_dofs_in_region(region, merge=True, igs=region.igs)
## conn = [nods]\
## + [nm.empty( (0,), dtype = nm.int32 )]\
## * (len( region.igs ) - 1)
conn.shape += (1,)
self.point_data[region.name] = conn
def get_connectivity(self, region, integration, is_trace=False):
"""
Return the DOF connectivity for the given geometry type.
Parameters
----------
region : Region instance
The region, used to index surface and volume connectivities.
integration : one of ('volume', 'plate', 'surface', 'surface_extra')
The term integration type.
"""
if integration == 'surface':
sd = self.surface_data[region.name]
conn = sd.get_connectivity(self.is_surface, is_trace=is_trace)
elif integration in ('volume', 'plate', 'surface_extra'):
if region.name == self.region.name:
conn = self.econn
else:
aux = integration in ('volume', 'plate')
cells = region.get_cells(self.ig, true_cells_only=aux)
conn = nm.take(self.econn, cells.astype(nm.int32), axis=0)
else:
raise ValueError('unsupported term integration! (%s)' % integration)
return conn
def get_poly_space(self, key, from_geometry=False):
"""
Get the polynomial space.
Parameters
----------
key : 'v' or 's?'
The key denoting volume or surface.
from_geometry : bool
If True, return the polynomial space for affine geometrical
interpolation.
Returns
-------
ps : PolySpace instance
The polynomial space.
"""
if from_geometry:
ps = self.interp.get_geom_poly_space(key)
else:
ps = self.interp.poly_spaces[key]
return ps
def clear_qp_base(self):
"""
Remove cached quadrature points and base functions.
"""
self.qp_coors = {}
self.bf = {}
def get_qp(self, key, integral):
"""
Get quadrature points and weights corresponding to the given key
and integral. The key is 'v' or 's#', where # is the number of
face vertices.
"""
qpkey = (integral.name, key)
if not self.qp_coors.has_key(qpkey):
interp = self.interp
if (key[0] == 's'):
dim = interp.gel.dim - 1
n_fp = interp.gel.surface_facet.n_vertex
geometry = '%d_%d' % (dim, n_fp)
else:
geometry = interp.gel.name
vals, weights = integral.get_qp(geometry)
self.qp_coors[qpkey] = Struct(vals=vals, weights=weights)
return self.qp_coors[qpkey]
def get_base(self, key, derivative, integral, iels=None,
from_geometry=False, base_only=True):
qp = self.get_qp(key, integral)
ps = self.get_poly_space(key, from_geometry=from_geometry)
_key = key if not from_geometry else 'g' + key
bf_key = (integral.name, _key, derivative)
if not self.bf.has_key(bf_key):
if (iels is not None) and (self.ori is not None):
ori = self.ori[iels]
else:
ori = self.ori
self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori)
if base_only:
return self.bf[bf_key]
else:
return self.bf[bf_key], qp.weights
def describe_geometry(self, field, gtype, region, integral,
return_mapping=False):
"""
Compute jacobians, element volumes and base function derivatives
for Volume-type geometries (volume mappings), and jacobians,
normals and base function derivatives for Surface-type
geometries (surface mappings).
Notes
-----
- volume mappings can be defined on a part of an element group,
although the field has to be defined always on the whole group.
- surface mappings are defined on the surface region
- surface mappings require field order to be > 0
"""
domain = field.domain
group = domain.groups[self.ig]
coors = domain.get_mesh_coors(actual=True)
if gtype == 'volume':
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
geo_ps = self.interp.get_geom_poly_space('v')
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, iels.astype(nm.int32), axis=0)
mapping = VolumeMapping(coors, conn, poly_space=geo_ps)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori)
out = vg
elif gtype == 'plate':
import sfepy.mechanics.membranes as mm
from sfepy.linalg import dot_sequences
qp = self.get_qp('v', integral)
iels = region.get_cells(self.ig)
ps = self.interp.poly_spaces['v']
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(group.conn, nm.int32(iels), axis=0)
ccoors = coors[conn]
# Coordinate transformation matrix (transposed!).
mtx_t = mm.create_transformation_matrix(ccoors)
# Transform coordinates to the local coordinate system.
coors_loc = dot_sequences((ccoors - ccoors[:, 0:1, :]), mtx_t)
# Mapping from transformed elements to reference elements.
mapping = mm.create_mapping(coors_loc, field.gel, 1)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori)
vg.mtx_t = mtx_t
out = vg
elif (gtype == 'surface') or (gtype == 'surface_extra'):
assert_(field.approx_order > 0)
if self.ori is not None:
msg = 'surface integrals do not work yet with the' \
' hierarchical basis!'
raise ValueError(msg)
sd = domain.surface_groups[self.ig][region.name]
esd = self.surface_data[region.name]
qp = self.get_qp(sd.face_type, integral)
geo_ps = self.interp.get_geom_poly_space(sd.face_type)
ps = self.interp.poly_spaces[esd.face_type]
bf = self.get_base(esd.face_type, 0, integral)
conn = sd.get_connectivity()
mapping = | SurfaceMapping(coors, conn, poly_space=geo_ps) | sfepy.discrete.fem.mappings.SurfaceMapping |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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 Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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 Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
| output('field 1: number of local DOFs:', field1_i.n_nod) | sfepy.base.base.output |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
| output('field 2: number of local DOFs:', field2_i.n_nod) | sfepy.base.base.output |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = | FieldVariable('u_i', 'unknown', field1_i, order=0) | sfepy.discrete.FieldVariable |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = | FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i') | sfepy.discrete.FieldVariable |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = | FieldVariable('p_i', 'unknown', field2_i, order=1) | sfepy.discrete.FieldVariable |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = | FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i') | sfepy.discrete.FieldVariable |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = | Equation('eq1', t11 - t12) | sfepy.discrete.Equation |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = | Equation('eq1', t21 + t22) | sfepy.discrete.Equation |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = | Equations([eq1, eq2]) | sfepy.discrete.Equations |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = | Function('bc_fun', bc_fun) | sfepy.discrete.Function |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = | Problem('problem_i', equations=eqs, active_only=False) | sfepy.discrete.Problem |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
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 Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = | Mesh.from_file(mesh_filename) | sfepy.discrete.fem.Mesh.from_file |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
| output('creating global domain and fields...') | sfepy.base.base.output |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = | FEDomain('domain', mesh) | sfepy.discrete.fem.FEDomain |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
| output('distributing fields...') | sfepy.base.base.output |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
| output('creating local problem...') | sfepy.base.base.output |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = | Region.from_cells(cells, domain) | sfepy.discrete.common.region.Region.from_cells |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = | State(variables) | sfepy.discrete.State |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
| output('allocating global system...') | sfepy.base.base.output |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
| output('creating solver...') | sfepy.base.base.output |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
output('creating solver...')
tt = time.clock()
conf = Struct(method='bcgsl', precond='jacobi', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-6, 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 Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
output('creating solver...')
tt = time.clock()
conf = Struct(method='bcgsl', precond='jacobi', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-6, eps_d=1e4,
verbose=True)
status = {}
ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
field_ranges = {}
for ii, variable in enumerate(variables.iter_state(ordered=True)):
field_ranges[variable.name] = lfds[ii].petsc_dofs_range
ls.set_field_split(field_ranges, comm=comm)
ev = PETScParallelEvaluator(pb, pdofs, drange, True,
psol, comm, verbose=True)
nls_status = {}
conf = Struct(method='newtonls',
i_max=5, eps_a=0, eps_r=1e-5, eps_s=0.0,
verbose=True)
nls = PETScNonlinearSolver(conf, pmtx=pmtx, prhs=prhs, comm=comm,
fun=ev.eval_residual,
fun_grad=ev.eval_tangent_matrix,
lin_solver=ls, status=nls_status)
output('...done in', time.clock() - tt)
| output('solving...') | sfepy.base.base.output |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
output('creating solver...')
tt = time.clock()
conf = Struct(method='bcgsl', precond='jacobi', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-6, eps_d=1e4,
verbose=True)
status = {}
ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
field_ranges = {}
for ii, variable in enumerate(variables.iter_state(ordered=True)):
field_ranges[variable.name] = lfds[ii].petsc_dofs_range
ls.set_field_split(field_ranges, comm=comm)
ev = PETScParallelEvaluator(pb, pdofs, drange, True,
psol, comm, verbose=True)
nls_status = {}
conf = Struct(method='newtonls',
i_max=5, eps_a=0, eps_r=1e-5, eps_s=0.0,
verbose=True)
nls = PETScNonlinearSolver(conf, pmtx=pmtx, prhs=prhs, comm=comm,
fun=ev.eval_residual,
fun_grad=ev.eval_tangent_matrix,
lin_solver=ls, status=nls_status)
output('...done in', time.clock() - tt)
output('solving...')
tt = time.clock()
state = pb.create_state()
state.apply_ebc()
ev.psol_i[...] = state()
ev.gather(psol, ev.psol_i)
psol = nls(psol)
ev.scatter(ev.psol_i, psol)
sol0_i = ev.psol_i[...]
output('...done in', time.clock() - tt)
| output('saving solution...') | sfepy.base.base.output |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
output('creating solver...')
tt = time.clock()
conf = Struct(method='bcgsl', precond='jacobi', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-6, eps_d=1e4,
verbose=True)
status = {}
ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
field_ranges = {}
for ii, variable in enumerate(variables.iter_state(ordered=True)):
field_ranges[variable.name] = lfds[ii].petsc_dofs_range
ls.set_field_split(field_ranges, comm=comm)
ev = PETScParallelEvaluator(pb, pdofs, drange, True,
psol, comm, verbose=True)
nls_status = {}
conf = Struct(method='newtonls',
i_max=5, eps_a=0, eps_r=1e-5, eps_s=0.0,
verbose=True)
nls = PETScNonlinearSolver(conf, pmtx=pmtx, prhs=prhs, comm=comm,
fun=ev.eval_residual,
fun_grad=ev.eval_tangent_matrix,
lin_solver=ls, status=nls_status)
output('...done in', time.clock() - tt)
output('solving...')
tt = time.clock()
state = pb.create_state()
state.apply_ebc()
ev.psol_i[...] = state()
ev.gather(psol, ev.psol_i)
psol = nls(psol)
ev.scatter(ev.psol_i, psol)
sol0_i = ev.psol_i[...]
output('...done in', time.clock() - tt)
output('saving solution...')
tt = time.clock()
state.set_full(sol0_i)
out = state.create_output_dict()
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 Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
output('creating solver...')
tt = time.clock()
conf = Struct(method='bcgsl', precond='jacobi', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-6, eps_d=1e4,
verbose=True)
status = {}
ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
field_ranges = {}
for ii, variable in enumerate(variables.iter_state(ordered=True)):
field_ranges[variable.name] = lfds[ii].petsc_dofs_range
ls.set_field_split(field_ranges, comm=comm)
ev = PETScParallelEvaluator(pb, pdofs, drange, True,
psol, comm, verbose=True)
nls_status = {}
conf = Struct(method='newtonls',
i_max=5, eps_a=0, eps_r=1e-5, eps_s=0.0,
verbose=True)
nls = PETScNonlinearSolver(conf, pmtx=pmtx, prhs=prhs, comm=comm,
fun=ev.eval_residual,
fun_grad=ev.eval_tangent_matrix,
lin_solver=ls, status=nls_status)
output('...done in', time.clock() - tt)
output('solving...')
tt = time.clock()
state = pb.create_state()
state.apply_ebc()
ev.psol_i[...] = state()
ev.gather(psol, ev.psol_i)
psol = nls(psol)
ev.scatter(ev.psol_i, psol)
sol0_i = ev.psol_i[...]
output('...done in', time.clock() - tt)
output('saving solution...')
tt = time.clock()
state.set_full(sol0_i)
out = state.create_output_dict()
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()
u = FieldVariable('u', 'parameter', field1,
primary_var_name='(set-to-None)')
remap = gfds[0].id_map
ug = sol[remap]
p = FieldVariable('p', 'parameter', field2,
primary_var_name='(set-to-None)')
remap = gfds[1].id_map
pg = sol[remap]
if (((order_u == 1) and (order_p == 1))
or (options.linearization == 'strip')):
out = u.create_output(ug)
out.update(p.create_output(pg))
filename = os.path.join(options.output_dir, 'sol.h5')
mesh.write(filename, io='auto', out=out)
else:
out = u.create_output(ug, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_u,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_u.h5')
out['u'].mesh.write(filename, io='auto', out=out)
out = p.create_output(pg, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_p,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_p.h5')
out['p'].mesh.write(filename, io='auto', out=out)
output('...done in', time.clock() - tt)
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',
'u-order' :
'displacement field approximation order',
'p-order' :
'pressure field approximation order',
'linearization' :
'linearization used for storing the results with approximation order > 1'
' [default: %(default)s]',
'metis' :
'use metis for domain partitioning',
'save_inter_regions' :
'save inter-task regions for debugging partitioning problems',
'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('--u-order', metavar='int', type=int,
action='store', dest='order_u',
default=1, help=helps['u-order'])
parser.add_argument('--p-order', metavar='int', type=int,
action='store', dest='order_p',
default=1, help=helps['p-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('--save-inter-regions',
action='store_true', dest='save_inter_regions',
default=False, help=helps['save_inter_regions'])
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()
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 Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
output('creating solver...')
tt = time.clock()
conf = Struct(method='bcgsl', precond='jacobi', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-6, eps_d=1e4,
verbose=True)
status = {}
ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
field_ranges = {}
for ii, variable in enumerate(variables.iter_state(ordered=True)):
field_ranges[variable.name] = lfds[ii].petsc_dofs_range
ls.set_field_split(field_ranges, comm=comm)
ev = PETScParallelEvaluator(pb, pdofs, drange, True,
psol, comm, verbose=True)
nls_status = {}
conf = Struct(method='newtonls',
i_max=5, eps_a=0, eps_r=1e-5, eps_s=0.0,
verbose=True)
nls = PETScNonlinearSolver(conf, pmtx=pmtx, prhs=prhs, comm=comm,
fun=ev.eval_residual,
fun_grad=ev.eval_tangent_matrix,
lin_solver=ls, status=nls_status)
output('...done in', time.clock() - tt)
output('solving...')
tt = time.clock()
state = pb.create_state()
state.apply_ebc()
ev.psol_i[...] = state()
ev.gather(psol, ev.psol_i)
psol = nls(psol)
ev.scatter(ev.psol_i, psol)
sol0_i = ev.psol_i[...]
output('...done in', time.clock() - tt)
output('saving solution...')
tt = time.clock()
state.set_full(sol0_i)
out = state.create_output_dict()
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()
u = FieldVariable('u', 'parameter', field1,
primary_var_name='(set-to-None)')
remap = gfds[0].id_map
ug = sol[remap]
p = FieldVariable('p', 'parameter', field2,
primary_var_name='(set-to-None)')
remap = gfds[1].id_map
pg = sol[remap]
if (((order_u == 1) and (order_p == 1))
or (options.linearization == 'strip')):
out = u.create_output(ug)
out.update(p.create_output(pg))
filename = os.path.join(options.output_dir, 'sol.h5')
mesh.write(filename, io='auto', out=out)
else:
out = u.create_output(ug, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_u,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_u.h5')
out['u'].mesh.write(filename, io='auto', out=out)
out = p.create_output(pg, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_p,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_p.h5')
out['p'].mesh.write(filename, io='auto', out=out)
output('...done in', time.clock() - tt)
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',
'u-order' :
'displacement field approximation order',
'p-order' :
'pressure field approximation order',
'linearization' :
'linearization used for storing the results with approximation order > 1'
' [default: %(default)s]',
'metis' :
'use metis for domain partitioning',
'save_inter_regions' :
'save inter-task regions for debugging partitioning problems',
'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('--u-order', metavar='int', type=int,
action='store', dest='order_u',
default=1, help=helps['u-order'])
parser.add_argument('--p-order', metavar='int', type=int,
action='store', dest='order_p',
default=1, help=helps['p-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('--save-inter-regions',
action='store_true', dest='save_inter_regions',
default=False, help=helps['save_inter_regions'])
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()
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 Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
output('creating solver...')
tt = time.clock()
conf = Struct(method='bcgsl', precond='jacobi', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-6, eps_d=1e4,
verbose=True)
status = {}
ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
field_ranges = {}
for ii, variable in enumerate(variables.iter_state(ordered=True)):
field_ranges[variable.name] = lfds[ii].petsc_dofs_range
ls.set_field_split(field_ranges, comm=comm)
ev = PETScParallelEvaluator(pb, pdofs, drange, True,
psol, comm, verbose=True)
nls_status = {}
conf = Struct(method='newtonls',
i_max=5, eps_a=0, eps_r=1e-5, eps_s=0.0,
verbose=True)
nls = PETScNonlinearSolver(conf, pmtx=pmtx, prhs=prhs, comm=comm,
fun=ev.eval_residual,
fun_grad=ev.eval_tangent_matrix,
lin_solver=ls, status=nls_status)
output('...done in', time.clock() - tt)
output('solving...')
tt = time.clock()
state = pb.create_state()
state.apply_ebc()
ev.psol_i[...] = state()
ev.gather(psol, ev.psol_i)
psol = nls(psol)
ev.scatter(ev.psol_i, psol)
sol0_i = ev.psol_i[...]
output('...done in', time.clock() - tt)
output('saving solution...')
tt = time.clock()
state.set_full(sol0_i)
out = state.create_output_dict()
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()
u = FieldVariable('u', 'parameter', field1,
primary_var_name='(set-to-None)')
remap = gfds[0].id_map
ug = sol[remap]
p = FieldVariable('p', 'parameter', field2,
primary_var_name='(set-to-None)')
remap = gfds[1].id_map
pg = sol[remap]
if (((order_u == 1) and (order_p == 1))
or (options.linearization == 'strip')):
out = u.create_output(ug)
out.update(p.create_output(pg))
filename = os.path.join(options.output_dir, 'sol.h5')
mesh.write(filename, io='auto', out=out)
else:
out = u.create_output(ug, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_u,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_u.h5')
out['u'].mesh.write(filename, io='auto', out=out)
out = p.create_output(pg, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_p,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_p.h5')
out['p'].mesh.write(filename, io='auto', out=out)
output('...done in', time.clock() - tt)
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',
'u-order' :
'displacement field approximation order',
'p-order' :
'pressure field approximation order',
'linearization' :
'linearization used for storing the results with approximation order > 1'
' [default: %(default)s]',
'metis' :
'use metis for domain partitioning',
'save_inter_regions' :
'save inter-task regions for debugging partitioning problems',
'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('--u-order', metavar='int', type=int,
action='store', dest='order_u',
default=1, help=helps['u-order'])
parser.add_argument('--p-order', metavar='int', type=int,
action='store', dest='order_p',
default=1, help=helps['p-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('--save-inter-regions',
action='store_true', dest='save_inter_regions',
default=False, help=helps['save_inter_regions'])
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()
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')
if comm.rank == 0:
from sfepy.mesh.mesh_generators import gen_block_mesh
if options.clear:
remove_files_patterns(output_dir,
['*.h5', '*.mesh', '*.txt'],
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))])
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)
mesh = gen_block_mesh(dims, shape, centre, name='block-fem',
verbose=True)
mesh.write(mesh_filename, io='auto')
comm.barrier()
| output('field u order:', options.order_u) | sfepy.base.base.output |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
output('creating solver...')
tt = time.clock()
conf = Struct(method='bcgsl', precond='jacobi', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-6, eps_d=1e4,
verbose=True)
status = {}
ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
field_ranges = {}
for ii, variable in enumerate(variables.iter_state(ordered=True)):
field_ranges[variable.name] = lfds[ii].petsc_dofs_range
ls.set_field_split(field_ranges, comm=comm)
ev = PETScParallelEvaluator(pb, pdofs, drange, True,
psol, comm, verbose=True)
nls_status = {}
conf = Struct(method='newtonls',
i_max=5, eps_a=0, eps_r=1e-5, eps_s=0.0,
verbose=True)
nls = PETScNonlinearSolver(conf, pmtx=pmtx, prhs=prhs, comm=comm,
fun=ev.eval_residual,
fun_grad=ev.eval_tangent_matrix,
lin_solver=ls, status=nls_status)
output('...done in', time.clock() - tt)
output('solving...')
tt = time.clock()
state = pb.create_state()
state.apply_ebc()
ev.psol_i[...] = state()
ev.gather(psol, ev.psol_i)
psol = nls(psol)
ev.scatter(ev.psol_i, psol)
sol0_i = ev.psol_i[...]
output('...done in', time.clock() - tt)
output('saving solution...')
tt = time.clock()
state.set_full(sol0_i)
out = state.create_output_dict()
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()
u = FieldVariable('u', 'parameter', field1,
primary_var_name='(set-to-None)')
remap = gfds[0].id_map
ug = sol[remap]
p = FieldVariable('p', 'parameter', field2,
primary_var_name='(set-to-None)')
remap = gfds[1].id_map
pg = sol[remap]
if (((order_u == 1) and (order_p == 1))
or (options.linearization == 'strip')):
out = u.create_output(ug)
out.update(p.create_output(pg))
filename = os.path.join(options.output_dir, 'sol.h5')
mesh.write(filename, io='auto', out=out)
else:
out = u.create_output(ug, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_u,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_u.h5')
out['u'].mesh.write(filename, io='auto', out=out)
out = p.create_output(pg, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_p,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_p.h5')
out['p'].mesh.write(filename, io='auto', out=out)
output('...done in', time.clock() - tt)
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',
'u-order' :
'displacement field approximation order',
'p-order' :
'pressure field approximation order',
'linearization' :
'linearization used for storing the results with approximation order > 1'
' [default: %(default)s]',
'metis' :
'use metis for domain partitioning',
'save_inter_regions' :
'save inter-task regions for debugging partitioning problems',
'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('--u-order', metavar='int', type=int,
action='store', dest='order_u',
default=1, help=helps['u-order'])
parser.add_argument('--p-order', metavar='int', type=int,
action='store', dest='order_p',
default=1, help=helps['p-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('--save-inter-regions',
action='store_true', dest='save_inter_regions',
default=False, help=helps['save_inter_regions'])
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()
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')
if comm.rank == 0:
from sfepy.mesh.mesh_generators import gen_block_mesh
if options.clear:
remove_files_patterns(output_dir,
['*.h5', '*.mesh', '*.txt'],
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))])
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)
mesh = gen_block_mesh(dims, shape, centre, name='block-fem',
verbose=True)
mesh.write(mesh_filename, io='auto')
comm.barrier()
output('field u order:', options.order_u)
| output('field p order:', options.order_p) | sfepy.base.base.output |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
output('creating solver...')
tt = time.clock()
conf = Struct(method='bcgsl', precond='jacobi', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-6, eps_d=1e4,
verbose=True)
status = {}
ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
field_ranges = {}
for ii, variable in enumerate(variables.iter_state(ordered=True)):
field_ranges[variable.name] = lfds[ii].petsc_dofs_range
ls.set_field_split(field_ranges, comm=comm)
ev = PETScParallelEvaluator(pb, pdofs, drange, True,
psol, comm, verbose=True)
nls_status = {}
conf = Struct(method='newtonls',
i_max=5, eps_a=0, eps_r=1e-5, eps_s=0.0,
verbose=True)
nls = PETScNonlinearSolver(conf, pmtx=pmtx, prhs=prhs, comm=comm,
fun=ev.eval_residual,
fun_grad=ev.eval_tangent_matrix,
lin_solver=ls, status=nls_status)
output('...done in', time.clock() - tt)
output('solving...')
tt = time.clock()
state = pb.create_state()
state.apply_ebc()
ev.psol_i[...] = state()
ev.gather(psol, ev.psol_i)
psol = nls(psol)
ev.scatter(ev.psol_i, psol)
sol0_i = ev.psol_i[...]
output('...done in', time.clock() - tt)
output('saving solution...')
tt = time.clock()
state.set_full(sol0_i)
out = state.create_output_dict()
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()
u = FieldVariable('u', 'parameter', field1,
primary_var_name='(set-to-None)')
remap = gfds[0].id_map
ug = sol[remap]
p = FieldVariable('p', 'parameter', field2,
primary_var_name='(set-to-None)')
remap = gfds[1].id_map
pg = sol[remap]
if (((order_u == 1) and (order_p == 1))
or (options.linearization == 'strip')):
out = u.create_output(ug)
out.update(p.create_output(pg))
filename = os.path.join(options.output_dir, 'sol.h5')
mesh.write(filename, io='auto', out=out)
else:
out = u.create_output(ug, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_u,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_u.h5')
out['u'].mesh.write(filename, io='auto', out=out)
out = p.create_output(pg, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_p,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_p.h5')
out['p'].mesh.write(filename, io='auto', out=out)
output('...done in', time.clock() - tt)
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',
'u-order' :
'displacement field approximation order',
'p-order' :
'pressure field approximation order',
'linearization' :
'linearization used for storing the results with approximation order > 1'
' [default: %(default)s]',
'metis' :
'use metis for domain partitioning',
'save_inter_regions' :
'save inter-task regions for debugging partitioning problems',
'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('--u-order', metavar='int', type=int,
action='store', dest='order_u',
default=1, help=helps['u-order'])
parser.add_argument('--p-order', metavar='int', type=int,
action='store', dest='order_p',
default=1, help=helps['p-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('--save-inter-regions',
action='store_true', dest='save_inter_regions',
default=False, help=helps['save_inter_regions'])
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()
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 Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
output('creating solver...')
tt = time.clock()
conf = Struct(method='bcgsl', precond='jacobi', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-6, eps_d=1e4,
verbose=True)
status = {}
ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
field_ranges = {}
for ii, variable in enumerate(variables.iter_state(ordered=True)):
field_ranges[variable.name] = lfds[ii].petsc_dofs_range
ls.set_field_split(field_ranges, comm=comm)
ev = PETScParallelEvaluator(pb, pdofs, drange, True,
psol, comm, verbose=True)
nls_status = {}
conf = Struct(method='newtonls',
i_max=5, eps_a=0, eps_r=1e-5, eps_s=0.0,
verbose=True)
nls = PETScNonlinearSolver(conf, pmtx=pmtx, prhs=prhs, comm=comm,
fun=ev.eval_residual,
fun_grad=ev.eval_tangent_matrix,
lin_solver=ls, status=nls_status)
output('...done in', time.clock() - tt)
output('solving...')
tt = time.clock()
state = pb.create_state()
state.apply_ebc()
ev.psol_i[...] = state()
ev.gather(psol, ev.psol_i)
psol = nls(psol)
ev.scatter(ev.psol_i, psol)
sol0_i = ev.psol_i[...]
output('...done in', time.clock() - tt)
output('saving solution...')
tt = time.clock()
state.set_full(sol0_i)
out = state.create_output_dict()
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()
u = FieldVariable('u', 'parameter', field1,
primary_var_name='(set-to-None)')
remap = gfds[0].id_map
ug = sol[remap]
p = FieldVariable('p', 'parameter', field2,
primary_var_name='(set-to-None)')
remap = gfds[1].id_map
pg = sol[remap]
if (((order_u == 1) and (order_p == 1))
or (options.linearization == 'strip')):
out = u.create_output(ug)
out.update(p.create_output(pg))
filename = os.path.join(options.output_dir, 'sol.h5')
mesh.write(filename, io='auto', out=out)
else:
out = u.create_output(ug, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_u,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_u.h5')
out['u'].mesh.write(filename, io='auto', out=out)
out = p.create_output(pg, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_p,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_p.h5')
out['p'].mesh.write(filename, io='auto', out=out)
output('...done in', time.clock() - tt)
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',
'u-order' :
'displacement field approximation order',
'p-order' :
'pressure field approximation order',
'linearization' :
'linearization used for storing the results with approximation order > 1'
' [default: %(default)s]',
'metis' :
'use metis for domain partitioning',
'save_inter_regions' :
'save inter-task regions for debugging partitioning problems',
'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('--u-order', metavar='int', type=int,
action='store', dest='order_u',
default=1, help=helps['u-order'])
parser.add_argument('--p-order', metavar='int', type=int,
action='store', dest='order_p',
default=1, help=helps['p-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('--save-inter-regions',
action='store_true', dest='save_inter_regions',
default=False, help=helps['save_inter_regions'])
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()
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')
if comm.rank == 0:
from sfepy.mesh.mesh_generators import gen_block_mesh
if options.clear:
remove_files_patterns(output_dir,
['*.h5', '*.mesh', '*.txt'],
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))])
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 Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
output('creating solver...')
tt = time.clock()
conf = Struct(method='bcgsl', precond='jacobi', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-6, eps_d=1e4,
verbose=True)
status = {}
ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
field_ranges = {}
for ii, variable in enumerate(variables.iter_state(ordered=True)):
field_ranges[variable.name] = lfds[ii].petsc_dofs_range
ls.set_field_split(field_ranges, comm=comm)
ev = PETScParallelEvaluator(pb, pdofs, drange, True,
psol, comm, verbose=True)
nls_status = {}
conf = Struct(method='newtonls',
i_max=5, eps_a=0, eps_r=1e-5, eps_s=0.0,
verbose=True)
nls = PETScNonlinearSolver(conf, pmtx=pmtx, prhs=prhs, comm=comm,
fun=ev.eval_residual,
fun_grad=ev.eval_tangent_matrix,
lin_solver=ls, status=nls_status)
output('...done in', time.clock() - tt)
output('solving...')
tt = time.clock()
state = pb.create_state()
state.apply_ebc()
ev.psol_i[...] = state()
ev.gather(psol, ev.psol_i)
psol = nls(psol)
ev.scatter(ev.psol_i, psol)
sol0_i = ev.psol_i[...]
output('...done in', time.clock() - tt)
output('saving solution...')
tt = time.clock()
state.set_full(sol0_i)
out = state.create_output_dict()
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()
u = FieldVariable('u', 'parameter', field1,
primary_var_name='(set-to-None)')
remap = gfds[0].id_map
ug = sol[remap]
p = FieldVariable('p', 'parameter', field2,
primary_var_name='(set-to-None)')
remap = gfds[1].id_map
pg = sol[remap]
if (((order_u == 1) and (order_p == 1))
or (options.linearization == 'strip')):
out = u.create_output(ug)
out.update(p.create_output(pg))
filename = os.path.join(options.output_dir, 'sol.h5')
mesh.write(filename, io='auto', out=out)
else:
out = u.create_output(ug, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_u,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_u.h5')
out['u'].mesh.write(filename, io='auto', out=out)
out = p.create_output(pg, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_p,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_p.h5')
out['p'].mesh.write(filename, io='auto', out=out)
output('...done in', time.clock() - tt)
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',
'u-order' :
'displacement field approximation order',
'p-order' :
'pressure field approximation order',
'linearization' :
'linearization used for storing the results with approximation order > 1'
' [default: %(default)s]',
'metis' :
'use metis for domain partitioning',
'save_inter_regions' :
'save inter-task regions for debugging partitioning problems',
'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('--u-order', metavar='int', type=int,
action='store', dest='order_u',
default=1, help=helps['u-order'])
parser.add_argument('--p-order', metavar='int', type=int,
action='store', dest='order_p',
default=1, help=helps['p-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('--save-inter-regions',
action='store_true', dest='save_inter_regions',
default=False, help=helps['save_inter_regions'])
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()
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')
if comm.rank == 0:
from sfepy.mesh.mesh_generators import gen_block_mesh
if options.clear:
remove_files_patterns(output_dir,
['*.h5', '*.mesh', '*.txt'],
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))])
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 Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2, ebc3]))
pb.update_materials()
return pb
def solve_problem(mesh_filename, options, comm):
order_u = options.order_u
order_p = options.order_p
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
mesh = Mesh.from_file(mesh_filename)
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
output('creating global domain and fields...')
tt = time.clock()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field1 = Field.from_args('fu', nm.float64, mesh.dim, omega,
approx_order=order_u)
field2 = Field.from_args('fp', nm.float64, 1, omega,
approx_order=order_p)
fields = [field1, field2]
output('...done in', time.clock() - tt)
output('distributing fields...')
tt = time.clock()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute(fields, cell_tasks,
is_overlap=True,
use_expand_dofs=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
output('...done in', time.clock() - tt)
output('creating local problem...')
tt = time.clock()
cells = lfds[0].cells
omega_gi = Region.from_cells(cells, domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, [order_u, order_p])
variables = pb.get_variables()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
output('...done in', time.clock() - tt)
output('allocating global system...')
tt = time.clock()
sizes, drange, pdofs = pl.setup_composite_dofs(lfds, fields, variables,
verbose=True)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
output('...done in', time.clock() - tt)
output('creating solver...')
tt = time.clock()
conf = Struct(method='bcgsl', precond='jacobi', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-6, eps_d=1e4,
verbose=True)
status = {}
ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
field_ranges = {}
for ii, variable in enumerate(variables.iter_state(ordered=True)):
field_ranges[variable.name] = lfds[ii].petsc_dofs_range
ls.set_field_split(field_ranges, comm=comm)
ev = PETScParallelEvaluator(pb, pdofs, drange, True,
psol, comm, verbose=True)
nls_status = {}
conf = Struct(method='newtonls',
i_max=5, eps_a=0, eps_r=1e-5, eps_s=0.0,
verbose=True)
nls = PETScNonlinearSolver(conf, pmtx=pmtx, prhs=prhs, comm=comm,
fun=ev.eval_residual,
fun_grad=ev.eval_tangent_matrix,
lin_solver=ls, status=nls_status)
output('...done in', time.clock() - tt)
output('solving...')
tt = time.clock()
state = pb.create_state()
state.apply_ebc()
ev.psol_i[...] = state()
ev.gather(psol, ev.psol_i)
psol = nls(psol)
ev.scatter(ev.psol_i, psol)
sol0_i = ev.psol_i[...]
output('...done in', time.clock() - tt)
output('saving solution...')
tt = time.clock()
state.set_full(sol0_i)
out = state.create_output_dict()
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()
u = FieldVariable('u', 'parameter', field1,
primary_var_name='(set-to-None)')
remap = gfds[0].id_map
ug = sol[remap]
p = FieldVariable('p', 'parameter', field2,
primary_var_name='(set-to-None)')
remap = gfds[1].id_map
pg = sol[remap]
if (((order_u == 1) and (order_p == 1))
or (options.linearization == 'strip')):
out = u.create_output(ug)
out.update(p.create_output(pg))
filename = os.path.join(options.output_dir, 'sol.h5')
mesh.write(filename, io='auto', out=out)
else:
out = u.create_output(ug, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_u,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_u.h5')
out['u'].mesh.write(filename, io='auto', out=out)
out = p.create_output(pg, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order_p,
eps=1e-3))
filename = os.path.join(options.output_dir, 'sol_p.h5')
out['p'].mesh.write(filename, io='auto', out=out)
output('...done in', time.clock() - tt)
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',
'u-order' :
'displacement field approximation order',
'p-order' :
'pressure field approximation order',
'linearization' :
'linearization used for storing the results with approximation order > 1'
' [default: %(default)s]',
'metis' :
'use metis for domain partitioning',
'save_inter_regions' :
'save inter-task regions for debugging partitioning problems',
'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('--u-order', metavar='int', type=int,
action='store', dest='order_u',
default=1, help=helps['u-order'])
parser.add_argument('--p-order', metavar='int', type=int,
action='store', dest='order_p',
default=1, help=helps['p-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('--save-inter-regions',
action='store_true', dest='save_inter_regions',
default=False, help=helps['save_inter_regions'])
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()
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')
if comm.rank == 0:
from sfepy.mesh.mesh_generators import gen_block_mesh
if options.clear:
remove_files_patterns(output_dir,
['*.h5', '*.mesh', '*.txt'],
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))])
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 Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D= | stiffness_from_lame(mesh.dim, lam=10, mu=5) | sfepy.mechanics.matcoefs.stiffness_from_lame |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Biot problem (deformable porous medium),
using commands for interactive use.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} q\ \alpha_{ij} e_{ij}(\ul{u})
+ \int_{\Omega} K_{ij} \nabla_i q \nabla_j p
= 0
\;, \quad \forall q \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
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 shows how to use a nonlinear solver from PETSc.
- This example can serve as a template for solving a (non)linear multi-field
problem - just replace the equations in :func:`create_local_problem()`.
- The material parameter :math:`\alpha_{ij}` is artificially high to be able to
see the pressure influence on displacements.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/multi_physics/biot_parallel_interactive.py -h
See PETSc options::
$ python examples/multi_physics/biot_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/multi_physics/biot_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel -2 --shape 101,101 --metis -snes_monitor -snes_view -snes_converged_reason -ksp_monitor
Using FieldSplit preconditioner::
$ mpiexec -n 2 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=101,101 -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit
$ mpiexec -n 8 python examples/multi_physics/biot_parallel_interactive.py output-parallel --shape=1001,1001 --metis -snes_monitor -snes_converged_reason -ksp_monitor -pc_type fieldsplit -pc_fieldsplit_type additive
View the results using (strip linearization or approximation orders one)::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'p,plot_warp_scalar:u,plot_displacements'
View the results using (adaptive linearization)::
$ python postproc.py output-parallel/sol_u.h5 --wireframe -b -d'u,plot_displacements'
$ python postproc.py output-parallel/sol_p.h5 --wireframe -b -d'p,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import time
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
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.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
from sfepy.solvers.nls import PETScNonlinearSolver
from sfepy.mechanics.matcoefs import stiffness_from_lame
import sfepy.parallel.parallel as pl
from sfepy.parallel.evaluate import PETScParallelEvaluator
def create_local_problem(omega_gi, orders):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
order_u, order_p = orders
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)
min_y, max_y = bbox[:, 1]
eps_y = 1e-8 * (max_y - min_y)
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)
gamma3_i = domain_i.create_region('Gamma3',
'vertices in (y < %.10f)'
% (min_y + eps_y),
'facet', allow_empty=True)
field1_i = Field.from_args('fu', nm.float64, mesh.dim, omega_i,
approx_order=order_u)
field2_i = Field.from_args('fp', nm.float64, 1, omega_i,
approx_order=order_p)
output('field 1: number of local DOFs:', field1_i.n_nod)
output('field 2: number of local DOFs:', field2_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field1_i, order=0)
v_i = FieldVariable('v_i', 'test', field1_i, primary_var_name='u_i')
p_i = FieldVariable('p_i', 'unknown', field2_i, order=1)
q_i = FieldVariable('q_i', 'test', field2_i, primary_var_name='p_i')
if mesh.dim == 2:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.092]])
else:
alpha = 1e2 * nm.array([[0.132], [0.132], [0.132],
[0.092], [0.092], [0.092]])
mat = Material('m', D=stiffness_from_lame(mesh.dim, lam=10, mu=5),
k=1, alpha=alpha)
integral = Integral('i', order=2*(max(order_u, order_p)))
t11 = Term.new('dw_lin_elastic(m.D, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
t12 = Term.new('dw_biot(m.alpha, v_i, p_i)',
integral, omega_i, m=mat, v_i=v_i, p_i=p_i)
t21 = Term.new('dw_biot(m.alpha, u_i, q_i)',
integral, omega_i, m=mat, u_i=u_i, q_i=q_i)
t22 = Term.new('dw_laplace(m.k, q_i, p_i)',
integral, omega_i, m=mat, q_i=q_i, p_i=p_i)
eq1 = Equation('eq1', t11 - t12)
eq2 = Equation('eq1', t21 + t22)
eqs = Equations([eq1, eq2])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.0' : 0.05})
def bc_fun(ts, coors, **kwargs):
val = 0.3 * nm.sin(4 * nm.pi * (coors[:, 0] - min_x) / (max_x - min_x))
return val
fun = Function('bc_fun', bc_fun)
ebc3 = EssentialBC('ebc3', gamma3_i, {'p_i.all' : fun})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs= | Conditions([ebc1, ebc2, ebc3]) | sfepy.discrete.conditions.Conditions |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = | tn.get_sym_indices(3) | sfepy.mechanics.tensors.get_sym_indices |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = | tn.get_trace(a_full, sym_storage=False) | sfepy.mechanics.tensors.get_trace |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = | tn.get_trace(a_sym, sym_storage=True) | sfepy.mechanics.tensors.get_trace |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = | tn.get_volumetric_tensor(a_full, sym_storage=False) | sfepy.mechanics.tensors.get_volumetric_tensor |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = | tn.get_volumetric_tensor(a_sym, sym_storage=True) | sfepy.mechanics.tensors.get_volumetric_tensor |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = | tn.get_deviator(a_full, sym_storage=False) | sfepy.mechanics.tensors.get_deviator |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = | tn.get_deviator(a_sym, sym_storage=True) | sfepy.mechanics.tensors.get_deviator |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = tn.get_deviator(a_sym, sym_storage=True)
_ok = nm.allclose(dev, _dev_sym, rtol=0.0, atol=1e-14)
self.report('deviator sym: %s' % _ok)
ok = ok and _ok
vms = | tn.get_von_mises_stress(a_full, sym_storage=False) | sfepy.mechanics.tensors.get_von_mises_stress |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = tn.get_deviator(a_sym, sym_storage=True)
_ok = nm.allclose(dev, _dev_sym, rtol=0.0, atol=1e-14)
self.report('deviator sym: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_full, sym_storage=False)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress full: %s' % _ok)
ok = ok and _ok
vms = | tn.get_von_mises_stress(a_sym, sym_storage=True) | sfepy.mechanics.tensors.get_von_mises_stress |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = tn.get_deviator(a_sym, sym_storage=True)
_ok = nm.allclose(dev, _dev_sym, rtol=0.0, atol=1e-14)
self.report('deviator sym: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_full, sym_storage=False)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress full: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_sym, sym_storage=True)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress sym: %s' % _ok)
ok = ok and _ok
_ok = nm.allclose(vms2, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress via deviator: %s' % _ok)
ok = ok and _ok
t2s = nm.arange(9).reshape(3, 3)
t2s = (t2s + t2s.T) / 2
t4 = | tn.get_t4_from_t2s(t2s) | sfepy.mechanics.tensors.get_t4_from_t2s |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = tn.get_deviator(a_sym, sym_storage=True)
_ok = nm.allclose(dev, _dev_sym, rtol=0.0, atol=1e-14)
self.report('deviator sym: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_full, sym_storage=False)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress full: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_sym, sym_storage=True)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress sym: %s' % _ok)
ok = ok and _ok
_ok = nm.allclose(vms2, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress via deviator: %s' % _ok)
ok = ok and _ok
t2s = nm.arange(9).reshape(3, 3)
t2s = (t2s + t2s.T) / 2
t4 = tn.get_t4_from_t2s(t2s)
expected = nm.array([[[[0, 4], [4, 2]],
[[4, 8], [8, 6]]],
[[[4, 8], [8, 6]],
[[2, 6], [6, 4]]]])
_ok = nm.allclose(t4, expected, rtol=0.0, atol=1e-14)
self.report('full 4D tensor from 2D matrix, 2D space: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data(self):
import numpy as nm
from sfepy.mechanics.tensors import transform_data
ok = True
coors = nm.eye(3)
data = nm.eye(3)
expected = nm.zeros((3, 3))
expected[[0, 1, 2], [0, 0, 2]] = 1.0
out = | transform_data(data, coors) | sfepy.mechanics.tensors.transform_data |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = tn.get_deviator(a_sym, sym_storage=True)
_ok = nm.allclose(dev, _dev_sym, rtol=0.0, atol=1e-14)
self.report('deviator sym: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_full, sym_storage=False)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress full: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_sym, sym_storage=True)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress sym: %s' % _ok)
ok = ok and _ok
_ok = nm.allclose(vms2, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress via deviator: %s' % _ok)
ok = ok and _ok
t2s = nm.arange(9).reshape(3, 3)
t2s = (t2s + t2s.T) / 2
t4 = tn.get_t4_from_t2s(t2s)
expected = nm.array([[[[0, 4], [4, 2]],
[[4, 8], [8, 6]]],
[[[4, 8], [8, 6]],
[[2, 6], [6, 4]]]])
_ok = nm.allclose(t4, expected, rtol=0.0, atol=1e-14)
self.report('full 4D tensor from 2D matrix, 2D space: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data(self):
import numpy as nm
from sfepy.mechanics.tensors import transform_data
ok = True
coors = nm.eye(3)
data = nm.eye(3)
expected = nm.zeros((3, 3))
expected[[0, 1, 2], [0, 0, 2]] = 1.0
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('vectors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
data = nm.zeros((3, 6))
data[:, :3] = [[1, 2, 3]]
expected = data.copy()
expected[1, [0, 1]] = expected[1, [1, 0]]
out = | transform_data(data, coors) | sfepy.mechanics.tensors.transform_data |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = tn.get_deviator(a_sym, sym_storage=True)
_ok = nm.allclose(dev, _dev_sym, rtol=0.0, atol=1e-14)
self.report('deviator sym: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_full, sym_storage=False)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress full: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_sym, sym_storage=True)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress sym: %s' % _ok)
ok = ok and _ok
_ok = nm.allclose(vms2, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress via deviator: %s' % _ok)
ok = ok and _ok
t2s = nm.arange(9).reshape(3, 3)
t2s = (t2s + t2s.T) / 2
t4 = tn.get_t4_from_t2s(t2s)
expected = nm.array([[[[0, 4], [4, 2]],
[[4, 8], [8, 6]]],
[[[4, 8], [8, 6]],
[[2, 6], [6, 4]]]])
_ok = nm.allclose(t4, expected, rtol=0.0, atol=1e-14)
self.report('full 4D tensor from 2D matrix, 2D space: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data(self):
import numpy as nm
from sfepy.mechanics.tensors import transform_data
ok = True
coors = nm.eye(3)
data = nm.eye(3)
expected = nm.zeros((3, 3))
expected[[0, 1, 2], [0, 0, 2]] = 1.0
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('vectors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
data = nm.zeros((3, 6))
data[:, :3] = [[1, 2, 3]]
expected = data.copy()
expected[1, [0, 1]] = expected[1, [1, 0]]
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('sym. tensors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data4(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
if not hasattr(nm, 'einsum'):
self.report('no numpy.einsum(), skipping!')
return ok
expected = nm.zeros((6, 6), dtype=nm.float64)
expected[0, 0] = expected[1, 1] = 1.0
phi = nm.deg2rad(30.)
dr, v1, v2, om1, om2 = get_ortho_d(phi, phi + nm.deg2rad(90.))
# Rotate coordinate system by phi.
mtx = | tn.make_axis_rotation_matrix([0., 0., 1.], phi) | sfepy.mechanics.tensors.make_axis_rotation_matrix |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = tn.get_deviator(a_sym, sym_storage=True)
_ok = nm.allclose(dev, _dev_sym, rtol=0.0, atol=1e-14)
self.report('deviator sym: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_full, sym_storage=False)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress full: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_sym, sym_storage=True)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress sym: %s' % _ok)
ok = ok and _ok
_ok = nm.allclose(vms2, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress via deviator: %s' % _ok)
ok = ok and _ok
t2s = nm.arange(9).reshape(3, 3)
t2s = (t2s + t2s.T) / 2
t4 = tn.get_t4_from_t2s(t2s)
expected = nm.array([[[[0, 4], [4, 2]],
[[4, 8], [8, 6]]],
[[[4, 8], [8, 6]],
[[2, 6], [6, 4]]]])
_ok = nm.allclose(t4, expected, rtol=0.0, atol=1e-14)
self.report('full 4D tensor from 2D matrix, 2D space: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data(self):
import numpy as nm
from sfepy.mechanics.tensors import transform_data
ok = True
coors = nm.eye(3)
data = nm.eye(3)
expected = nm.zeros((3, 3))
expected[[0, 1, 2], [0, 0, 2]] = 1.0
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('vectors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
data = nm.zeros((3, 6))
data[:, :3] = [[1, 2, 3]]
expected = data.copy()
expected[1, [0, 1]] = expected[1, [1, 0]]
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('sym. tensors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data4(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
if not hasattr(nm, 'einsum'):
self.report('no numpy.einsum(), skipping!')
return ok
expected = nm.zeros((6, 6), dtype=nm.float64)
expected[0, 0] = expected[1, 1] = 1.0
phi = nm.deg2rad(30.)
dr, v1, v2, om1, om2 = get_ortho_d(phi, phi + nm.deg2rad(90.))
# Rotate coordinate system by phi.
mtx = tn.make_axis_rotation_matrix([0., 0., 1.], phi)
do = | tn.transform_data(dr[None, ...], mtx=mtx[None, ...]) | sfepy.mechanics.tensors.transform_data |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = tn.get_deviator(a_sym, sym_storage=True)
_ok = nm.allclose(dev, _dev_sym, rtol=0.0, atol=1e-14)
self.report('deviator sym: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_full, sym_storage=False)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress full: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_sym, sym_storage=True)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress sym: %s' % _ok)
ok = ok and _ok
_ok = nm.allclose(vms2, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress via deviator: %s' % _ok)
ok = ok and _ok
t2s = nm.arange(9).reshape(3, 3)
t2s = (t2s + t2s.T) / 2
t4 = tn.get_t4_from_t2s(t2s)
expected = nm.array([[[[0, 4], [4, 2]],
[[4, 8], [8, 6]]],
[[[4, 8], [8, 6]],
[[2, 6], [6, 4]]]])
_ok = nm.allclose(t4, expected, rtol=0.0, atol=1e-14)
self.report('full 4D tensor from 2D matrix, 2D space: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data(self):
import numpy as nm
from sfepy.mechanics.tensors import transform_data
ok = True
coors = nm.eye(3)
data = nm.eye(3)
expected = nm.zeros((3, 3))
expected[[0, 1, 2], [0, 0, 2]] = 1.0
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('vectors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
data = nm.zeros((3, 6))
data[:, :3] = [[1, 2, 3]]
expected = data.copy()
expected[1, [0, 1]] = expected[1, [1, 0]]
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('sym. tensors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data4(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
if not hasattr(nm, 'einsum'):
self.report('no numpy.einsum(), skipping!')
return ok
expected = nm.zeros((6, 6), dtype=nm.float64)
expected[0, 0] = expected[1, 1] = 1.0
phi = nm.deg2rad(30.)
dr, v1, v2, om1, om2 = get_ortho_d(phi, phi + nm.deg2rad(90.))
# Rotate coordinate system by phi.
mtx = tn.make_axis_rotation_matrix([0., 0., 1.], phi)
do = tn.transform_data(dr[None, ...], mtx=mtx[None, ...])
_ok = nm.allclose(do, expected, rtol=0.0, atol=1e-14)
self.report('sym. 4th-th order tensor rotation: %s' % _ok)
ok = ok and _ok
dt, vt1, vt2, omt1, omt2 = get_ortho_d(0, nm.deg2rad(90.))
expected1 = nm.zeros((3, 3), dtype=nm.float64)
expected1[0, 0] = 1.0
expected2 = nm.zeros((3, 3), dtype=nm.float64)
expected2[1, 1] = 1.0
omr1 = nm.einsum('pq,ip,jq->ij', om1, mtx, mtx)
omr2 = nm.einsum('pq,ip,jq->ij', om2, mtx, mtx)
ii = | tn.get_sym_indices(3) | sfepy.mechanics.tensors.get_sym_indices |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = tn.get_deviator(a_sym, sym_storage=True)
_ok = nm.allclose(dev, _dev_sym, rtol=0.0, atol=1e-14)
self.report('deviator sym: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_full, sym_storage=False)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress full: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_sym, sym_storage=True)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress sym: %s' % _ok)
ok = ok and _ok
_ok = nm.allclose(vms2, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress via deviator: %s' % _ok)
ok = ok and _ok
t2s = nm.arange(9).reshape(3, 3)
t2s = (t2s + t2s.T) / 2
t4 = tn.get_t4_from_t2s(t2s)
expected = nm.array([[[[0, 4], [4, 2]],
[[4, 8], [8, 6]]],
[[[4, 8], [8, 6]],
[[2, 6], [6, 4]]]])
_ok = nm.allclose(t4, expected, rtol=0.0, atol=1e-14)
self.report('full 4D tensor from 2D matrix, 2D space: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data(self):
import numpy as nm
from sfepy.mechanics.tensors import transform_data
ok = True
coors = nm.eye(3)
data = nm.eye(3)
expected = nm.zeros((3, 3))
expected[[0, 1, 2], [0, 0, 2]] = 1.0
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('vectors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
data = nm.zeros((3, 6))
data[:, :3] = [[1, 2, 3]]
expected = data.copy()
expected[1, [0, 1]] = expected[1, [1, 0]]
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('sym. tensors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data4(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
if not hasattr(nm, 'einsum'):
self.report('no numpy.einsum(), skipping!')
return ok
expected = nm.zeros((6, 6), dtype=nm.float64)
expected[0, 0] = expected[1, 1] = 1.0
phi = nm.deg2rad(30.)
dr, v1, v2, om1, om2 = get_ortho_d(phi, phi + nm.deg2rad(90.))
# Rotate coordinate system by phi.
mtx = tn.make_axis_rotation_matrix([0., 0., 1.], phi)
do = tn.transform_data(dr[None, ...], mtx=mtx[None, ...])
_ok = nm.allclose(do, expected, rtol=0.0, atol=1e-14)
self.report('sym. 4th-th order tensor rotation: %s' % _ok)
ok = ok and _ok
dt, vt1, vt2, omt1, omt2 = get_ortho_d(0, nm.deg2rad(90.))
expected1 = nm.zeros((3, 3), dtype=nm.float64)
expected1[0, 0] = 1.0
expected2 = nm.zeros((3, 3), dtype=nm.float64)
expected2[1, 1] = 1.0
omr1 = nm.einsum('pq,ip,jq->ij', om1, mtx, mtx)
omr2 = nm.einsum('pq,ip,jq->ij', om2, mtx, mtx)
ii = tn.get_sym_indices(3)
jj = | tn.get_full_indices(3) | sfepy.mechanics.tensors.get_full_indices |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = tn.get_deviator(a_sym, sym_storage=True)
_ok = nm.allclose(dev, _dev_sym, rtol=0.0, atol=1e-14)
self.report('deviator sym: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_full, sym_storage=False)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress full: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_sym, sym_storage=True)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress sym: %s' % _ok)
ok = ok and _ok
_ok = nm.allclose(vms2, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress via deviator: %s' % _ok)
ok = ok and _ok
t2s = nm.arange(9).reshape(3, 3)
t2s = (t2s + t2s.T) / 2
t4 = tn.get_t4_from_t2s(t2s)
expected = nm.array([[[[0, 4], [4, 2]],
[[4, 8], [8, 6]]],
[[[4, 8], [8, 6]],
[[2, 6], [6, 4]]]])
_ok = nm.allclose(t4, expected, rtol=0.0, atol=1e-14)
self.report('full 4D tensor from 2D matrix, 2D space: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data(self):
import numpy as nm
from sfepy.mechanics.tensors import transform_data
ok = True
coors = nm.eye(3)
data = nm.eye(3)
expected = nm.zeros((3, 3))
expected[[0, 1, 2], [0, 0, 2]] = 1.0
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('vectors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
data = nm.zeros((3, 6))
data[:, :3] = [[1, 2, 3]]
expected = data.copy()
expected[1, [0, 1]] = expected[1, [1, 0]]
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('sym. tensors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data4(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
if not hasattr(nm, 'einsum'):
self.report('no numpy.einsum(), skipping!')
return ok
expected = nm.zeros((6, 6), dtype=nm.float64)
expected[0, 0] = expected[1, 1] = 1.0
phi = nm.deg2rad(30.)
dr, v1, v2, om1, om2 = get_ortho_d(phi, phi + nm.deg2rad(90.))
# Rotate coordinate system by phi.
mtx = tn.make_axis_rotation_matrix([0., 0., 1.], phi)
do = tn.transform_data(dr[None, ...], mtx=mtx[None, ...])
_ok = nm.allclose(do, expected, rtol=0.0, atol=1e-14)
self.report('sym. 4th-th order tensor rotation: %s' % _ok)
ok = ok and _ok
dt, vt1, vt2, omt1, omt2 = get_ortho_d(0, nm.deg2rad(90.))
expected1 = nm.zeros((3, 3), dtype=nm.float64)
expected1[0, 0] = 1.0
expected2 = nm.zeros((3, 3), dtype=nm.float64)
expected2[1, 1] = 1.0
omr1 = nm.einsum('pq,ip,jq->ij', om1, mtx, mtx)
omr2 = nm.einsum('pq,ip,jq->ij', om2, mtx, mtx)
ii = tn.get_sym_indices(3)
jj = tn.get_full_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
omr12 = | tn.transform_data(o1[None,...], mtx=mtx[None, ...]) | sfepy.mechanics.tensors.transform_data |
from __future__ import absolute_import
from sfepy.base.testing import TestCommon
def get_ortho_d(phi1, phi2):
import numpy as nm
import sfepy.mechanics.tensors as tn
v1 = nm.array([nm.cos(phi1), nm.sin(phi1), 0])
v2 = nm.array([nm.cos(phi2), nm.sin(phi2), 0])
om1 = nm.outer(v1, v1)
om2 = nm.outer(v2, v2)
ii = tn.get_sym_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
dr = nm.outer(o1, o1) + nm.outer(o2, o2)
return dr, v1, v2, om1, om2
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = tn.get_deviator(a_sym, sym_storage=True)
_ok = nm.allclose(dev, _dev_sym, rtol=0.0, atol=1e-14)
self.report('deviator sym: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_full, sym_storage=False)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress full: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_sym, sym_storage=True)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress sym: %s' % _ok)
ok = ok and _ok
_ok = nm.allclose(vms2, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress via deviator: %s' % _ok)
ok = ok and _ok
t2s = nm.arange(9).reshape(3, 3)
t2s = (t2s + t2s.T) / 2
t4 = tn.get_t4_from_t2s(t2s)
expected = nm.array([[[[0, 4], [4, 2]],
[[4, 8], [8, 6]]],
[[[4, 8], [8, 6]],
[[2, 6], [6, 4]]]])
_ok = nm.allclose(t4, expected, rtol=0.0, atol=1e-14)
self.report('full 4D tensor from 2D matrix, 2D space: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data(self):
import numpy as nm
from sfepy.mechanics.tensors import transform_data
ok = True
coors = nm.eye(3)
data = nm.eye(3)
expected = nm.zeros((3, 3))
expected[[0, 1, 2], [0, 0, 2]] = 1.0
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('vectors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
data = nm.zeros((3, 6))
data[:, :3] = [[1, 2, 3]]
expected = data.copy()
expected[1, [0, 1]] = expected[1, [1, 0]]
out = transform_data(data, coors)
_ok = nm.allclose(out, expected, rtol=0.0, atol=1e-14)
self.report('sym. tensors in cylindrical coordinates: %s' % _ok)
ok = ok and _ok
return ok
def test_transform_data4(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
if not hasattr(nm, 'einsum'):
self.report('no numpy.einsum(), skipping!')
return ok
expected = nm.zeros((6, 6), dtype=nm.float64)
expected[0, 0] = expected[1, 1] = 1.0
phi = nm.deg2rad(30.)
dr, v1, v2, om1, om2 = get_ortho_d(phi, phi + nm.deg2rad(90.))
# Rotate coordinate system by phi.
mtx = tn.make_axis_rotation_matrix([0., 0., 1.], phi)
do = tn.transform_data(dr[None, ...], mtx=mtx[None, ...])
_ok = nm.allclose(do, expected, rtol=0.0, atol=1e-14)
self.report('sym. 4th-th order tensor rotation: %s' % _ok)
ok = ok and _ok
dt, vt1, vt2, omt1, omt2 = get_ortho_d(0, nm.deg2rad(90.))
expected1 = nm.zeros((3, 3), dtype=nm.float64)
expected1[0, 0] = 1.0
expected2 = nm.zeros((3, 3), dtype=nm.float64)
expected2[1, 1] = 1.0
omr1 = nm.einsum('pq,ip,jq->ij', om1, mtx, mtx)
omr2 = nm.einsum('pq,ip,jq->ij', om2, mtx, mtx)
ii = tn.get_sym_indices(3)
jj = tn.get_full_indices(3)
o1 = om1.flat[ii]
o2 = om2.flat[ii]
omr12 = tn.transform_data(o1[None,...], mtx=mtx[None, ...])[0, jj]
omr22 = | tn.transform_data(o2[None,...], mtx=mtx[None, ...]) | sfepy.mechanics.tensors.transform_data |
# 28.05.2009, c
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/3d/elbow.mesh'
fields = {
'scalar' : ('real', 'scalar', 'Omega', 1),
'vector' : ('real', 'vector', 'Omega', 1),
}
integrals = {
'i1' : ('v', 'gauss_o2_d3'),
'i2' : ('s', 'gauss_o2_d2'),
}
regions = {
'Omega' : ('all', {}),
'Gamma' : ('nodes of surface', {'can_cells' : True}),
}
expressions = {
'volume_p' : 'd_volume.i1.Omega( p )',
'volume_u' : 'd_volume.i1.Omega( u )',
'surface_p' : 'd_volume_surface.i2.Gamma( p )',
'surface_u' : 'd_volume_surface.i2.Gamma( u )',
}
fe = {
'chunk_size' : 1000
}
import numpy as nm
from sfepy.base.testing import TestCommon
from sfepy.base.base import debug, pause
##
# 10.07.2007, c
class Test( TestCommon ):
tests = ['test_volume']
def from_conf( conf, options ):
from sfepy.fem import ProblemDefinition
problem = | ProblemDefinition.from_conf(conf, init_equations=False) | sfepy.fem.ProblemDefinition.from_conf |