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 = nm.array([[ 6., -2., -2., 0., 0., 0.], [-2., 6., -2., 0., 0., 0.], [-2., -2., 6., 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_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 = 2.0 / 3.0 * (lam - mu) _ds = mc.stiffness_from_lame(3, blam, 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() with modified lambda:', _ok) 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)) _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() with modified lambda:', _ok) ok = ok and _ok return ok
def get_inclusion_pars(ts, coor, mode=None, **kwargs): """TODO: implement proper 3D -> 2D transformation of constitutive matrices.""" if mode == 'qp': _, dim = coor.shape sym = (dim + 1) * dim // 2 dielectric = nm.eye(dim, dtype=nm.float64) # !!! coupling = nm.ones((dim, sym), dtype=nm.float64) # coupling[0,1] = 0.2 out = { # Lame coefficients in 1e+10 Pa. 'D': stiffness_from_lame(dim=2, lam=0.1798, mu=0.148), # dielectric tensor 'dielectric': dielectric, # piezoelectric coupling 'coupling': coupling, 'density': nm.array([[0.1142]]), # in 1e4 kg/m3 } for key, val in six.iteritems(out): out[key] = val[None, ...] return out
def get_inclusion_pars(ts, coor, mode=None, **kwargs): """TODO: implement proper 3D -> 2D transformation of constitutive matrices.""" if mode == 'qp': n_nod, dim = coor.shape sym = (dim + 1) * dim // 2 dielectric = nm.eye(dim, dtype=nm.float64) # !!! coupling = nm.ones((dim, sym), dtype=nm.float64) # coupling[0,1] = 0.2 out = { # Lame coefficients in 1e+10 Pa. 'D' : stiffness_from_lame(dim=2, lam=0.1798, mu=0.148), # dielectric tensor 'dielectric' : dielectric, # piezoelectric coupling 'coupling' : coupling, 'density' : 0.1142, # in 1e4 kg/m3 } for key, val in six.iteritems(out): out[key] = nm.tile(val, (coor.shape[0], 1, 1)) return out
def get_inclusion_pars(ts, coor, mode=None, **kwargs): """TODO: implement proper 3D -> 2D transformation of constitutive matrices.""" if mode == 'qp': n_nod, dim = coor.shape sym = (dim + 1) * dim / 2 dielectric = nm.eye(dim, dtype=nm.float64) # !!! coupling = nm.ones((dim, sym), dtype=nm.float64) # coupling[0,1] = 0.2 out = { # Lame coefficients in 1e+10 Pa. 'lam': 0.1798, 'mu': 0.148, # dielectric tensor 'dielectric': dielectric, # piezoelectric coupling 'coupling': coupling, 'density': 0.1142, # in 1e4 kg/m3 } out['D'] = stiffness_from_lame(2, out['lam'], out['mu']), for key, val in out.iteritems(): out[key] = nm.tile(val, (coor.shape[0], 1, 1)) return out
def get_pars(ts, coors, mode='qp', equations=None, term=None, problem=None, **kwargs): """ The material nonlinearity function - the Lamé coefficient `mu` depends on the strain. """ if mode != 'qp': return val = nm.empty((coors.shape[0], 1, 1), dtype=nm.float64) val.fill(1e0) order = term.integral.order uvar = equations.variables['u'] strain = problem.evaluate('ev_cauchy_strain.%d.Omega(u)' % order, u=uvar, mode='qp') if ts.step > 0: strain0 = strains[-1] else: strain0 = strain dstrain = (strain - strain0) / ts.dt dstrain.shape = (strain.shape[0] * strain.shape[1], strain.shape[2]) norm = norm_l2_along_axis(dstrain) val += norm[:, None, None] # Store history. strains[0] = strain return {'D': stiffness_from_lame(dim=3, lam=1e1, mu=val), 'mu': val}
def test_solving(self): from sfepy.base.base import IndexedStruct from sfepy.discrete import (FieldVariable, Material, Problem, Function, Equation, Equations, Integral) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.mechanics.matcoefs import stiffness_from_lame u = FieldVariable('u', 'unknown', self.field) v = FieldVariable('v', 'test', self.field, primary_var_name='u') m = Material('m', D=stiffness_from_lame(self.dim, 1.0, 1.0)) f = Material('f', val=[[0.02], [0.01]]) bc_fun = Function('fix_u_fun', fix_u_fun, extra_args={'extra_arg' : 'hello'}) fix_u = EssentialBC('fix_u', self.gamma1, {'u.all' : bc_fun}) shift_u = EssentialBC('shift_u', self.gamma2, {'u.0' : 0.1}) integral = Integral('i', order=3) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, self.omega, m=m, v=v, u=u) t2 = Term.new('dw_volume_lvf(f.val, v)', integral, self.omega, f=f, v=v) eq = Equation('balance', t1 + t2) eqs = Equations([eq]) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs) ## pb.save_regions_as_groups('regions') pb.set_bcs(ebcs=Conditions([fix_u, shift_u])) pb.set_solver(nls) state = pb.solve() name = op.join(self.options.out_dir, 'test_high_level_solving.vtk') pb.save_state(name, state) ok = nls_status.condition == 0 if not ok: self.report('solver did not converge!') _ok = state.has_ebc() if not _ok: self.report('EBCs violated!') ok = ok and _ok return ok
def get_fargs(self, lam, mu, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): from sfepy.mechanics.matcoefs import stiffness_from_lame mat = stiffness_from_lame(self.region.dim, lam, mu) return LinearElasticTerm.get_fargs(self, mat, virtual, state, mode=mode, term_mode=term_mode, diff_var=diff_var, **kwargs)
def test_solving(self): from sfepy.base.base import IndexedStruct from sfepy.discrete import (FieldVariable, Material, Problem, Function, Equation, Equations, Integral) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.mechanics.matcoefs import stiffness_from_lame u = FieldVariable('u', 'unknown', self.field) v = FieldVariable('v', 'test', self.field, primary_var_name='u') m = Material('m', D=stiffness_from_lame(self.dim, 1.0, 1.0)) f = Material('f', val=[[0.02], [0.01]]) bc_fun = Function('fix_u_fun', fix_u_fun, extra_args={'extra_arg' : 'hello'}) fix_u = EssentialBC('fix_u', self.gamma1, {'u.all' : bc_fun}) shift_u = EssentialBC('shift_u', self.gamma2, {'u.0' : 0.1}) integral = Integral('i', order=3) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, self.omega, m=m, v=v, u=u) t2 = Term.new('dw_volume_lvf(f.val, v)', integral, self.omega, f=f, v=v) eq = Equation('balance', t1 + t2) eqs = Equations([eq]) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) ## pb.save_regions_as_groups('regions') pb.time_update(ebcs=Conditions([fix_u, shift_u])) state = pb.solve() name = op.join(self.options.out_dir, 'test_high_level_solving.vtk') pb.save_state(name, state) ok = nls_status.condition == 0 if not ok: self.report('solver did not converge!') _ok = state.has_ebc() if not _ok: self.report('EBCs violated!') ok = ok and _ok return ok
def get_pars(dim, lam, mu): c = stiffness_from_lame(3, lam, mu) if dim == 2: tr = TransformToPlane() try: c = tr.tensor_plane_stress(c3=c) except: sym = (dim + 1) * dim // 2 c = nm.zeros((sym, sym), dtype=nm.float64) return c
def get_pars(dim, lam, mu): c = stiffness_from_lame(3, lam, mu) if dim == 2: tr = TransformToPlane() try: c = tr.tensor_plane_stress(c3=c) except: sym = (dim + 1) * dim / 2 c = nm.zeros((sym, sym), dtype=nm.float64) return c
def get_pars(lam, mu, dim, full=False): from sfepy.mechanics.matcoefs import stiffness_from_lame, TransformToPlane if full: c = stiffness_from_lame(3, lam, mu) if dim == 2: tr = TransformToPlane() try: c = tr.tensor_plane_stress(c3=c) except: sym = (dim + 1) * dim / 2 c = nm.zeros((sym, sym), dtype=nm.float64) return c else: return lam, mu
def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return
def get_pars(ts, coor, mode, output_dir=".", **kwargs): if mode == "qp": n_nod, dim = coor.shape sym = (dim + 1) * dim / 2 out = {} out["D"] = nm.tile(stiffness_from_lame(dim, lam=1.7, mu=0.3), (coor.shape[0], 1, 1)) aa = nm.zeros((sym, 1), dtype=nm.float64) aa[:dim] = 0.132 aa[dim:sym] = 0.092 out["alpha"] = nm.tile(aa, (coor.shape[0], 1, 1)) perm = nm.eye(dim, dtype=nm.float64) out["K"] = nm.tile(perm, (coor.shape[0], 1, 1)) return out
def get_pars(ts, coor, mode, output_dir='.', **kwargs): if mode == 'qp': n_nod, dim = coor.shape sym = (dim + 1) * dim // 2 out = {} out['D'] = nm.tile(stiffness_from_lame(dim, lam=1.7, mu=0.3), (coor.shape[0], 1, 1)) aa = nm.zeros((sym, 1), dtype=nm.float64) aa[:dim] = 0.132 aa[dim:sym] = 0.092 out['alpha'] = nm.tile(aa, (coor.shape[0], 1, 1)) perm = nm.eye(dim, dtype=nm.float64) out['K'] = nm.tile(perm, (coor.shape[0], 1, 1)) return out
def get_pars(ts, coor, mode, **kwargs): """ Define the material parameters. """ if mode == 'qp': n_nod, dim = coor.shape out = {} out['D'] = stiffness_from_lame(dim, lam=1.7, mu=0.3)[None, ...] out['alpha'] = nm.array([[[0.132, 0.092], [0.052, 0.132]]]) out['K'] = nm.eye(dim, dtype=nm.float64)[None, ...] out['np_eps'] = nm.array([[[1e5]]]) return out
def stress_strain(out, pb, state,lam,mu, extend=False): """ Calculate and output strain and stress for given displacements. """ from sfepy.base.base import Struct D = stiffness_from_lame(3,lam, mu) #asphalt = Material('Asphalt', D=D) mat = Material('Mat', D=D) ev = pb.evaluate strain = ev('ev_cauchy_strain.2.Omega(u)', mode='el_avg') stress = ev('ev_cauchy_stress.2.Omega(Mat.D, u)', mode='el_avg', copy_materials=False) out['cauchy_strain'] = Struct(name='output_data', mode='cell', data=strain, dofs=None) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out
def get_pars(ts, coor, mode, **kwargs): """ Define the material parameters. """ if mode == 'qp': n_nod, dim = coor.shape out = {} out['D'] = nm.tile(stiffness_from_lame(dim, lam=1.7, mu=0.3), (coor.shape[0], 1, 1)) alpha = [[0.132, 0.092], [0.052, 0.132]] out['alpha'] = nm.tile(alpha, (coor.shape[0], 1, 1)) perm = nm.eye(dim, dtype=nm.float64) out['K'] = nm.tile(perm, (coor.shape[0], 1, 1)) out['np_eps'] = nm.tile(1e5, (coor.shape[0], 1, 1)) return out
def get_pars(ts, coors, mode='qp', equations=None, term=None, problem=None, **kwargs): """ The material nonlinearity function - the Lamé coefficient `mu` depends on the strain. """ if mode != 'qp': return val = nm.empty(coors.shape[0], dtype=nm.float64) val.fill(1e0) order = term.integral.order uvar = equations.variables['u'] strain = problem.evaluate('ev_cauchy_strain.%d.Omega(u)' % order, u=uvar, mode='qp') if ts.step > 0: strain0 = strains[-1] else: strain0 = strain dstrain = (strain - strain0) / ts.dt dstrain.shape = (strain.shape[0] * strain.shape[1], strain.shape[2]) norm = norm_l2_along_axis(dstrain) val += norm # Store history. strains[0] = strain return { 'D': stiffness_from_lame(dim=3, lam=1e1, mu=val), 'mu': val.reshape(-1, 1, 1) }
def _material_func_(_, coors, mode=None, **__): if mode == "qp": return pipe( np.empty_like(coors, dtype=int), lambda x: np.floor( (coors - domain.get_mesh_bounding_box()[0][None]) / delta_x, x, casting="unsafe", ), lambda x: x.swapaxes(0, 1), tuple, lambda x: property_array[x], lambda x: dict( lam=reshape(x[..., 0]), mu=reshape(x[..., 1]), D=stiffness_from_lame( domain.get_mesh_bounding_box().shape[1], lam=x[..., 0], mu=x[..., 1], ), ), ) return None
def main(): from sfepy import data_dir parser = OptionParser(usage=usage, version='%prog') parser.add_option('-s', '--show', action="store_true", dest='show', default=False, help=help['show']) options, args = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/2d/rectangle_tri.mesh') domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:, 0] eps = 1e-8 * (max_x - min_x) omega = domain.create_region('Omega', 'all') gamma1 = domain.create_region('Gamma1', 'vertices in x < %.10f' % (min_x + eps), 'facet') gamma2 = domain.create_region('Gamma2', 'vertices in x > %.10f' % (max_x - eps), 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_lame(dim=2, lam=1.0, mu=1.0)) f = Material('f', val=[[0.02], [0.01]]) integral = Integral('i', order=3) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) t2 = Term.new('dw_volume_lvf(f.val, v)', integral, omega, f=f, v=v) eq = Equation('balance', t1 + t2) eqs = Equations([eq]) fix_u = EssentialBC('fix_u', gamma1, {'u.all': 0.0}) bc_fun = Function('shift_u_fun', shift_u_fun, extra_args={'shift': 0.01}) shift_u = EssentialBC('shift_u', gamma2, {'u.0': bc_fun}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) pb.save_regions_as_groups('regions') pb.time_update(ebcs=Conditions([fix_u, shift_u])) vec = pb.solve() print(nls_status) pb.save_state('linear_elasticity.vtk', vec) if options.show: view = Viewer('linear_elasticity.vtk') view(vector_mode='warp_norm', rel_scaling=2, is_scalar_bar=True, is_wireframe=True)
except: pass return out options = { 'nls': 'newton', 'ls': 'ls', 'post_process_hook': 'post_process', } materials = { 'm': ({ 'D': stiffness_from_lame(3, lam=0.0007, mu=0.0003), 'one': 1.0 }, ), } regions = { 'Omega': ('all', {}), 'Gamma_Left': ('nodes in (x < %f)' % xmin, {}), 'Gamma_Right': ('nodes in (x > %f)' % xmax, {}), } fields = { 'displacements': ('real', 'vector', 'Omega', 1), } variables = {
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 _lam, _mu = mc.lame_from_stiffness(d) _ok = (_lam == 1) and (_mu == 4) self.report('lame_from_stiffness():', _ok) ok = ok and _ok young = 1.0 poisson = 0.25 d = mc.stiffness_from_youngpoisson(3, young, poisson, plane='strain') _young, _poisson = mc.youngpoisson_from_stiffness(d, plane='strain') _ok = nm.allclose([young, poisson], [_young, _poisson], rtol=0.0, atol=1e-14) self.report('youngpoisson_from_stiffness(plane="strain"):', _ok) ok = ok and _ok d = mc.stiffness_from_youngpoisson(2, young, poisson, plane='stress') _young, _poisson = mc.youngpoisson_from_stiffness(d, plane='stress') _ok = nm.allclose([young, poisson], [_young, _poisson], rtol=0.0, atol=1e-14) self.report('youngpoisson_from_stiffness(plane="stress"):', _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)) _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() with modified lambda:', _ok) ok = ok and _ok return ok
$ ./postproc.py block3d.vtk --wireframe -b -d 'u,plot_displacements,rel_scaling=1e0' """ from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy import data_dir filename_domain = data_dir + '/meshes/iga/block3d.iga' regions = { 'Omega': 'all', 'Gamma1': ('vertices of set xi00', 'facet'), 'Gamma2': ('vertices of set xi01', 'facet'), } materials = { 'solid': ({ 'D': stiffness_from_lame(3, lam=5.769, mu=3.846), }, ), } fields = { 'displacement': ('real', 'vector', 'Omega', None, 'H1', 'iga'), } integrals = { 'i': 3, } variables = { 'u': ('unknown field', 'displacement', 0), 'v': ('test field', 'displacement', 'u'), }
def main(): parser = OptionParser(usage=usage, version='%prog') parser.add_option('-b', '--basis', metavar='name', action='store', dest='basis', default='lagrange', help=help['basis']) parser.add_option('-n', '--max-order', metavar='order', type=int, action='store', dest='max_order', default=10, help=help['max_order']) parser.add_option('-m', '--matrix', metavar='type', action='store', dest='matrix_type', default='laplace', help=help['matrix_type']) parser.add_option('-g', '--geometry', metavar='name', action='store', dest='geometry', default='2_4', help=help['geometry']) options, args = parser.parse_args() dim, n_ep = int(options.geometry[0]), int(options.geometry[2]) output('reference element geometry:') output(' dimension: %d, vertices: %d' % (dim, n_ep)) n_c = {'laplace' : 1, 'elasticity' : dim}[options.matrix_type] output('matrix type:', options.matrix_type) output('number of variable components:', n_c) output('polynomial space:', options.basis) output('max. order:', options.max_order) mesh = Mesh.from_file(data_dir + '/meshes/elements/%s_1.mesh' % options.geometry) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') orders = nm.arange(1, options.max_order + 1, dtype=nm.int) conds = [] order_fix = 0 if options.geometry in ['2_4', '3_8'] else 1 for order in orders: output('order:', order, '...') field = Field.from_args('fu', nm.float64, n_c, omega, approx_order=order, space='H1', poly_space_base=options.basis) to = field.approx_order quad_order = 2 * (max(to - order_fix, 0)) output('quadrature order:', quad_order) integral = Integral('i', order=quad_order) qp, _ = integral.get_qp(options.geometry) output('number of quadrature points:', qp.shape[0]) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_lame(dim, 1.0, 1.0), mu=1.0) if options.matrix_type == 'laplace': term = Term.new('dw_laplace(m.mu, v, u)', integral, omega, m=m, v=v, u=u) n_zero = 1 else: assert_(options.matrix_type == 'elasticity') term = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) n_zero = (dim + 1) * dim / 2 term.setup() output('assembling...') tt = time.clock() mtx, iels = term.evaluate(mode='weak', diff_var='u') output('...done in %.2f s' % (time.clock() - tt)) mtx = mtx[0][0, 0] try: assert_(nm.max(nm.abs(mtx - mtx.T)) < 1e-10) except: from sfepy.base.base import debug; debug() output('matrix shape:', mtx.shape) eigs = eig(mtx, method='eig.sgscipy', eigenvectors=False) eigs.sort() # Zero 'true' zeros. eigs[:n_zero] = 0.0 ii = nm.where(eigs < 0.0)[0] if len(ii): output('matrix is not positive semi-definite!') ii = nm.where(eigs[n_zero:] < 1e-12)[0] if len(ii): output('matrix has more than %d zero eigenvalues!' % n_zero) output('smallest eigs:\n', eigs[:10]) ii = nm.where(eigs > 0.0)[0] emin, emax = eigs[ii[[0, -1]]] output('min:', emin, 'max:', emax) cond = emax / emin conds.append(cond) output('condition number:', cond) output('...done') plt.figure(1) plt.semilogy(orders, conds) plt.xticks(orders, orders) plt.xlabel('polynomial order') plt.ylabel('condition number') plt.grid() plt.figure(2) plt.loglog(orders, conds) plt.xticks(orders, orders) plt.xlabel('polynomial order') plt.ylabel('condition number') plt.grid() plt.show()
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
from sfepy.postprocess.probes_vtk import Probe from sfepy.mechanics.matcoefs import stiffness_from_lame # Define options. options = { 'output_dir' : '.', 'post_process_hook' : 'post_process', } # Update materials, as ev_cauchy_stress below needs the elastic constants in # the tensor form. materials = deepcopy(materials) solid = materials['solid'][0] lam, mu = solid['lam'], solid['mu'] solid.update({ 'D' : stiffness_from_lame(3, lam=lam, mu=mu), }) # The function returning the probe parametrization. def par_fun(idx): return nm.log(idx + 1) / nm.log(20) * 0.04 # Define the function post_process, that will be called after the problem is # solved. def post_process(out, problem, state, extend=False): """ This will be called after the problem is solved. Parameters ---------- out : dict
def define(dim=2, use_ebcs=True): assert_(dim in (2, 3)) if dim == 2: filename_mesh = data_dir + '/meshes/2d/square_quad.mesh' else: filename_mesh = data_dir + '/meshes/3d/cube_medium_tetra.mesh' options = { 'nls': 'newton', 'ls': 'ls', 'post_process_hook': 'post_process' } def get_constraints(ts, coors, region=None): mtx = nm.ones((coors.shape[0], 1, dim), dtype=nm.float64) rhs = nm.arange(coors.shape[0], dtype=nm.float64)[:, None] rhs *= 0.1 / (coors.shape[0] - 1) return mtx, rhs functions = { 'get_constraints': (get_constraints, ), } fields = { 'displacement': ('real', dim, 'Omega', 1), } materials = { 'm': ({ 'D': stiffness_from_lame(dim, lam=5.769, mu=3.846), }, ), 'load': ({ 'val': -1.0 }, ), } variables = { 'u': ('unknown field', 'displacement', 0), 'v': ('test field', 'displacement', 'u'), } regions = { 'Omega': 'all', 'Bottom': ('vertices in (y < -0.499) -v r.Left', 'facet'), 'Top': ('vertices in (y > 0.499) -v r.Left', 'facet'), 'Left': ('vertices in (x < -0.499)', 'facet'), 'Right': ('vertices in (x > 0.499) -v (r.Bottom +v r.Top)', 'facet'), } if dim == 2: lcbcs = { 'nlcbc1': ('Top', { 'u.all': None }, None, 'nodal_combination', ([[1.0, -1.0]], [0.0])), 'nlcbc2': ('Bottom', { 'u.all': None }, None, 'nodal_combination', ([[1.0, 1.0]], [-0.1])), 'nlcbc3': ('Right', { 'u.all': None }, None, 'nodal_combination', 'get_constraints'), } else: lcbcs = { 'nlcbc1': ('Top', { 'u.all': None }, None, 'nodal_combination', ([[1.0, -1.0, 1.0], [1.0, 0.5, 0.1]], [0.0, 0.05])), 'nlcbc2': ('Bottom', { 'u.[2,1]': None }, None, 'nodal_combination', ([[1.0, -0.1]], [0.2])), 'nlcbc3': ('Right', { 'u.all': None }, None, 'nodal_combination', 'get_constraints'), } if use_ebcs: ebcs = { 'fix': ('Left', { 'u.all': 0.0 }), } else: ebcs = {} lcbcs.update({ 'nlcbc4': ('Left', { 'u.all': None }, None, 'nodal_combination', (nm.eye(dim), nm.zeros(dim))), }) equations = { 'elasticity': """ dw_lin_elastic.2.Omega(m.D, v, u) = -dw_surface_ltr.2.Right(load.val, v) """, } solvers = { 'ls': ('ls.scipy_direct', {}), 'newton': ('nls.newton', { 'i_max': 1, 'eps_a': 1e-10, }), } return locals()
'fixed_r': ('Right', { 'w.0': 0.0, 'theta.all': 0.0 }), } options = {} materials = { 'ac': ({ 'c': -1.064e+00, 'T': 9.202e-01, 'hG': thickness * 4.5e10 * nm.eye(2), 'hR': thickness * 0.71, 'h3R': thickness**3 / 3.0 * 0.71, 'h3C': thickness**3 / 3.0 * stiffness_from_lame(2, 1e1, 1e0) }, ), } equations = { 'eq_3': """ %e * dw_volume_dot.5.Gamma0(ac.c, z, g0) - %e * dw_volume_dot.5.Gamma0(ac.T, z, w) - %e * dw_volume_dot.5.Gamma0(ac.hR, z, w) + dw_diffusion.5.Gamma0(ac.hG, z, w) - dw_v_dot_grad_s.5.Gamma0(ac.hG, theta, z) = 0"""\ % (w2, w2, w2), 'eq_4': """ - %e * dw_volume_dot.5.Gamma0(ac.h3R, nu, theta) + dw_lin_elastic.5.Gamma0(ac.h3C, nu, theta)
from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy import data_dir filename_mesh = data_dir + '/meshes/3d/block.mesh' regions = { 'Omega': 'all', 'Left': ('vertices in (x < -4.99)', 'facet'), 'Omega1': 'vertices in (x < 0.001)', 'Omega2': 'vertices in (x > -0.001)', } materials = { 'solid': ({ 'D': stiffness_from_lame(3, lam=1e2, mu=1e1), 'prestress': 0.1 * nm.array([[1.0], [1.0], [1.0], [0.5], [0.5], [0.5]], dtype=nm.float64), 'DF': stiffness_from_lame(3, lam=8e0, mu=8e-1), 'nu': nm.array([[-0.5], [0.0], [0.5]], dtype=nm.float64), }, ), } fields = { 'displacement': ('real', 'vector', 'Omega', 1), } variables = {
def main(): parser = ArgumentParser(description=__doc__) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-b', '--basis', metavar='name', action='store', dest='basis', default='lagrange', help=help['basis']) parser.add_argument('-n', '--max-order', metavar='order', type=int, action='store', dest='max_order', default=10, help=help['max_order']) parser.add_argument('-m', '--matrix', metavar='type', action='store', dest='matrix_type', default='laplace', help=help['matrix_type']) parser.add_argument('-g', '--geometry', metavar='name', action='store', dest='geometry', default='2_4', help=help['geometry']) options = parser.parse_args() dim, n_ep = int(options.geometry[0]), int(options.geometry[2]) output('reference element geometry:') output(' dimension: %d, vertices: %d' % (dim, n_ep)) n_c = {'laplace': 1, 'elasticity': dim}[options.matrix_type] output('matrix type:', options.matrix_type) output('number of variable components:', n_c) output('polynomial space:', options.basis) output('max. order:', options.max_order) mesh = Mesh.from_file(data_dir + '/meshes/elements/%s_1.mesh' % options.geometry) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') orders = nm.arange(1, options.max_order + 1, dtype=nm.int) conds = [] order_fix = 0 if options.geometry in ['2_4', '3_8'] else 1 for order in orders: output('order:', order, '...') field = Field.from_args('fu', nm.float64, n_c, omega, approx_order=order, space='H1', poly_space_base=options.basis) to = field.approx_order quad_order = 2 * (max(to - order_fix, 0)) output('quadrature order:', quad_order) integral = Integral('i', order=quad_order) qp, _ = integral.get_qp(options.geometry) output('number of quadrature points:', qp.shape[0]) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_lame(dim, 1.0, 1.0), mu=1.0) if options.matrix_type == 'laplace': term = Term.new('dw_laplace(m.mu, v, u)', integral, omega, m=m, v=v, u=u) n_zero = 1 else: assert_(options.matrix_type == 'elasticity') term = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) n_zero = (dim + 1) * dim / 2 term.setup() output('assembling...') tt = time.clock() mtx, iels = term.evaluate(mode='weak', diff_var='u') output('...done in %.2f s' % (time.clock() - tt)) mtx = mtx[0, 0] try: assert_(nm.max(nm.abs(mtx - mtx.T)) < 1e-10) except: from sfepy.base.base import debug debug() output('matrix shape:', mtx.shape) eigs = eig(mtx, method='eig.sgscipy', eigenvectors=False) eigs.sort() # Zero 'true' zeros. eigs[:n_zero] = 0.0 ii = nm.where(eigs < 0.0)[0] if len(ii): output('matrix is not positive semi-definite!') ii = nm.where(eigs[n_zero:] < 1e-12)[0] if len(ii): output('matrix has more than %d zero eigenvalues!' % n_zero) output('smallest eigs:\n', eigs[:10]) ii = nm.where(eigs > 0.0)[0] emin, emax = eigs[ii[[0, -1]]] output('min:', emin, 'max:', emax) cond = emax / emin conds.append(cond) output('condition number:', cond) output('...done') plt.figure(1) plt.semilogy(orders, conds) plt.xticks(orders, orders) plt.xlabel('polynomial order') plt.ylabel('condition number') plt.grid() plt.figure(2) plt.loglog(orders, conds) plt.xticks(orders, orders) plt.xlabel('polynomial order') plt.ylabel('condition number') plt.grid() plt.show()
def main(): parser = ArgumentParser(description=__doc__) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-b', '--basis', metavar='name', action='store', dest='basis', default='lagrange', help=helps['basis']) parser.add_argument('-n', '--max-order', metavar='order', type=int, action='store', dest='max_order', default=10, help=helps['max_order']) parser.add_argument('-m', '--matrix', action='store', dest='matrix_type', choices=['laplace', 'elasticity', 'smass', 'vmass'], default='laplace', help=helps['matrix_type']) parser.add_argument('-g', '--geometry', metavar='name', action='store', dest='geometry', default='2_4', help=helps['geometry']) parser.add_argument('-o', '--output-dir', metavar='path', action='store', dest='output_dir', default=None, help=helps['output_dir']) parser.add_argument('--no-show', action='store_false', dest='show', default=True, help=helps['no_show']) options = parser.parse_args() dim, n_ep = int(options.geometry[0]), int(options.geometry[2]) output('reference element geometry:') output(' dimension: %d, vertices: %d' % (dim, n_ep)) n_c = { 'laplace': 1, 'elasticity': dim, 'smass': 1, 'vmass': dim }[options.matrix_type] output('matrix type:', options.matrix_type) output('number of variable components:', n_c) output('polynomial space:', options.basis) output('max. order:', options.max_order) mesh = Mesh.from_file(data_dir + '/meshes/elements/%s_1.mesh' % options.geometry) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') orders = nm.arange(1, options.max_order + 1, dtype=nm.int32) conds = [] for order in orders: output('order:', order, '...') field = Field.from_args('fu', nm.float64, n_c, omega, approx_order=order, space='H1', poly_space_base=options.basis) quad_order = 2 * field.approx_order output('quadrature order:', quad_order) integral = Integral('i', order=quad_order) qp, _ = integral.get_qp(options.geometry) output('number of quadrature points:', qp.shape[0]) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_lame(dim, 1.0, 1.0)) if options.matrix_type == 'laplace': term = Term.new('dw_laplace(v, u)', integral, omega, v=v, u=u) n_zero = 1 elif options.matrix_type == 'elasticity': term = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) n_zero = (dim + 1) * dim // 2 elif options.matrix_type in ('smass', 'vmass'): term = Term.new('dw_dot(v, u)', integral, omega, v=v, u=u) n_zero = 0 term.setup() output('assembling...') timer = Timer(start=True) mtx, iels = term.evaluate(mode='weak', diff_var='u') output('...done in %.2f s' % timer.stop()) mtx = mtx[0, 0] try: assert_(nm.max(nm.abs(mtx - mtx.T)) < 1e-10) except: from sfepy.base.base import debug debug() output('matrix shape:', mtx.shape) eigs = eig(mtx, method='eig.sgscipy', eigenvectors=False) eigs.sort() # Zero 'true' zeros. eigs[:n_zero] = 0.0 ii = nm.where(eigs < 0.0)[0] if len(ii): output('matrix is not positive semi-definite!') ii = nm.where(eigs[n_zero:] < 1e-12)[0] if len(ii): output('matrix has more than %d zero eigenvalues!' % n_zero) output('smallest eigs:\n', eigs[:10]) ii = nm.where(eigs > 0.0)[0] emin, emax = eigs[ii[[0, -1]]] output('min:', emin, 'max:', emax) cond = emax / emin conds.append(cond) output('condition number:', cond) output('...done') if options.output_dir is not None: indir = partial(op.join, options.output_dir) else: indir = None plt.rcParams['font.size'] = 12 plt.rcParams['lines.linewidth'] = 3 fig, ax = plt.subplots() ax.semilogy(orders, conds) ax.set_xticks(orders) ax.set_xticklabels(orders) ax.set_xlabel('polynomial order') ax.set_ylabel('condition number') ax.set_title(f'{options.basis.capitalize()} basis') ax.grid() plt.tight_layout() if indir is not None: fig.savefig(indir(f'{options.basis}-{options.matrix_type}-' f'{options.geometry}-{options.max_order}-xlin.png'), bbox_inches='tight') fig, ax = plt.subplots() ax.loglog(orders, conds) ax.set_xticks(orders) ax.set_xticklabels(orders) ax.set_xlabel('polynomial order') ax.set_ylabel('condition number') ax.set_title(f'{options.basis.capitalize()} basis') ax.grid() plt.tight_layout() if indir is not None: fig.savefig(indir(f'{options.basis}-{options.matrix_type}-' f'{options.geometry}-{options.max_order}-xlog.png'), bbox_inches='tight') if options.show: plt.show()
} ebcs = { 'fixed_l': ('Left', {'w.0': 0.0, 'theta.all': 0.0}), 'fixed_r': ('Right', {'w.0': 0.0, 'theta.all': 0.0}), } options = { } materials = { 'ac' : ({'c': -1.064e+00, 'T': 9.202e-01, 'hG': thickness * 4.5e10 * nm.eye(2), 'hR': thickness * 0.71, 'h3R': thickness**3 / 3.0 * 0.71, 'h3C': thickness**3 / 3.0 * stiffness_from_lame(2, 1e1, 1e0)}, ), } equations = { 'eq_3': """ %e * dw_volume_dot.5.Gamma0(ac.c, z, g0) - %e * dw_volume_dot.5.Gamma0(ac.T, z, w) - %e * dw_volume_dot.5.Gamma0(ac.hR, z, w) + dw_diffusion.5.Gamma0(ac.hG, z, w) - dw_v_dot_grad_s.5.Gamma0(ac.hG, theta, z) = 0"""\ % (w2, w2, w2), 'eq_4': """ - %e * dw_volume_dot.5.Gamma0(ac.h3R, nu, theta) + dw_lin_elastic.5.Gamma0(ac.h3C, nu, theta) - dw_v_dot_grad_s.5.Gamma0(ac.hG, nu, w)
def main(): from sfepy import data_dir parser = OptionParser(usage=usage, version='%prog') parser.add_option('-s', '--show', action="store_true", dest='show', default=False, help=help['show']) options, args = parser.parse_args() options_probe = True folder = str(uuid.uuid4()) os.mkdir(folder) os.chdir(folder) file = open('README.txt', 'w') file.write('DIMENSIONS\n') file.write('Lx = '+str(dims[0])+' Ly = '+str(dims[1])+' Lz = '+str(dims[2])+'\n') file.write('DISCRETIZATION (NX, NY, NZ)\n') file.write(str(NX)+' '+str(NY)+' '+str(NZ)+'\n') file.write('MATERIALS\n') file.write(str(E_f)+' '+str(nu_f)+' '+str(E_m)+' '+str(nu_m)+'\n') #mesh = Mesh.from_file(data_dir + '/meshes/2d/rectangle_tri.mesh') mesh = mesh_generators.gen_block_mesh(dims,shape,centre,name='block') domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:,0] min_y, max_y = domain.get_mesh_bounding_box()[:,1] min_z, max_z = domain.get_mesh_bounding_box()[:,2] eps = 1e-8 * (max_x - min_x) print min_x, max_x print min_y, max_y print min_z, max_z R1 = domain.create_region('Ym', 'vertices in z < %.10f' % (max_z/2)) R2 = domain.create_region('Yf', 'vertices in z >= %.10f' % (min_z/2)) omega = domain.create_region('Omega', 'all') gamma1 = domain.create_region('Left', 'vertices in x < %.10f' % (min_x + eps), 'facet') gamma2 = domain.create_region('Right', 'vertices in x > %.10f' % (max_x - eps), 'facet') gamma3 = domain.create_region('Front', 'vertices in y < %.10f' % (min_y + eps), 'facet') gamma4 = domain.create_region('Back', 'vertices in y > %.10f' % (max_y - eps), 'facet') gamma5 = domain.create_region('Bottom', 'vertices in z < %.10f' % (min_z + eps), 'facet') gamma6 = domain.create_region('Top', 'vertices in z > %.10f' % (max_z - eps), 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') mu=1.1 lam=1.0 m = Material('m', lam=lam, mu=mu) f = Material('f', val=[[0.0], [0.0],[-1.0]]) load = Material('Load',val=[[0.0],[0.0],[-Load]]) D = stiffness_from_lame(3,lam, mu) mat = Material('Mat', D=D) get_mat = Function('get_mat1',get_mat1) get_mat_f = Function('get_mat_f',get_mat1) integral = Integral('i', order=3) s_integral = Integral('is',order=2) t1 = Term.new('dw_lin_elastic(Mat.D, v, u)', integral, omega, Mat=mat, v=v, u=u) t2 = Term.new('dw_volume_lvf(f.val, v)', integral, omega, f=f, v=v) #t3 = Term.new('DotProductSurfaceTerm(Load.val, v)',s_integral,gamma5,Load=load,v=v) t3 = Term.new('dw_surface_ltr( Load.val, v )',s_integral,gamma6,Load=load,v=v) eq = Equation('balance', t1 + t2 + t3) eqs = Equations([eq]) fix_u = EssentialBC('fix_u', gamma1, {'u.all' : 0.0}) left_bc = EssentialBC('Left', gamma1, {'u.0' : 0.0}) right_bc = EssentialBC('Right', gamma2, {'u.0' : 0.0}) back_bc = EssentialBC('Front', gamma3, {'u.1' : 0.0}) front_bc = EssentialBC('Back', gamma4, {'u.1' : 0.0}) bottom_bc = EssentialBC('Bottom', gamma5, {'u.all' : 0.0}) top_bc = EssentialBC('Top', gamma6, {'u.2' : 0.2}) bc=[left_bc,right_bc,back_bc,front_bc,bottom_bc] #bc=[bottom_bc,top_bc] ############################## # ##### SOLVER SECTION ##### ############################## conf = Struct(method='bcgsl', precond='jacobi', sub_precond=None, i_max=10000, eps_a=1e-50, eps_r=1e-10, eps_d=1e4, verbose=True) ls = PETScKrylovSolver(conf) file.write(str(ls.name)+' '+str(ls.conf.method)+' '+str(ls.conf.precond)+' '+str(ls.conf.eps_r)+' '+str(ls.conf.i_max)+'\n' ) nls_status = IndexedStruct() nls = Newton({'i_max':1,'eps_a':1e-10}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) dd=pb.get_materials()['Mat'] dd.set_function(get_mat1) #xload = pb.get_materials()['f'] #xload.set_function(get_mat_f) pb.save_regions_as_groups('regions') pb.time_update(ebcs=Conditions(bc)) vec = pb.solve() print nls_status file.write('TIME TO SOLVE\n') file.write(str(nls.status.time_stats['solve'])+'\n') file.write('TIME TO CREATE MATRIX\n') file.write(str(nls.status.time_stats['matrix'])+'\n') ev = pb.evaluate out = vec.create_output_dict() strain = ev('ev_cauchy_strain.3.Omega(u)', mode='el_avg') stress = ev('ev_cauchy_stress.3.Omega(Mat.D, u)', mode='el_avg', copy_materials=False) out['cauchy_strain'] = Struct(name='output_data', mode='cell', data=strain, dofs=None) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) pb.save_state('strain.vtk', out=out) print nls_status file.close()
'fix_u': ('Bottom', { 'u.all': 0.0 }), 'load_u': ('Top', { 'u.2': 0.2 }), 'load_p': ('Left', { 'p.all': 1.0 }), } material_1 = { 'name': 'm', 'values': { 'D': stiffness_from_lame(dim=3, lam=1.7, mu=0.3), 'alpha': nm.array([[0.132], [0.132], [0.132], [0.092], [0.092], [0.092]], dtype=nm.float64), 'K': nm.array([[2.0, 0.2, 0.0], [0.2, 1.0, 0.0], [0.0, 0.0, 0.5]], dtype=nm.float64), } } integral_1 = { 'name': 'i1', 'order': 1, } integral_2 = {
'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), 'p' : ('unknown field', 'pressure', 1), 'q' : ('test field', 'pressure', 'p'), } ebcs = { 'fix_u' : ('Bottom', {'u.all' : 0.0}), 'load_u' : ('Top', {'u.2' : 0.2}), 'load_p' : ('Left', {'p.all' : 1.0}), } material_1 = { 'name' : 'm', 'values' : { 'D': stiffness_from_lame(dim=3, lam=1.7, mu=0.3), 'alpha' : nm.array( [[0.132], [0.132], [0.132], [0.092], [0.092], [0.092]], dtype = nm.float64 ), 'K' : nm.array( [[2.0, 0.2, 0.0], [0.2, 1.0, 0.0], [0.0, 0.0, 0.5]], dtype = nm.float64 ), } } integral_1 = { 'name' : 'i1', 'order' : 1, } integral_2 = { 'name' : 'i2',
t0 = 0.0 t1 = 20.0 n_step = 21 # Fading memory times. f_t0 = 0.0 f_t1 = 5.0 f_n_step = 6 decay = 0.8 mode = 'eth' ## Configure above. ## times = nm.linspace(f_t0, f_t1, f_n_step) kernel = get_exp_fading_kernel(stiffness_from_lame(3, lam=1.0, mu=1.0), decay, times) dt = (t1 - t0) / (n_step - 1) fading_memory_length = min(int((f_t1 - f_t0) / dt) + 1, n_step) output('fading memory length:', fading_memory_length) def post_process(out, pb, state, extend=False): """ Calculate and output strain and stress for given displacements. """ from sfepy.base.base import Struct ev = pb.evaluate strain = ev('ev_cauchy_strain.2.Omega(u)', mode='el_avg')
return val.T functions = { 'get_shift' : (get_shift,), 'linear_tension' : (linear_tension,), 'match_y_plane' : (per.match_y_plane,), 'match_z_plane' : (per.match_z_plane,), } fields = { 'displacement': ('real', 3, 'Omega', 1), } materials = { 'solid' : ({ 'D' : stiffness_from_lame(3, lam=5.769, mu=3.846), },), 'load' : (None, 'linear_tension') } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Left' : ('vertices in (x < -4.99)', 'facet'), 'Right' : ('vertices in (x > 4.99)', 'facet'), 'Bottom' : ('vertices in (z < -0.99)', 'facet'), 'Top' : ('vertices in (z > 0.99)', 'facet'),
region_10 = { 'name' : 'Bottom', 'select' : 'vertices in (y < %f)' % -wy, 'kind' : 'facet', } region_11 = { 'name' : 'Top', 'select' : 'vertices in (y > %f)' % wy, 'kind' : 'facet', } material_1 = { 'name' : 'solid', 'values' : { 'D' : stiffness_from_lame(2, 1e1, 1e0), 'density' : 1e-1, }, } field_1 = { 'name' : '2_displacement', 'dtype' : 'real', 'shape' : 'vector', 'region' : 'Y', 'approx_order' : 2, } variable_1 = { 'name' : 'u', 'kind' : 'unknown field',
t0 = 0.0 t1 = 20.0 n_step = 21 # Fading memory times. f_t0 = 0.0 f_t1 = 5.0 f_n_step = 6 decay = 0.8 mode = "eth" ## Configure above. ## times = nm.linspace(f_t0, f_t1, f_n_step) kernel = get_exp_fading_kernel(stiffness_from_lame(3, lam=1.0, mu=1.0), decay, times) dt = (t1 - t0) / (n_step - 1) fading_memory_length = min(int((f_t1 - f_t0) / dt) + 1, n_step) output("fading memory length:", fading_memory_length) def post_process(out, pb, state, extend=False): """ Calculate and output strain and stress for given displacements. """ from sfepy.base.base import Struct ev = pb.evaluate strain = ev("ev_cauchy_strain.2.Omega(u)", mode="el_avg") out["cauchy_strain"] = Struct(name="output_data", mode="cell", data=strain, dofs=None)
def define(K=8.333, mu_nh=3.846, mu_mr=1.923, kappa=1.923, lam=5.769, mu=3.846): """Define the problem to solve.""" from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import stiffness_from_lame def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3', verbose=False) return mesh elif mode == 'write': pass filename_mesh = UserMeshIO(mesh_hook) options = { 'nls': 'newton', 'ls': 'ls', 'ts': 'ts', 'save_times': 'all', } functions = { 'linear_pressure': (linear_pressure, ), 'empty': (lambda ts, coor, mode, region, ig: None, ), } fields = { 'displacement': ('real', 3, 'Omega', 1), } # Coefficients are chosen so that the tangent stiffness is the same for all # material for zero strains. materials = { 'solid': ( { 'K': K, # bulk modulus 'mu_nh': mu_nh, # shear modulus of neoHookean term 'mu_mr': mu_mr, # shear modulus of Mooney-Rivlin term 'kappa': kappa, # second modulus of Mooney-Rivlin term # elasticity for LE term 'D': stiffness_from_lame(dim=3, lam=lam, mu=mu), }, ), 'load': 'empty', } variables = { 'u': ('unknown field', 'displacement', 0), 'v': ('test field', 'displacement', 'u'), } regions = { 'Omega': 'all', 'Bottom': ('vertices in (z < 0.1)', 'facet'), 'Top': ('vertices in (z > 2.9)', 'facet'), } ebcs = { 'fixb': ('Bottom', { 'u.all': 0.0 }), 'fixt': ('Top', { 'u.[0,1]': 0.0 }), } integrals = { 'i': 1, 'isurf': 2, } equations = { 'linear': """dw_lin_elastic.i.Omega(solid.D, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'neo-Hookean': """dw_tl_he_neohook.i.Omega(solid.mu_nh, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'Mooney-Rivlin': """dw_tl_he_neohook.i.Omega(solid.mu_mr, v, u) + dw_tl_he_mooney_rivlin.i.Omega(solid.kappa, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", } solvers = { 'ls': ('ls.scipy_direct', {}), 'newton': ('nls.newton', { 'i_max': 5, 'eps_a': 1e-10, 'eps_r': 1.0, }), 'ts': ( 'ts.simple', { 't0': 0, 't1': 1, 'time_interval': None, 'n_step': 26, # has precedence over time_interval! 'verbose': 1, }), } return locals()
def define(): """Define the problem to solve.""" from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import stiffness_from_lame def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3', verbose=False) return mesh elif mode == 'write': pass filename_mesh = UserMeshIO(mesh_hook) options = { 'nls' : 'newton', 'ls' : 'ls', 'ts' : 'ts', 'save_steps' : -1, } functions = { 'linear_tension' : (linear_tension,), 'linear_compression' : (linear_compression,), 'empty' : (lambda ts, coor, mode, region, ig: None,), } fields = { 'displacement' : ('real', 3, 'Omega', 1), } # Coefficients are chosen so that the tangent stiffness is the same for all # material for zero strains. # Young modulus = 10 kPa, Poisson's ratio = 0.3 materials = { 'solid' : ({ 'K' : 8.333, # bulk modulus 'mu_nh' : 3.846, # shear modulus of neoHookean term 'mu_mr' : 1.923, # shear modulus of Mooney-Rivlin term 'kappa' : 1.923, # second modulus of Mooney-Rivlin term # elasticity for LE term 'D' : stiffness_from_lame(dim=3, lam=5.769, mu=3.846), },), 'load' : 'empty', } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Bottom' : ('vertices in (z < 0.1)', 'facet'), 'Top' : ('vertices in (z > 2.9)', 'facet'), } ebcs = { 'fixb' : ('Bottom', {'u.all' : 0.0}), 'fixt' : ('Top', {'u.[0,1]' : 0.0}), } integrals = { 'i' : 1, 'isurf' : 2, } equations = { 'linear' : """dw_lin_elastic.i.Omega(solid.D, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'neo-Hookean' : """dw_tl_he_neohook.i.Omega(solid.mu_nh, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'Mooney-Rivlin' : """dw_tl_he_neohook.i.Omega(solid.mu_mr, v, u) + dw_tl_he_mooney_rivlin.i.Omega(solid.kappa, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 5, 'eps_a' : 1e-10, 'eps_r' : 1.0, }), 'ts' : ('ts.simple', { 't0' : 0, 't1' : 1, 'dt' : None, 'n_step' : 101, # has precedence over dt! }), } return locals()
import numpy as nm from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy import data_dir filename_mesh = data_dir + '/meshes/3d/block.mesh' regions = { 'Omega' : 'all', 'Left' : ('vertices in (x < -4.99)', 'facet'), 'Omega1' : 'vertices in (x < 0.001)', 'Omega2' : 'vertices in (x > -0.001)', } materials = { 'solid' : ({ 'D' : stiffness_from_lame(3, lam=1e2, mu=1e1), 'prestress' : 0.1 * nm.array([[1.0], [1.0], [1.0], [0.5], [0.5], [0.5]], dtype=nm.float64), 'DF' : stiffness_from_lame(3, lam=8e0, mu=8e-1), 'nu' : nm.array([[-0.5], [0.0], [0.5]], dtype=nm.float64), },), } fields = { 'displacement': ('real', 'vector', 'Omega', 1), } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'),
def define(): """Define the problem to solve.""" from sfepy import data_dir filename_mesh = data_dir + '/meshes/3d/block.mesh' options = { 'nls' : 'newton', 'ls' : 'ls', } functions = { 'linear_tension' : (linear_tension,), } fields = { 'displacement': ('real', 3, 'Omega', 1), } materials = { 'solid' : ({'D': stiffness_from_lame(3, lam=5.769, mu=3.846)},), 'load' : (None, 'linear_tension') } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Left' : ('vertices in (x < -4.99)', 'facet'), 'Right' : ('vertices in (x > 4.99)', 'facet'), } ebcs = { 'fixb' : ('Left', {'u.all' : 0.0}), 'fixt' : ('Right', {'u.[1,2]' : 0.0}), } ## # Balance of forces. equations = { 'elasticity' : """dw_lin_elastic.2.Omega( solid.D, v, u ) = - dw_surface_ltr.2.Right( load.val, v )""", } ## # Solvers etc. solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 1, 'eps_a' : 1e-10, 'eps_r' : 1.0, 'macheps' : 1e-16, # Linear system error < (eps_a * lin_red). 'lin_red' : 1e-2, 'ls_red' : 0.1, 'ls_red_warp' : 0.001, 'ls_on' : 1.1, 'ls_min' : 1e-5, 'check' : 0, 'delta' : 1e-6, }) } return locals()
def define(dim=2, use_ebcs=True): assert_(dim in (2, 3)) if dim == 2: filename_mesh = data_dir + '/meshes/2d/square_quad.mesh' else: filename_mesh = data_dir + '/meshes/3d/cube_medium_tetra.mesh' options = { 'nls' : 'newton', 'ls' : 'ls', 'post_process_hook' : 'post_process' } def get_constraints(ts, coors, region=None): mtx = nm.ones((coors.shape[0], 1, dim), dtype=nm.float64) rhs = nm.arange(coors.shape[0], dtype=nm.float64)[:, None] rhs *= 0.1 / (coors.shape[0] - 1) return mtx, rhs functions = { 'get_constraints' : (get_constraints,), } fields = { 'displacement': ('real', dim, 'Omega', 1), } materials = { 'm' : ({ 'D' : stiffness_from_lame(dim, lam=5.769, mu=3.846), },), 'load' : ({'val' : -1.0},), } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Bottom' : ('vertices in (y < -0.499) -v r.Left', 'facet'), 'Top' : ('vertices in (y > 0.499) -v r.Left', 'facet'), 'Left' : ('vertices in (x < -0.499)', 'facet'), 'Right' : ('vertices in (x > 0.499) -v (r.Bottom +v r.Top)', 'facet'), } if dim == 2: lcbcs = { 'nlcbc1' : ('Top', {'u.all' : None}, None, 'nodal_combination', ([[1.0, -1.0]], [0.0])), 'nlcbc2' : ('Bottom', {'u.all' : None}, None, 'nodal_combination', ([[1.0, 1.0]], [-0.1])), 'nlcbc3' : ('Right', {'u.all' : None}, None, 'nodal_combination', 'get_constraints'), } else: lcbcs = { 'nlcbc1' : ('Top', {'u.all' : None}, None, 'nodal_combination', ([[1.0, -1.0, 1.0], [1.0, 0.5, 0.1]], [0.0, 0.05])), 'nlcbc2' : ('Bottom', {'u.[2,1]' : None}, None, 'nodal_combination', ([[1.0, -0.1]], [0.2])), 'nlcbc3' : ('Right', {'u.all' : None}, None, 'nodal_combination', 'get_constraints'), } if use_ebcs: ebcs = { 'fix' : ('Left', {'u.all' : 0.0}), } else: ebcs = {} lcbcs.update({ 'nlcbc4' : ('Left', {'u.all' : None}, None, 'nodal_combination', (nm.eye(dim), nm.zeros(dim))), }) equations = { 'elasticity' : """ dw_lin_elastic.2.Omega(m.D, v, u) = -dw_surface_ltr.2.Right(load.val, v) """, } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 1, 'eps_a' : 1e-10, }), } return locals()
t0 = 0.0 t1 = 20.0 n_step = 21 # Fading memory times. f_t0 = 0.0 f_t1 = 5.0 f_n_step = 6 decay = 0.8 mode = 'eth' ## Configure above. ## times = nm.linspace(f_t0, f_t1, f_n_step) kernel = get_exp_fading_kernel(stiffness_from_lame(3, lam=1.0, mu=1.0), decay, times) dt = (t1 - t0) / (n_step - 1) fading_memory_length = min(int((f_t1 - f_t0) / dt) + 1, n_step) output('fading memory length:', fading_memory_length) def post_process(out, pb, state, extend=False): """ Calculate and output strain and stress for given displacements. """ from sfepy.base.base import Struct ev = pb.evaluate strain = ev('ev_cauchy_strain.2.Omega(u)', mode='el_avg') out['cauchy_strain'] = Struct(name='output_data', mode='cell',
region_10 = { 'name': 'Bottom', 'select': 'vertices in (z < %f)' % -0.499, 'kind': 'facet', } region_11 = { 'name': 'Top', 'select': 'vertices in (z > %f)' % 0.499, 'kind': 'facet', } material_1 = { 'name': 'solid', 'values': { 'D': stiffness_from_lame(3, 1e1, 1e0), 'density': 1e-1, }, } field_1 = { 'name': '3_displacement', 'dtype': 'real', 'shape': 'vector', 'region': 'Y', 'approx_order': 1, } variable_1 = { 'name': 'u', 'kind': 'unknown field',
% (vn, vn), verbose=False) print 'dw_lin_elastic', vn, val except: pass return out options = { 'nls' : 'newton', 'ls' : 'ls', 'post_process_hook' : 'post_process', } materials = { 'm' : ({'D' : stiffness_from_lame(3, lam=0.0007, mu=0.0003), 'one' : 1.0},), } regions = { 'Omega' : ('all', {}), 'Gamma_Left' : ('nodes in (x < %f)' % xmin, {}), 'Gamma_Right' : ('nodes in (x > %f)' % xmax, {}), } fields = { 'displacements' : ('real', 'vector', 'Omega', 1), } variables = { 'u' : ('unknown field', 'displacements', 0),
from __future__ import absolute_import from sfepy import data_dir from sfepy.mechanics.matcoefs import stiffness_from_lame filename_mesh = data_dir + '/meshes/3d/cylinder.mesh' regions = { 'Omega' : 'all', 'Left' : ('vertices in (x < 0.001)', 'facet'), 'Right' : ('vertices in (x > 0.099)', 'facet'), 'SomewhereTop' : ('vertices in (z > 0.017) & (x > 0.03) & (x < 0.07)', 'vertex'), } materials = { 'solid' : ({'D': stiffness_from_lame(dim=3, lam=1e1, mu=1e0)},), } fields = { 'displacement': ('real', 'vector', 'Omega', 1), } integrals = { 'i' : 1, } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), }
import numpy as nm sym = (dim + 1) * dim / 2 lam = 1e1 mu = 1e0 o = nm.array( [1.] * dim + [0.] * (sym - dim), dtype = nm.float64 ) oot = nm.outer( o, o ) if full: return lam * oot + mu * nm.diag( o + 1.0 ) else: return lam, mu material_1 = { 'name' : 'solid', 'values' : { 'Dijkl' : get_pars( 3, True ), 'D' : stiffness_from_lame(3, get_pars(3)[0], get_pars(3)[1]), 'lam' : get_pars(3)[0], 'mu' : get_pars(3)[1], } } material_2 = { 'name' : 'spring', 'values' : { '.stiffness' : 1e0, } } variable_1 = { 'name' : 'u', 'kind' : 'unknown field',
def main(): from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/2d/rectangle_tri.mesh') domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:,0] eps = 1e-8 * (max_x - min_x) omega = domain.create_region('Omega', 'all') gamma1 = domain.create_region('Gamma1', 'vertices in x < %.10f' % (min_x + eps), 'facet') gamma2 = domain.create_region('Gamma2', 'vertices in x > %.10f' % (max_x - eps), 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_lame(dim=2, lam=1.0, mu=1.0)) f = Material('f', val=[[0.02], [0.01]]) integral = Integral('i', order=3) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) t2 = Term.new('dw_volume_lvf(f.val, v)', integral, omega, f=f, v=v) eq = Equation('balance', t1 + t2) eqs = Equations([eq]) fix_u = EssentialBC('fix_u', gamma1, {'u.all' : 0.0}) bc_fun = Function('shift_u_fun', shift_u_fun, extra_args={'shift' : 0.01}) shift_u = EssentialBC('shift_u', gamma2, {'u.0' : bc_fun}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) pb.save_regions_as_groups('regions') pb.time_update(ebcs=Conditions([fix_u, shift_u])) vec = pb.solve() print(nls_status) pb.save_state('linear_elasticity.vtk', vec) if options.show: view = Viewer('linear_elasticity.vtk') view(vector_mode='warp_norm', rel_scaling=2, is_scalar_bar=True, is_wireframe=True)