Dataset Viewer
Auto-converted to Parquet Duplicate
code
stringlengths
768
64.5k
apis
sequence
extract_api
stringlengths
180
29k
import numpy as nm from sfepy.linalg import dot_sequences from sfepy.terms.terms import Term, terms class DivGradTerm(Term): r""" Diffusion term. :Definition: .. math:: \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u} \mbox{ , } \int_{\Omega} \nu\ \nabla \ul{u} : \nabla \ul{w} \\ \int_{\Omega} \nabla \ul{v} : \nabla \ul{u} \mbox{ , } \int_{\Omega} \nabla \ul{u} : \nabla \ul{w} :Arguments 1: - material : :math:`\nu` (viscosity, optional) - virtual : :math:`\ul{v}` - state : :math:`\ul{u}` :Arguments 2: - material : :math:`\nu` (viscosity, optional) - parameter_1 : :math:`\ul{u}` - parameter_2 : :math:`\ul{w}` """ name = 'dw_div_grad' arg_types = (('opt_material', 'virtual', 'state'), ('opt_material', 'parameter_1', 'parameter_2')) arg_shapes = {'opt_material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter_1' : 'D', 'parameter_2' : 'D'} modes = ('weak', 'eval') function = staticmethod(terms.term_ns_asm_div_grad) def d_div_grad(self, out, grad1, grad2, mat, vg, fmode): sh = grad1.shape g1 = grad1.reshape((sh[0], sh[1], sh[2] * sh[3])) g2 = grad2.reshape((sh[0], sh[1], sh[2] * sh[3])) aux = mat * dot_sequences(g1[..., None], g2, 'ATB')[..., None] if fmode == 2: out[:] = aux status = 0 else: status = vg.integrate(out, aux, fmode) return status def get_fargs(self, mat, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) if mat is None: n_el, n_qp, dim, n_en, n_c = self.get_data_shape(state) mat = nm.ones((1, n_qp, 1, 1), dtype=nm.float64) if mode == 'weak': if diff_var is None: grad = self.get(state, 'grad').transpose((0, 1, 3, 2)) sh = grad.shape grad = grad.reshape((sh[0], sh[1], sh[2] * sh[3], 1)) fmode = 0 else: grad = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return grad, mat, vg, fmode elif mode == 'eval': grad1 = self.get(virtual, 'grad') grad2 = self.get(state, 'grad') fmode = {'eval' : 0, 'el_avg' : 1, 'qp' : 2}.get(mode, 1) return grad1, grad2, mat, vg, fmode else: raise ValueError('unsupported evaluation mode in %s! (%s)' % (self.name, mode)) def get_eval_shape(self, mat, 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 def set_arg_types(self): if self.mode == 'weak': self.function = terms.term_ns_asm_div_grad else: self.function = self.d_div_grad class ConvectTerm(Term): r""" Nonlinear convective term. :Definition: .. math:: \int_{\Omega} ((\ul{u} \cdot \nabla) \ul{u}) \cdot \ul{v} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{u}` """ name = 'dw_convect' arg_types = ('virtual', 'state') arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D'} function = staticmethod(terms.term_ns_asm_convect) def get_fargs(self, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) grad = self.get(state, 'grad').transpose((0, 1, 3, 2)).copy() val_qp = self.get(state, 'val') fmode = diff_var is not None return grad, val_qp, vg, fmode class LinearConvectTerm(Term): r""" Linearized convective term. :Definition: .. math:: \int_{\Omega} ((\ul{b} \cdot \nabla) \ul{u}) \cdot \ul{v} .. math:: ((\ul{b} \cdot \nabla) \ul{u})|_{qp} :Arguments: - virtual : :math:`\ul{v}` - parameter : :math:`\ul{b}` - state : :math:`\ul{u}` """ name = 'dw_lin_convect' arg_types = ('virtual', 'parameter', 'state') arg_shapes = {'virtual' : ('D', 'state'), 'parameter' : 'D', 'state' : 'D'} function = staticmethod(terms.dw_lin_convect) def get_fargs(self, virtual, parameter, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_qp = self.get(parameter, 'val') if mode == 'weak': if diff_var is None: grad = self.get(state, 'grad').transpose((0, 1, 3, 2)).copy() fmode = 0 else: grad = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return grad, val_qp, vg, fmode elif mode == 'qp': grad = self.get(state, 'grad').transpose((0, 1, 3, 2)).copy() fmode = 2 return grad, val_qp, vg, fmode else: raise ValueError('unsupported evaluation mode in %s! (%s)' % (self.name, mode)) class StokesTerm(Term): r""" Stokes problem coupling term. Corresponds to weak forms of gradient and divergence terms. Can be evaluated. :Definition: .. math:: \int_{\Omega} p\ \nabla \cdot \ul{v} \mbox{ , } \int_{\Omega} q\ \nabla \cdot \ul{u} \mbox{ or } \int_{\Omega} c\ p\ \nabla \cdot \ul{v} \mbox{ , } \int_{\Omega} c\ q\ \nabla \cdot \ul{u} :Arguments 1: - material : :math:`c` (optional) - virtual : :math:`\ul{v}` - state : :math:`p` :Arguments 2: - material : :math:`c` (optional) - state : :math:`\ul{u}` - virtual : :math:`q` :Arguments 3: - material : :math:`c` (optional) - parameter_v : :math:`\ul{u}` - parameter_s : :math:`p` """ name = 'dw_stokes' arg_types = (('opt_material', 'virtual', 'state'), ('opt_material', 'state', 'virtual'), ('opt_material', 'parameter_v', 'parameter_s')) arg_shapes = [{'opt_material' : '1, 1', 'virtual/grad' : ('D', None), 'state/grad' : 1, 'virtual/div' : (1, None), 'state/div' : 'D', 'parameter_v' : 'D', 'parameter_s' : 1}, {'opt_material' : None}] modes = ('grad', 'div', 'eval') @staticmethod def d_eval(out, coef, vec_qp, div, vvg): out_qp = coef * vec_qp * div status = vvg.integrate(out, out_qp) return status def get_fargs(self, coef, vvar, svar, mode=None, term_mode=None, diff_var=None, **kwargs): if self.mode == 'grad': qp_var, qp_name = svar, 'val' else: qp_var, qp_name = vvar, 'div' n_el, n_qp, dim, n_en, n_c = self.get_data_shape(vvar) if coef is None: coef = nm.ones((1, n_qp, 1, 1), dtype=nm.float64) if mode == 'weak': vvg, _ = self.get_mapping(vvar) svg, _ = self.get_mapping(svar) if diff_var is None: val_qp = self.get(qp_var, qp_name) fmode = 0 else: val_qp = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return coef, val_qp, svg, vvg, fmode elif mode == 'eval': vvg, _ = self.get_mapping(vvar) div = self.get(vvar, 'div') vec_qp = self.get(svar, 'val') return coef, vec_qp, div, vvg else: raise ValueError('unsupported evaluation mode in %s! (%s)' % (self.name, mode)) def get_eval_shape(self, coef, vvar, svar, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(vvar) return (n_el, 1, 1, 1), vvar.dtype def set_arg_types(self): self.function = { 'grad' : terms.dw_grad, 'div' : terms.dw_div, 'eval' : self.d_eval, }[self.mode] class GradTerm(Term): r""" Evaluate gradient of a scalar or vector field. Supports 'eval', 'el_avg' and 'qp' evaluation modes. :Definition: .. math:: \int_{\Omega} \nabla p \mbox{ or } \int_{\Omega} \nabla \ul{w} .. math:: \mbox{vector for } K \from \Ical_h: \int_{T_K} \nabla p / \int_{T_K} 1 \mbox{ or } \int_{T_K} \nabla \ul{w} / \int_{T_K} 1 .. math:: (\nabla p)|_{qp} \mbox{ or } \nabla \ul{w}|_{qp} :Arguments: - parameter : :math:`p` or :math:`\ul{w}` """ name = 'ev_grad' arg_types = ('parameter',) arg_shapes = [{'parameter' : 1}, {'parameter' : 'D'}] @staticmethod def function(out, grad, vg, fmode): if fmode == 2: out[:] = grad status = 0 else: status = vg.integrate(out, grad, fmode) return status def get_fargs(self, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(parameter) grad = self.get(parameter, 'grad') fmode = {'eval' : 0, 'el_avg' : 1, 'qp' : 2}.get(mode, 1) return grad, vg, fmode def get_eval_shape(self, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(parameter) if mode != 'qp': n_qp = 1 return (n_el, n_qp, dim, n_c), parameter.dtype class DivTerm(Term): r""" Evaluate divergence of a vector field. Supports 'eval', 'el_avg' and 'qp' evaluation modes. :Definition: .. math:: \int_{\Omega} \nabla \cdot \ul{u} .. math:: \mbox{vector for } K \from \Ical_h: \int_{T_K} \nabla \cdot \ul{u} / \int_{T_K} 1 .. math:: (\nabla \cdot \ul{u})|_{qp} :Arguments: - parameter : :math:`\ul{u}` """ name = 'ev_div' arg_types = ('parameter',) arg_shapes = {'parameter' : 'D'} @staticmethod def function(out, div, vg, fmode): if fmode == 2: out[:] = div status = 0 else: status = vg.integrate(out, div, fmode) return status def get_fargs(self, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(parameter) div = self.get(parameter, 'div') fmode = {'eval' : 0, 'el_avg' : 1, 'qp' : 2}.get(mode, 1) return div, vg, fmode def get_eval_shape(self, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(parameter) if mode != 'qp': n_qp = 1 return (n_el, n_qp, 1, 1), parameter.dtype class DivOperatorTerm(Term): r""" Weighted divergence term of a test function. :Definition: .. math:: \int_{\Omega} \nabla \cdot \ul{v} \mbox { or } \int_{\Omega} c \nabla \cdot \ul{v} :Arguments: - material : :math:`c` (optional) - virtual : :math:`\ul{v}` """ name = 'dw_div' arg_types = ('opt_material', 'virtual') arg_shapes = [{'opt_material' : '1, 1', 'virtual' : ('D', None)}, {'opt_material' : None}] @staticmethod def function(out, mat, vg): div_bf = vg.bfg n_el, n_qp, dim, n_ep = div_bf.shape div_bf = div_bf.reshape((n_el, n_qp, dim * n_ep, 1)) div_bf = nm.ascontiguousarray(div_bf) if mat is not None: status = vg.integrate(out, mat * div_bf) else: status = vg.integrate(out, div_bf) return status def get_fargs(self, mat, virtual, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(virtual) return mat, vg class GradDivStabilizationTerm(Term): r""" Grad-div stabilization term ( :math:`\gamma` is a global stabilization parameter). :Definition: .. math:: \gamma \int_{\Omega} (\nabla\cdot\ul{u}) \cdot (\nabla\cdot\ul{v}) :Arguments: - material : :math:`\gamma` - virtual : :math:`\ul{v}` - state : :math:`\ul{u}` """ name = 'dw_st_grad_div' arg_types = ('material', 'virtual', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D'} function = staticmethod(terms.dw_st_grad_div) def get_fargs(self, gamma, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) if diff_var is None: div = self.get(state, 'div') fmode = 0 else: div = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return div, gamma, vg, fmode from sfepy.terms.terms_diffusion import LaplaceTerm class PSPGPStabilizationTerm(LaplaceTerm): r""" PSPG stabilization term, pressure part ( :math:`\tau` is a local stabilization parameter), alias to Laplace term dw_laplace. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \tau_K\ \nabla p \cdot \nabla q :Arguments: - material : :math:`\tau_K` - virtual : :math:`q` - state : :math:`p` """ name = 'dw_st_pspg_p' class PSPGCStabilizationTerm(Term): r""" PSPG stabilization term, convective part ( :math:`\tau` is a local stabilization parameter). :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \tau_K\ ((\ul{b} \cdot \nabla) \ul{u}) \cdot \nabla q :Arguments: - material : :math:`\tau_K` - virtual : :math:`q` - parameter : :math:`\ul{b}` - state : :math:`\ul{u}` """ name = 'dw_st_pspg_c' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : (1, None), 'parameter' : 'D', 'state' : 'D'} function = staticmethod(terms.dw_st_pspg_c) def get_fargs(self, tau, virtual, parameter, state, mode=None, term_mode=None, diff_var=None, **kwargs): sap, svg = self.get_approximation(virtual) vap, vvg = self.get_approximation(state) val_qp = self.get(parameter, 'val') conn = vap.get_connectivity(self.region, self.integration) if diff_var is None: fmode = 0 else: fmode = 1 return val_qp, state(), tau, svg, vvg, conn, fmode class SUPGPStabilizationTerm(Term): r""" SUPG stabilization term, pressure part ( :math:`\delta` is a local stabilization parameter). :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ \nabla p\cdot ((\ul{b} \cdot \nabla) \ul{v}) :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - parameter : :math:`\ul{b}` - state : :math:`p` """ name = 'dw_st_supg_p' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', None), 'parameter' : 'D', 'state' : 1} function = staticmethod(terms.dw_st_supg_p) def get_fargs(self, delta, virtual, parameter, state, mode=None, term_mode=None, diff_var=None, **kwargs): vvg, _ = self.get_mapping(virtual) svg, _ = self.get_mapping(state) val_qp = self.get(parameter, 'val') if diff_var is None: grad = self.get(state, 'grad') fmode = 0 else: grad = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return val_qp, grad, delta, vvg, svg, fmode class SUPGCStabilizationTerm(Term): r""" SUPG stabilization term, convective part ( :math:`\delta` is a local stabilization parameter). :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ ((\ul{b} \cdot \nabla) \ul{u})\cdot ((\ul{b} \cdot \nabla) \ul{v}) :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - parameter : :math:`\ul{b}` - state : :math:`\ul{u}` """ name = 'dw_st_supg_c' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'parameter' : 'D', 'state' : 'D'} function = staticmethod(terms.dw_st_supg_c) def get_fargs(self, delta, virtual, parameter, state, mode=None, term_mode=None, diff_var=None, **kwargs): ap, vg = self.get_approximation(virtual) val_qp = self.get(parameter, 'val') conn = ap.get_connectivity(self.region, self.integration) if diff_var is None: fmode = 0 else: fmode = 1 return val_qp, state(), delta, vg, conn, fmode
[ "sfepy.linalg.dot_sequences" ]
[((11757, 11785), 'numpy.ascontiguousarray', 'nm.ascontiguousarray', (['div_bf'], {}), '(div_bf)\n', (11777, 11785), True, 'import numpy as nm\n'), ((1821, 1863), 'numpy.ones', 'nm.ones', (['(1, n_qp, 1, 1)'], {'dtype': 'nm.float64'}), '((1, n_qp, 1, 1), dtype=nm.float64)\n', (1828, 1863), True, 'import numpy as nm\n'), ((7094, 7136), 'numpy.ones', 'nm.ones', (['(1, n_qp, 1, 1)'], {'dtype': 'nm.float64'}), '((1, n_qp, 1, 1), dtype=nm.float64)\n', (7101, 7136), True, 'import numpy as nm\n'), ((13021, 13061), 'numpy.array', 'nm.array', (['[0]'], {'ndmin': '(4)', 'dtype': 'nm.float64'}), '([0], ndmin=4, dtype=nm.float64)\n', (13029, 13061), True, 'import numpy as nm\n'), ((15893, 15933), 'numpy.array', 'nm.array', (['[0]'], {'ndmin': '(4)', 'dtype': 'nm.float64'}), '([0], ndmin=4, dtype=nm.float64)\n', (15901, 15933), True, 'import numpy as nm\n'), ((1341, 1380), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['g1[..., None]', 'g2', '"""ATB"""'], {}), "(g1[..., None], g2, 'ATB')\n", (1354, 1380), False, 'from sfepy.linalg import dot_sequences\n'), ((2166, 2206), 'numpy.array', 'nm.array', (['[0]'], {'ndmin': '(4)', 'dtype': 'nm.float64'}), '([0], ndmin=4, dtype=nm.float64)\n', (2174, 2206), True, 'import numpy as nm\n'), ((4832, 4872), 'numpy.array', 'nm.array', (['[0]'], {'ndmin': '(4)', 'dtype': 'nm.float64'}), '([0], ndmin=4, dtype=nm.float64)\n', (4840, 4872), True, 'import numpy as nm\n'), ((7408, 7448), 'numpy.array', 'nm.array', (['[0]'], {'ndmin': '(4)', 'dtype': 'nm.float64'}), '([0], ndmin=4, dtype=nm.float64)\n', (7416, 7448), True, 'import numpy as nm\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 28 09:33:53 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, InitialCondition from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe import numpy as np helps = { 'show' : 'show the results figure', } 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/3d/fluid_mesh.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field_1 = Field.from_args(name='3_velocity', dtype=nm.float64, shape=3, region=omega, approx_order=1) field_2 = Field.from_args(name='pressure', dtype=nm.float64, shape=1, region=omega, approx_order=1) region_0 = domain.create_region(name='Walls1', select='vertices in (y < -0.049)', kind='facet') region_1 = domain.create_region(name='Walls2', select='vertices in (y > 0.049)', kind='facet') region_2 = domain.create_region(name='Inlet', select='vertices in (x < -0.499)', kind='facet') region_3 = domain.create_region(name='Outlet', select='vertices in (x > -0.499)', kind='facet') ebc_1 = EssentialBC(name='Walls1', region=region_0, dofs={'u.[0,1,2]' : 0.0}) ebc_2 = EssentialBC(name='Walls2', region=region_1, dofs={'u.[0,1,2]' : 0.0}) ebc_3 = EssentialBC(name='Inlet', region=region_2, dofs={'u.0' : 1.0, 'u.[1,2]' : 0.0}) ebc_4 = EssentialBC(name='Outlet', region=region_3, dofs={'p':0.0, 'u.[1,2]' : 0.0}) viscosity = Material(name='viscosity', value=1.25e-3) variable_1 = FieldVariable('u', 'unknown', field_1) variable_2 = FieldVariable(name='v', kind='test', field=field_1, primary_var_name='u') variable_3 = FieldVariable(name='p', kind='unknown', field=field_2) variable_4 = FieldVariable(name='q', kind='test', field=field_2, primary_var_name='p') integral_1 = Integral('i1', order=2) integral_2 = Integral('i2', order=3) t1 = Term.new(name='dw_div_grad(viscosity.value, v, u)', integral=integral_2, region=omega, viscosity=viscosity, v=variable_2, u=variable_1) t2 = Term.new(name='dw_convect(v, u)', integral=integral_2, region=omega, v=variable_2, u=variable_1) t3 = Term.new(name='dw_stokes(v, p)', integral=integral_1, region=omega, v=variable_2, p=variable_3) t4 = Term.new(name='dw_stokes(u, q)', integral=integral_1, region=omega, u=variable_1, q=variable_4) eq1 = Equation('balance', t1+t2-t3) eq2 = Equation('incompressibility', t4) eqs = Equations([eq1,eq2]) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({'i_max' : 20, 'eps_a' : 1e-8, 'eps_r' : 1.0, 'macheps' : 1e-16, 'lin_red' : 1e-2, 'ls_red' : 0.1, 'ls_red_warp' : 0.001, 'ls_on' : 0.99999, 'ls_min' : 1e-5, 'check' : 0, 'delta' : 1e-6}, lin_solver=ls, status=nls_status) pb = Problem('Navier-Stokes', equations=eqs) pb.set_bcs(ebcs=Conditions([ebc_1, ebc_2, ebc_3])) pb.set_solver(nls) status = IndexedStruct() state = pb.solve(status=status, save_results=True) out = state.create_output_dict() pb.save_state('Navier_Stokes.vtk', out=out) view = Viewer('Navier_Stokes.vtk') view(rel_scaling=2, is_scalar_bar=True, is_wireframe=True)
[ "sfepy.discrete.Equations", "sfepy.discrete.conditions.EssentialBC", "sfepy.solvers.ls.ScipyDirect", "sfepy.discrete.Equation", "sfepy.solvers.nls.Newton", "sfepy.discrete.conditions.Conditions", "sfepy.discrete.fem.Mesh.from_file", "sfepy.discrete.Integral", "sfepy.discrete.fem.Field.from_args", ...
[((253, 273), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (268, 273), False, 'import sys\n'), ((912, 928), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (926, 928), False, 'from argparse import ArgumentParser\n'), ((1183, 1237), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (["(data_dir + '/meshes/3d/fluid_mesh.inp')"], {}), "(data_dir + '/meshes/3d/fluid_mesh.inp')\n", (1197, 1237), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1247, 1271), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""domain"""', 'mesh'], {}), "('domain', mesh)\n", (1255, 1271), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1328, 1423), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', ([], {'name': '"""3_velocity"""', 'dtype': 'nm.float64', 'shape': '(3)', 'region': 'omega', 'approx_order': '(1)'}), "(name='3_velocity', dtype=nm.float64, shape=3, region=omega,\n approx_order=1)\n", (1343, 1423), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1430, 1523), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', ([], {'name': '"""pressure"""', 'dtype': 'nm.float64', 'shape': '(1)', 'region': 'omega', 'approx_order': '(1)'}), "(name='pressure', dtype=nm.float64, shape=1, region=omega,\n approx_order=1)\n", (1445, 1523), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1912, 1980), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', ([], {'name': '"""Walls1"""', 'region': 'region_0', 'dofs': "{'u.[0,1,2]': 0.0}"}), "(name='Walls1', region=region_0, dofs={'u.[0,1,2]': 0.0})\n", (1923, 1980), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC, InitialCondition\n'), ((1990, 2058), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', ([], {'name': '"""Walls2"""', 'region': 'region_1', 'dofs': "{'u.[0,1,2]': 0.0}"}), "(name='Walls2', region=region_1, dofs={'u.[0,1,2]': 0.0})\n", (2001, 2058), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC, InitialCondition\n'), ((2068, 2145), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', ([], {'name': '"""Inlet"""', 'region': 'region_2', 'dofs': "{'u.0': 1.0, 'u.[1,2]': 0.0}"}), "(name='Inlet', region=region_2, dofs={'u.0': 1.0, 'u.[1,2]': 0.0})\n", (2079, 2145), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC, InitialCondition\n'), ((2156, 2232), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', ([], {'name': '"""Outlet"""', 'region': 'region_3', 'dofs': "{'p': 0.0, 'u.[1,2]': 0.0}"}), "(name='Outlet', region=region_3, dofs={'p': 0.0, 'u.[1,2]': 0.0})\n", (2167, 2232), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC, InitialCondition\n'), ((2246, 2287), 'sfepy.discrete.Material', 'Material', ([], {'name': '"""viscosity"""', 'value': '(0.00125)'}), "(name='viscosity', value=0.00125)\n", (2254, 2287), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2302, 2340), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""u"""', '"""unknown"""', 'field_1'], {}), "('u', 'unknown', field_1)\n", (2315, 2340), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2354, 2427), 'sfepy.discrete.FieldVariable', 'FieldVariable', ([], {'name': '"""v"""', 'kind': '"""test"""', 'field': 'field_1', 'primary_var_name': '"""u"""'}), "(name='v', kind='test', field=field_1, primary_var_name='u')\n", (2367, 2427), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2441, 2495), 'sfepy.discrete.FieldVariable', 'FieldVariable', ([], {'name': '"""p"""', 'kind': '"""unknown"""', 'field': 'field_2'}), "(name='p', kind='unknown', field=field_2)\n", (2454, 2495), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2509, 2582), 'sfepy.discrete.FieldVariable', 'FieldVariable', ([], {'name': '"""q"""', 'kind': '"""test"""', 'field': 'field_2', 'primary_var_name': '"""p"""'}), "(name='q', kind='test', field=field_2, primary_var_name='p')\n", (2522, 2582), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2597, 2620), 'sfepy.discrete.Integral', 'Integral', (['"""i1"""'], {'order': '(2)'}), "('i1', order=2)\n", (2605, 2620), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2634, 2657), 'sfepy.discrete.Integral', 'Integral', (['"""i2"""'], {'order': '(3)'}), "('i2', order=3)\n", (2642, 2657), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2664, 2803), 'sfepy.terms.Term.new', 'Term.new', ([], {'name': '"""dw_div_grad(viscosity.value, v, u)"""', 'integral': 'integral_2', 'region': 'omega', 'viscosity': 'viscosity', 'v': 'variable_2', 'u': 'variable_1'}), "(name='dw_div_grad(viscosity.value, v, u)', integral=integral_2,\n region=omega, viscosity=viscosity, v=variable_2, u=variable_1)\n", (2672, 2803), False, 'from sfepy.terms import Term\n'), ((2819, 2920), 'sfepy.terms.Term.new', 'Term.new', ([], {'name': '"""dw_convect(v, u)"""', 'integral': 'integral_2', 'region': 'omega', 'v': 'variable_2', 'u': 'variable_1'}), "(name='dw_convect(v, u)', integral=integral_2, region=omega, v=\n variable_2, u=variable_1)\n", (2827, 2920), False, 'from sfepy.terms import Term\n'), ((2935, 3035), 'sfepy.terms.Term.new', 'Term.new', ([], {'name': '"""dw_stokes(v, p)"""', 'integral': 'integral_1', 'region': 'omega', 'v': 'variable_2', 'p': 'variable_3'}), "(name='dw_stokes(v, p)', integral=integral_1, region=omega, v=\n variable_2, p=variable_3)\n", (2943, 3035), False, 'from sfepy.terms import Term\n'), ((3050, 3150), 'sfepy.terms.Term.new', 'Term.new', ([], {'name': '"""dw_stokes(u, q)"""', 'integral': 'integral_1', 'region': 'omega', 'u': 'variable_1', 'q': 'variable_4'}), "(name='dw_stokes(u, q)', integral=integral_1, region=omega, u=\n variable_1, q=variable_4)\n", (3058, 3150), False, 'from sfepy.terms import Term\n'), ((3166, 3199), 'sfepy.discrete.Equation', 'Equation', (['"""balance"""', '(t1 + t2 - t3)'], {}), "('balance', t1 + t2 - t3)\n", (3174, 3199), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((3202, 3235), 'sfepy.discrete.Equation', 'Equation', (['"""incompressibility"""', 't4'], {}), "('incompressibility', t4)\n", (3210, 3235), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((3242, 3263), 'sfepy.discrete.Equations', 'Equations', (['[eq1, eq2]'], {}), '([eq1, eq2])\n', (3251, 3263), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((3269, 3284), 'sfepy.solvers.ls.ScipyDirect', 'ScipyDirect', (['{}'], {}), '({})\n', (3280, 3284), False, 'from sfepy.solvers.ls import ScipyDirect\n'), ((3298, 3313), 'sfepy.base.base.IndexedStruct', 'IndexedStruct', ([], {}), '()\n', (3311, 3313), False, 'from sfepy.base.base import IndexedStruct, Struct\n'), ((3320, 3553), 'sfepy.solvers.nls.Newton', 'Newton', (["{'i_max': 20, 'eps_a': 1e-08, 'eps_r': 1.0, 'macheps': 1e-16, 'lin_red': \n 0.01, 'ls_red': 0.1, 'ls_red_warp': 0.001, 'ls_on': 0.99999, 'ls_min': \n 1e-05, 'check': 0, 'delta': 1e-06}"], {'lin_solver': 'ls', 'status': 'nls_status'}), "({'i_max': 20, 'eps_a': 1e-08, 'eps_r': 1.0, 'macheps': 1e-16,\n 'lin_red': 0.01, 'ls_red': 0.1, 'ls_red_warp': 0.001, 'ls_on': 0.99999,\n 'ls_min': 1e-05, 'check': 0, 'delta': 1e-06}, lin_solver=ls, status=\n nls_status)\n", (3326, 3553), False, 'from sfepy.solvers.nls import Newton\n'), ((3554, 3593), 'sfepy.discrete.Problem', 'Problem', (['"""Navier-Stokes"""'], {'equations': 'eqs'}), "('Navier-Stokes', equations=eqs)\n", (3561, 3593), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((3673, 3688), 'sfepy.base.base.IndexedStruct', 'IndexedStruct', ([], {}), '()\n', (3686, 3688), False, 'from sfepy.base.base import IndexedStruct, Struct\n'), ((3826, 3853), 'sfepy.postprocess.viewer.Viewer', 'Viewer', (['"""Navier_Stokes.vtk"""'], {}), "('Navier_Stokes.vtk')\n", (3832, 3853), False, 'from sfepy.postprocess.viewer import Viewer\n'), ((3610, 3643), 'sfepy.discrete.conditions.Conditions', 'Conditions', (['[ebc_1, ebc_2, ebc_3]'], {}), '([ebc_1, ebc_2, ebc_3])\n', (3620, 3643), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC, InitialCondition\n')]
r""" Piezo-elasticity problem - linear elastic material with piezoelectric effects. Find :math:`\ul{u}`, :math:`\phi` such that: .. math:: - \omega^2 \int_{Y} \rho\ \ul{v} \cdot \ul{u} + \int_{Y} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) - \int_{Y_2} g_{kij}\ e_{ij}(\ul{v}) \nabla_k \phi = 0 \;, \quad \forall \ul{v} \;, \int_{Y_2} g_{kij}\ e_{ij}(\ul{u}) \nabla_k \psi + \int_{Y} K_{ij} \nabla_i \psi \nabla_j \phi = 0 \;, \quad \forall \psi \;, where .. math:: D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) + \lambda \ \delta_{ij} \delta_{kl} \;. """ import os import numpy as nm from sfepy import data_dir from sfepy.discrete.fem import MeshIO filename_mesh = data_dir + '/meshes/2d/special/circle_in_square.mesh' ## filename_mesh = data_dir + '/meshes/2d/special/circle_in_square_small.mesh' ## filename_mesh = data_dir + '/meshes/3d/special/cube_sphere.mesh' ## filename_mesh = data_dir + '/meshes/2d/special/cube_cylinder.mesh' omega = 1 omega_squared = omega**2 conf_dir = os.path.dirname(__file__) io = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir) bbox, dim = io.read_bounding_box( ret_dim = True ) geom = {3 : '3_4', 2 : '2_3'}[dim] x_left, x_right = bbox[:,0] regions = { 'Y' : 'all', 'Y1' : 'cells of group 1', 'Y2' : 'cells of group 2', 'Y2_Surface': ('r.Y1 *v r.Y2', 'facet'), 'Left' : ('vertices in (x < %f)' % (x_left + 1e-3), 'facet'), 'Right' : ('vertices in (x > %f)' % (x_right - 1e-3), 'facet'), } material_2 = { 'name' : 'inclusion', # epoxy 'function' : 'get_inclusion_pars', } 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 } for key, val in out.iteritems(): out[key] = nm.tile(val, (coor.shape[0], 1, 1)) return out functions = { 'get_inclusion_pars' : (get_inclusion_pars,), } field_0 = { 'name' : 'displacement', 'dtype' : nm.float64, 'shape' : dim, 'region' : 'Y', 'approx_order' : 1, } field_2 = { 'name' : 'potential', 'dtype' : nm.float64, 'shape' : (1,), 'region' : 'Y', 'approx_order' : 1, } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), 'phi' : ('unknown field', 'potential', 1), 'psi' : ('test field', 'potential', 'phi'), } ebcs = { 'u1' : ('Left', {'u.all' : 0.0}), 'u2' : ('Right', {'u.0' : 0.1}), 'phi' : ('Y2_Surface', {'phi.all' : 0.0}), } integral_1 = { 'name' : 'i', 'order' : 2, } equations = { '1' : """- %f * dw_volume_dot.i.Y( inclusion.density, v, u ) + dw_lin_elastic_iso.i.Y( inclusion.lam, inclusion.mu, v, u ) - dw_piezo_coupling.i.Y2( inclusion.coupling, v, phi ) = 0""" % omega_squared, '2' : """dw_piezo_coupling.i.Y2( inclusion.coupling, u, psi ) + dw_diffusion.i.Y( inclusion.dielectric, psi, phi ) = 0""", } ## # Solvers etc. solver_0 = { 'name' : 'ls', 'kind' : 'ls.scipy_direct', } solver_1 = { 'name' : 'newton', 'kind' : 'nls.newton', 'i_max' : 1, 'eps_a' : 1e-10, 'eps_r' : 1.0, 'macheps' : 1e-16, 'lin_red' : 1e-2, # Linear system error < (eps_a * lin_red). 'ls_red' : 0.1, 'ls_red_warp': 0.001, 'ls_on' : 1.1, 'ls_min' : 1e-5, 'check' : 0, 'delta' : 1e-6, 'problem' : 'nonlinear', # 'nonlinear' or 'linear' (ignore i_max) }
[ "sfepy.discrete.fem.MeshIO.any_from_filename" ]
[((1055, 1080), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1070, 1080), False, 'import os\n'), ((1086, 1146), 'sfepy.discrete.fem.MeshIO.any_from_filename', 'MeshIO.any_from_filename', (['filename_mesh'], {'prefix_dir': 'conf_dir'}), '(filename_mesh, prefix_dir=conf_dir)\n', (1110, 1146), False, 'from sfepy.discrete.fem import MeshIO\n'), ((1884, 1913), 'numpy.eye', 'nm.eye', (['dim'], {'dtype': 'nm.float64'}), '(dim, dtype=nm.float64)\n', (1890, 1913), True, 'import numpy as nm\n'), ((1951, 1988), 'numpy.ones', 'nm.ones', (['(dim, sym)'], {'dtype': 'nm.float64'}), '((dim, sym), dtype=nm.float64)\n', (1958, 1988), True, 'import numpy as nm\n'), ((2407, 2442), 'numpy.tile', 'nm.tile', (['val', '(coor.shape[0], 1, 1)'], {}), '(val, (coor.shape[0], 1, 1))\n', (2414, 2442), True, 'import numpy as nm\n')]
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.mesh --remesh='q2/0 a1e-8 O9/7 V' $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new2.mesh --remesh='rq2/0 a1e-8 O9/7 V' """ from __future__ import absolute_import import sys import os.path as op from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter from sfepy.base.base import nm, output from sfepy.base.ioutils import remove_files from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) from sfepy.discrete.fem.mesh import fix_double_nodes from sfepy.mesh.mesh_tools import elems_q2t helps = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %(default)s]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %(default)s]', 'refine' : 'uniform refinement level [default: %(default)s]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', 'merge' : 'remove duplicate vertices', 'tri-tetra' : 'convert elements: quad->tri, hexa->tetra', '2d' : 'force a 2D mesh by removing the z coordinates - assumes a 3D mesh' ' in the xy plane', 'save-per-mat': 'extract cells by material id and save them into' ' separate mesh files with a name based on filename_out and the id' ' numbers (preserves original mesh vertices)', 'remesh' : """when given, remesh the given mesh using tetgen. The options can be the following, separated by spaces, in this order: 1. "r" causes remeshing of the mesh volume - if not present the mesh surface is extracted and used for the volume mesh generation. 2. "q[<float>/<float>]" (required) - the two numbers after "q" are a maximum radius-edge ratio bound and a minimum dihedral angle bound. 3. "a<float>" (optional) - the number imposes a maximum volume constraint on all tetrahedra. 4. O[<0-9>/<0-7>] - the two numbers correspond to a mesh optimization level and a choice of optimizing operations. 5. "V" (optional) - if present, mesh statistics are printed. Consult the tetgen documentation for details.""", } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=helps['scale']) parser.add_argument('-c', '--center', metavar='center', action='store', dest='center', default=None, help=helps['center']) parser.add_argument('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=helps['refine']) parser.add_argument('-f', '--format', metavar='format', action='store', type=str, dest='format', default=None, help=helps['format']) parser.add_argument('-l', '--list', action='store_true', dest='list', help=helps['list']) parser.add_argument('-m', '--merge', action='store_true', dest='merge', help=helps['merge']) parser.add_argument('-t', '--tri-tetra', action='store_true', dest='tri_tetra', help=helps['tri-tetra']) parser.add_argument('-2', '--2d', action='store_true', dest='force_2d', help=helps['2d']) parser.add_argument('--save-per-mat', action='store_true', dest='save_per_mat', help=helps['save-per-mat']) parser.add_argument('--remesh', metavar='options', action='store', dest='remesh', default=None, help=helps['remesh']) parser.add_argument('filename_in') parser.add_argument('filename_out') options = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r') output('') output('Supported writable mesh formats:') output('--------------------------------') output_mesh_formats('w') sys.exit(0) scale = _parse_val_or_vec(options.scale, 'scale', parser) center = _parse_val_or_vec(options.center, 'center', parser) filename_in = options.filename_in filename_out = options.filename_out if options.remesh: import tempfile import shlex import subprocess dirname = tempfile.mkdtemp() is_surface = options.remesh.startswith('q') if is_surface: mesh = Mesh.from_file(filename_in) domain = FEDomain(mesh.name, mesh) region = domain.create_region('surf', 'vertices of surface', 'facet') surf_mesh = Mesh.from_region(region, mesh, localize=True, is_surface=True) filename = op.join(dirname, 'surf.mesh') surf_mesh.write(filename, io='auto') else: import shutil shutil.copy(filename_in, dirname) filename = op.join(dirname, op.basename(filename_in)) qopts = ''.join(options.remesh.split()) # Remove spaces. command = 'tetgen -BFENkACp%s %s' % (qopts, filename) args = shlex.split(command) subprocess.call(args) root, ext = op.splitext(filename) mesh = Mesh.from_file(root + '.1.vtk') remove_files(dirname) else: mesh = Mesh.from_file(filename_in) if options.force_2d: data = list(mesh._get_io_data()) data[0] = data[0][:, :2] mesh = Mesh.from_data(mesh.name, *data) if scale is not None: if len(scale) == 1: tr = nm.eye(mesh.dim, dtype=nm.float64) * scale elif len(scale) == mesh.dim: tr = nm.diag(scale) else: raise ValueError('bad scale! (%s)' % scale) mesh.transform_coors(tr) if center is not None: cc = 0.5 * mesh.get_bounding_box().sum(0) shift = center - cc tr = nm.c_[nm.eye(mesh.dim, dtype=nm.float64), shift[:, None]] mesh.transform_coors(tr) if options.refine > 0: domain = FEDomain(mesh.name, mesh) output('initial mesh: %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) mesh = domain.mesh if options.tri_tetra > 0: 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) 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]) mesh = Mesh.from_data(mesh.name, mesh.coors, mesh.cmesh.vertex_groups, [new_conns], [new_cgroups], [new_desc]) if options.merge: desc = mesh.descs[0] coor, ngroups, conns = fix_double_nodes(mesh.coors, mesh.cmesh.vertex_groups, mesh.get_conn(desc), 1e-9) mesh = Mesh.from_data(mesh.name + '_merged', coor, ngroups, [conns], [mesh.cmesh.cell_groups], [desc]) if options.save_per_mat: desc = mesh.descs[0] conns, cgroups = mesh.get_conn(desc), mesh.cmesh.cell_groups coors, ngroups = mesh.coors, mesh.cmesh.vertex_groups mat_ids = nm.unique(cgroups) for mat_id in mat_ids: idxs = nm.where(cgroups == mat_id)[0] imesh = Mesh.from_data(mesh.name + '_matid_%d' % mat_id, coors, ngroups, [conns[idxs]], [cgroups[idxs]], [desc]) fbase, fext = op.splitext(filename_out) ifilename_out = '%s_matid_%d%s' % (fbase, mat_id, fext) io = MeshIO.for_format(ifilename_out, format=options.format, writable=True) output('writing %s...' % ifilename_out) imesh.write(ifilename_out, io=io) output('...done') io = MeshIO.for_format(filename_out, format=options.format, writable=True) cell_types = ', '.join(supported_cell_types[io.format]) output('writing [%s] %s...' % (cell_types, filename_out)) mesh.write(filename_out, io=io) output('...done') if __name__ == '__main__': main()
[ "sfepy.base.base.nm.eye", "sfepy.base.base.nm.repeat", "sfepy.discrete.fem.meshio.output_mesh_formats", "sfepy.discrete.fem.Mesh.from_region", "sfepy.discrete.fem.Mesh.from_file", "sfepy.discrete.fem.FEDomain", "sfepy.base.base.output", "sfepy.discrete.fem.Mesh.from_data", "sfepy.base.base.nm.array"...
[((665, 685), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (680, 685), False, 'import sys\n'), ((3246, 3331), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '__doc__', 'formatter_class': 'RawDescriptionHelpFormatter'}), '(description=__doc__, formatter_class=RawDescriptionHelpFormatter\n )\n', (3260, 3331), False, 'from argparse import ArgumentParser, RawDescriptionHelpFormatter\n'), ((9829, 9898), 'sfepy.discrete.fem.meshio.MeshIO.for_format', 'MeshIO.for_format', (['filename_out'], {'format': 'options.format', 'writable': '(True)'}), '(filename_out, format=options.format, writable=True)\n', (9846, 9898), False, 'from sfepy.discrete.fem.meshio import output_mesh_formats, MeshIO, supported_cell_types\n'), ((9991, 10048), 'sfepy.base.base.output', 'output', (["('writing [%s] %s...' % (cell_types, filename_out))"], {}), "('writing [%s] %s...' % (cell_types, filename_out))\n", (9997, 10048), False, 'from sfepy.base.base import nm, output\n'), ((10089, 10106), 'sfepy.base.base.output', 'output', (['"""...done"""'], {}), "('...done')\n", (10095, 10106), False, 'from sfepy.base.base import nm, output\n'), ((5006, 5048), 'sfepy.base.base.output', 'output', (['"""Supported readable mesh formats:"""'], {}), "('Supported readable mesh formats:')\n", (5012, 5048), False, 'from sfepy.base.base import nm, output\n'), ((5057, 5099), 'sfepy.base.base.output', 'output', (['"""--------------------------------"""'], {}), "('--------------------------------')\n", (5063, 5099), False, 'from sfepy.base.base import nm, output\n'), ((5108, 5132), 'sfepy.discrete.fem.meshio.output_mesh_formats', 'output_mesh_formats', (['"""r"""'], {}), "('r')\n", (5127, 5132), False, 'from sfepy.discrete.fem.meshio import output_mesh_formats, MeshIO, supported_cell_types\n'), ((5141, 5151), 'sfepy.base.base.output', 'output', (['""""""'], {}), "('')\n", (5147, 5151), False, 'from sfepy.base.base import nm, output\n'), ((5160, 5202), 'sfepy.base.base.output', 'output', (['"""Supported writable mesh formats:"""'], {}), "('Supported writable mesh formats:')\n", (5166, 5202), False, 'from sfepy.base.base import nm, output\n'), ((5211, 5253), 'sfepy.base.base.output', 'output', (['"""--------------------------------"""'], {}), "('--------------------------------')\n", (5217, 5253), False, 'from sfepy.base.base import nm, output\n'), ((5262, 5286), 'sfepy.discrete.fem.meshio.output_mesh_formats', 'output_mesh_formats', (['"""w"""'], {}), "('w')\n", (5281, 5286), False, 'from sfepy.discrete.fem.meshio import output_mesh_formats, MeshIO, supported_cell_types\n'), ((5295, 5306), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (5303, 5306), False, 'import sys\n'), ((5628, 5646), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (5644, 5646), False, 'import tempfile\n'), ((6469, 6489), 'shlex.split', 'shlex.split', (['command'], {}), '(command)\n', (6480, 6489), False, 'import shlex\n'), ((6498, 6519), 'subprocess.call', 'subprocess.call', (['args'], {}), '(args)\n', (6513, 6519), False, 'import subprocess\n'), ((6541, 6562), 'os.path.splitext', 'op.splitext', (['filename'], {}), '(filename)\n', (6552, 6562), True, 'import os.path as op\n'), ((6578, 6609), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (["(root + '.1.vtk')"], {}), "(root + '.1.vtk')\n", (6592, 6609), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((6619, 6640), 'sfepy.base.ioutils.remove_files', 'remove_files', (['dirname'], {}), '(dirname)\n', (6631, 6640), False, 'from sfepy.base.ioutils import remove_files\n'), ((6667, 6694), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['filename_in'], {}), '(filename_in)\n', (6681, 6694), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((6810, 6842), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (['mesh.name', '*data'], {}), '(mesh.name, *data)\n', (6824, 6842), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((7385, 7410), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['mesh.name', 'mesh'], {}), '(mesh.name, mesh)\n', (7393, 7410), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((7419, 7510), 'sfepy.base.base.output', 'output', (["('initial mesh: %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)\n )"], {}), "('initial mesh: %d nodes %d elements' % (domain.shape.n_nod, domain.\n shape.n_el))\n", (7425, 7510), False, 'from sfepy.base.base import nm, output\n'), ((7540, 7561), 'six.moves.range', 'range', (['options.refine'], {}), '(options.refine)\n', (7545, 7561), False, 'from six.moves import range\n'), ((8787, 8887), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (["(mesh.name + '_merged')", 'coor', 'ngroups', '[conns]', '[mesh.cmesh.cell_groups]', '[desc]'], {}), "(mesh.name + '_merged', coor, ngroups, [conns], [mesh.cmesh.\n cell_groups], [desc])\n", (8801, 8887), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((9151, 9169), 'sfepy.base.base.nm.unique', 'nm.unique', (['cgroups'], {}), '(cgroups)\n', (9160, 9169), False, 'from sfepy.base.base import nm, output\n'), ((3033, 3076), 'sfepy.base.base.nm.array', 'nm.array', (['option'], {'dtype': 'nm.float64', 'ndmin': '(1)'}), '(option, dtype=nm.float64, ndmin=1)\n', (3041, 3076), False, 'from sfepy.base.base import nm, output\n'), ((5742, 5769), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['filename_in'], {}), '(filename_in)\n', (5756, 5769), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((5791, 5816), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['mesh.name', 'mesh'], {}), '(mesh.name, mesh)\n', (5799, 5816), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((5965, 6027), 'sfepy.discrete.fem.Mesh.from_region', 'Mesh.from_region', (['region', 'mesh'], {'localize': '(True)', 'is_surface': '(True)'}), '(region, mesh, localize=True, is_surface=True)\n', (5981, 6027), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((6093, 6122), 'os.path.join', 'op.join', (['dirname', '"""surf.mesh"""'], {}), "(dirname, 'surf.mesh')\n", (6100, 6122), True, 'import os.path as op\n'), ((6226, 6259), 'shutil.copy', 'shutil.copy', (['filename_in', 'dirname'], {}), '(filename_in, dirname)\n', (6237, 6259), False, 'import shutil\n'), ((7575, 7602), 'sfepy.base.base.output', 'output', (["('refine %d...' % ii)"], {}), "('refine %d...' % ii)\n", (7581, 7602), False, 'from sfepy.base.base import nm, output\n'), ((7652, 7728), 'sfepy.base.base.output', 'output', (["('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el))"], {}), "('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el))\n", (7658, 7728), False, 'from sfepy.base.base import nm, output\n'), ((8061, 8103), 'sfepy.base.base.output', 'output', (["('initial mesh: %d elements' % nelo)"], {}), "('initial mesh: %d elements' % nelo)\n", (8067, 8103), False, 'from sfepy.base.base import nm, output\n'), ((8129, 8145), 'sfepy.mesh.mesh_tools.elems_q2t', 'elems_q2t', (['conns'], {}), '(conns)\n', (8138, 8145), False, 'from sfepy.mesh.mesh_tools import elems_q2t\n'), ((8216, 8253), 'sfepy.base.base.nm.repeat', 'nm.repeat', (['mesh.cmesh.cell_groups', 'nn'], {}), '(mesh.cmesh.cell_groups, nn)\n', (8225, 8253), False, 'from sfepy.base.base import nm, output\n'), ((8267, 8319), 'sfepy.base.base.output', 'output', (["('new mesh: %d elements' % new_conns.shape[0])"], {}), "('new mesh: %d elements' % new_conns.shape[0])\n", (8273, 8319), False, 'from sfepy.base.base import nm, output\n'), ((8339, 8446), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (['mesh.name', 'mesh.coors', 'mesh.cmesh.vertex_groups', '[new_conns]', '[new_cgroups]', '[new_desc]'], {}), '(mesh.name, mesh.coors, mesh.cmesh.vertex_groups, [new_conns],\n [new_cgroups], [new_desc])\n', (8353, 8446), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((9272, 9381), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (["(mesh.name + '_matid_%d' % mat_id)", 'coors', 'ngroups', '[conns[idxs]]', '[cgroups[idxs]]', '[desc]'], {}), "(mesh.name + '_matid_%d' % mat_id, coors, ngroups, [conns[\n idxs]], [cgroups[idxs]], [desc])\n", (9286, 9381), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((9474, 9499), 'os.path.splitext', 'op.splitext', (['filename_out'], {}), '(filename_out)\n', (9485, 9499), True, 'import os.path as op\n'), ((9585, 9655), 'sfepy.discrete.fem.meshio.MeshIO.for_format', 'MeshIO.for_format', (['ifilename_out'], {'format': 'options.format', 'writable': '(True)'}), '(ifilename_out, format=options.format, writable=True)\n', (9602, 9655), False, 'from sfepy.discrete.fem.meshio import output_mesh_formats, MeshIO, supported_cell_types\n'), ((9703, 9742), 'sfepy.base.base.output', 'output', (["('writing %s...' % ifilename_out)"], {}), "('writing %s...' % ifilename_out)\n", (9709, 9742), False, 'from sfepy.base.base import nm, output\n'), ((9801, 9818), 'sfepy.base.base.output', 'output', (['"""...done"""'], {}), "('...done')\n", (9807, 9818), False, 'from sfepy.base.base import nm, output\n'), ((3105, 3144), 'sfepy.base.base.output', 'output', (["('bad %s! (%s)' % (name, option))"], {}), "('bad %s! (%s)' % (name, option))\n", (3111, 3144), False, 'from sfepy.base.base import nm, output\n'), ((3189, 3200), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3197, 3200), False, 'import sys\n'), ((6300, 6324), 'os.path.basename', 'op.basename', (['filename_in'], {}), '(filename_in)\n', (6311, 6324), True, 'import os.path as op\n'), ((6915, 6949), 'sfepy.base.base.nm.eye', 'nm.eye', (['mesh.dim'], {'dtype': 'nm.float64'}), '(mesh.dim, dtype=nm.float64)\n', (6921, 6949), False, 'from sfepy.base.base import nm, output\n'), ((7012, 7026), 'sfepy.base.base.nm.diag', 'nm.diag', (['scale'], {}), '(scale)\n', (7019, 7026), False, 'from sfepy.base.base import nm, output\n'), ((7255, 7289), 'sfepy.base.base.nm.eye', 'nm.eye', (['mesh.dim'], {'dtype': 'nm.float64'}), '(mesh.dim, dtype=nm.float64)\n', (7261, 7289), False, 'from sfepy.base.base import nm, output\n'), ((9221, 9248), 'sfepy.base.base.nm.where', 'nm.where', (['(cgroups == mat_id)'], {}), '(cgroups == mat_id)\n', (9229, 9248), False, 'from sfepy.base.base import nm, output\n')]
# This example implements macroscopic homogenized model of Biot-Darcy-Brinkman model of flow in deformable # double porous media. # The mathematical model is described in: # #<NAME>., <NAME>., <NAME>. #The Biot-Darcy-Brinkman model of flow in deformable double porous media; homogenization and numerical modelling. # Computers and Mathematics with applications, 78(9):3044-3066, 2019, # https://doi.org/10.1016/j.camwa.2019.04.004 # # Run simulation: # # ./simple.py example_perfusion_BDB/perf_BDB_mac.py # # The results are stored in `example_perfusion_BDB/results/macro` directory. # import numpy as nm from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.utils import define_box_regions from sfepy.discrete.fem.mesh import Mesh import os.path as osp material_cache = {} data_dir = 'example_perfusion_BDB' def coefs2qp(coefs, nqp): out = {} for k, v in coefs.items(): if type(v) not in [nm.ndarray, float]: continue if type(v) is nm.ndarray: if len(v.shape) >= 3: out[k] = v out[k] = nm.tile(v, (nqp, 1, 1)) return out # Get raw homogenized coefficients, recalculate them if necessary def get_raw_coefs(problem): if 'raw_coefs' not in material_cache: micro_filename = material_cache['meso_filename'] coefs_filename = 'coefs_meso' coefs_filename = osp.join(problem.conf.options.get('output_dir', '.'), coefs_filename) + '.h5' coefs = get_homog_coefs_linear(0, 0, None, micro_filename=micro_filename, coefs_filename=coefs_filename) coefs['B'] = coefs['B'][:, nm.newaxis] material_cache['raw_coefs'] = coefs return material_cache['raw_coefs'] #Get homogenized coefficients in quadrature points def get_homog(coors,pb, mode, **kwargs): if not (mode == 'qp'): return nqp = coors.shape[0] coefs=get_raw_coefs(pb) for k in coefs.keys(): v = coefs[k] if type(v) is nm.ndarray: if len(v.shape) == 0: coefs[k] = v.reshape((1, 1)) elif len(v.shape) == 1: coefs[k] = v[:, nm.newaxis] elif isinstance(v, float): coefs[k] = nm.array([[v]]) out = coefs2qp(coefs, nqp) return out #Definition of dirichlet boundary conditions def get_ebc( coors, amplitude, cg1, cg2,const=False): """ Define the essential boundary conditions as a function of coordinates `coors` of region nodes. """ y = coors[:, 1] - cg1 z = coors[:, 2] - cg2 val = amplitude*((cg1**2 - (abs(y)**2))+(cg2**2 - (abs(z)**2))) if const: val=nm.ones_like(y) *amplitude return val #Returns value of \phi_c\bar{w}^{mes} as a material function def get_ebc_mat( coors,pb, mode, amplitude, cg1, cg2,konst=False): if mode == 'qp': val = get_ebc( coors, amplitude, cg1, cg2,konst) phic = get_raw_coefs(pb)['vol']["fraction_Zc"] v_w1 = val[:, nm.newaxis, nm.newaxis] return {'val': v_w1*phic} #Definition of boundary conditions for numerical example at http://sfepy.org/sfepy_examples/example_perfusion_BDB/ def define_bc(cg1,cg2, val_in=1e2, val_out=1e2): funs = { 'w_in': (lambda ts, coor, bc, problem, **kwargs: get_ebc( coor, val_in, cg1, cg2),), 'w_out': (lambda ts, coor, bc, problem, **kwargs: get_ebc( coor, val_out, cg1, cg2),), 'w_in_mat': (lambda ts,coor, problem, mode=None, **kwargs: get_ebc_mat( coor, problem, mode, val_in, cg1, cg2),), 'w_out_mat': (lambda ts,coor, problem, mode=None, **kwargs: get_ebc_mat( coor, problem, mode, val_out, cg1, cg2),), } mats = { 'w_in': 'w_in_mat', 'w_out': 'w_out_mat', } ebcs = { 'fix_u_in': ('In', {'u.all': 0.0}), 'fix_u_out': ('Out', {'u.all': 0.0}), 'w_in': ('In', {'w.0': 'w_in','w.[1,2]': 0.0}), 'w_out': ('Out', {'w.0': 'w_out','w.[1,2]': 0.0}), 'wB_dirichlet':('Bottom',{'w.2' :0.0,'u.2':0.0}), 'WT_dirichlet':('Top',{'w.2' :0.0,'u.2':0.0}), 'wN_dirichlet':('Near',{'w.1' :0.0,'u.1':0.0}), 'wF_dirichlet':('Far',{'w.1' :0.0,'u.1':0.0}), } lcbcs = { 'imv': ('Omega', {'ls.all' : None}, None, 'integral_mean_value') } return ebcs, funs, mats, lcbcs #Definition of macroscopic problem def define(filename_mesh=None,cg1=None, cg2=None): if filename_mesh is None: filename_mesh = osp.join(data_dir, 'macro_perf.vtk') cg1, cg2 = 0.0015, 0.0015 # y and z coordinates of center of gravity mesh = Mesh.from_file(filename_mesh) poroela_mezo_file = osp.join(data_dir,'perf_BDB_mes.py') material_cache['meso_filename']=poroela_mezo_file bbox = mesh.get_bounding_box() regions = define_box_regions(mesh.dim, bbox[0], bbox[1], eps=1e-6) regions.update({ 'Omega': 'all', 'Wall': ('r.Top +v r.Bottom +v r.Far +v r.Near', 'facet'), 'In': ('r.Left -v r.Wall', 'facet'), 'Out': ('r.Right -v r.Wall', 'facet'), }) ebcs, bc_funs, mats, lcbcs = define_bc(cg1,cg2,val_in=1.e4,val_out=1.e4) fields = { 'displacement': ('real', 'vector', 'Omega', 1), 'pressure': ('real', 'scalar', 'Omega', 1), 'velocity': ('real', 'vector', 'Omega', 2), } variables = { #Displacement 'u': ('unknown field', 'displacement'), 'v': ('test field', 'displacement', 'u'), #Pressure 'p': ('unknown field', 'pressure'), 'q': ('test field', 'pressure', 'p'), 'ls': ('unknown field', 'pressure'), 'lv': ('test field', 'pressure', 'ls'), #Velocity 'w': ('unknown field', 'velocity'), 'z': ('test field', 'velocity', 'w'), } functions = { 'get_homog': (lambda ts, coors, problem, mode=None, **kwargs: \ get_homog(coors,problem, mode, **kwargs),), } functions.update(bc_funs) materials = { 'hom': 'get_homog', } materials.update(mats) integrals = { 'i': 4, "is": ("s", 4), } #Definition of solvers solvers = { 'ls': ('ls.mumps', {}), 'newton': ('nls.newton', {'i_max': 2, 'eps_a': 1e-12, 'eps_r': 1e-3, 'problem': 'nonlinear', }) } #Definition of macroscopic equations, see (43) equations = { 'eq1': """ dw_lin_elastic.i.Omega(hom.A, v, u) - dw_biot.i.Omega(hom.B, v, p) - dw_v_dot_grad_s.i.Omega(hom.PT, v, p) - dw_volume_dot.i.Omega(hom.H, v, w) = 0""", 'eq2': """ dw_diffusion.i.Omega(hom.K, q, p) - dw_v_dot_grad_s.i.Omega(hom.P, w, q)+ dw_volume_dot.i.Omega( q,ls ) = + dw_surface_integrate.is.In(w_in.val, q) - dw_surface_integrate.is.Out(w_out.val, q) """, 'eq3': """ dw_lin_elastic.i.Omega(hom.S, z, w) + dw_volume_dot.i.Omega(hom.H, z, w) + dw_v_dot_grad_s.i.Omega(hom.PT, z, p) = 0""", 'eq_imv': 'dw_volume_dot.i.Omega( lv, p ) = 0', } options = { 'output_dir': data_dir + '/results/macro', 'ls': 'ls', 'nls': 'newton', 'micro_filename' : poroela_mezo_file, 'absolute_mesh_path': True, } return locals()
[ "sfepy.homogenization.micmac.get_homog_coefs_linear", "sfepy.homogenization.utils.define_box_regions", "sfepy.discrete.fem.mesh.Mesh.from_file" ]
[((4957, 4986), 'sfepy.discrete.fem.mesh.Mesh.from_file', 'Mesh.from_file', (['filename_mesh'], {}), '(filename_mesh)\n', (4971, 4986), False, 'from sfepy.discrete.fem.mesh import Mesh\n'), ((5012, 5049), 'os.path.join', 'osp.join', (['data_dir', '"""perf_BDB_mes.py"""'], {}), "(data_dir, 'perf_BDB_mes.py')\n", (5020, 5049), True, 'import os.path as osp\n'), ((5157, 5214), 'sfepy.homogenization.utils.define_box_regions', 'define_box_regions', (['mesh.dim', 'bbox[0]', 'bbox[1]'], {'eps': '(1e-06)'}), '(mesh.dim, bbox[0], bbox[1], eps=1e-06)\n', (5175, 5214), False, 'from sfepy.homogenization.utils import define_box_regions\n'), ((1140, 1163), 'numpy.tile', 'nm.tile', (['v', '(nqp, 1, 1)'], {}), '(v, (nqp, 1, 1))\n', (1147, 1163), True, 'import numpy as nm\n'), ((1576, 1676), 'sfepy.homogenization.micmac.get_homog_coefs_linear', 'get_homog_coefs_linear', (['(0)', '(0)', 'None'], {'micro_filename': 'micro_filename', 'coefs_filename': 'coefs_filename'}), '(0, 0, None, micro_filename=micro_filename,\n coefs_filename=coefs_filename)\n', (1598, 1676), False, 'from sfepy.homogenization.micmac import get_homog_coefs_linear\n'), ((4827, 4863), 'os.path.join', 'osp.join', (['data_dir', '"""macro_perf.vtk"""'], {}), "(data_dir, 'macro_perf.vtk')\n", (4835, 4863), True, 'import os.path as osp\n'), ((2800, 2815), 'numpy.ones_like', 'nm.ones_like', (['y'], {}), '(y)\n', (2812, 2815), True, 'import numpy as nm\n'), ((2352, 2367), 'numpy.array', 'nm.array', (['[[v]]'], {}), '([[v]])\n', (2360, 2367), True, 'import numpy as nm\n')]
#!/usr/bin/env python """ Dispersion analysis of a heterogeneous finite scale periodic cell. The periodic cell mesh has to contain two subdomains Y1 (with the cell ids 1), Y2 (with the cell ids 2), so that different material properties can be defined in each of the subdomains (see ``--pars`` option). The command line parameters can be given in any consistent unit set, for example the basic SI units. The ``--unit-multipliers`` option can be used to rescale the input units to ones more suitable to the simulation, for example to prevent having different matrix blocks with large differences of matrix entries magnitudes. The results are then in the rescaled units. Usage Examples -------------- Default material parameters, a square periodic cell with a spherical inclusion, logs also standard pressure dilatation and shear waves, no eigenvectors:: python examples/linear_elasticity/dispersion_analysis.py meshes/2d/special/circle_in_square.mesh --log-std-waves --eigs-only As above, with custom eigenvalue solver parameters, and different number of eigenvalues, mesh size and units used in the calculation:: python examples/linear_elasticity/dispersion_analysis.py meshes/2d/special/circle_in_square.mesh --solver-conf="kind='eig.scipy', method='eigsh', tol=1e-10, maxiter=1000, which='LM', sigma=0" --log-std-waves -n 5 --range=0,640,101 --mode=omega --unit-multipliers=1e-6,1e-2,1e-3 --mesh-size=1e-2 --eigs-only Default material parameters, a square periodic cell with a square inclusion, and a very small mesh to allow comparing the omega and kappa modes (full matrix solver required!):: python examples/linear_elasticity/dispersion_analysis.py meshes/2d/square_2m.mesh --solver-conf="kind='eig.scipy', method='eigh'" --log-std-waves -n 10 --range=0,640,101 --mesh-size=1e-2 --mode=omega --eigs-only --no-legends --unit-multipliers=1e-6,1e-2,1e-3 -o output/omega python examples/linear_elasticity/dispersion_analysis.py meshes/2d/square_2m.mesh --solver-conf="kind='eig.qevp', method='companion', mode='inverted', solver={kind='eig.scipy', method='eig'}" --log-std-waves -n 500 --range=0,4000000,1001 --mesh-size=1e-2 --mode=kappa --eigs-only --no-legends --unit-multipliers=1e-6,1e-2,1e-3 -o output/kappa View/compare the resulting logs:: python script/plot_logs.py output/omega/frequencies.txt --no-legends -g 1 -o mode-omega.png python script/plot_logs.py output/kappa/wave-numbers.txt --no-legends -o mode-kappa.png python script/plot_logs.py output/kappa/wave-numbers.txt --no-legends --swap-axes -o mode-kappa-t.png In contrast to the heterogeneous square periodic cell, a homogeneous square periodic cell (the region Y2 is empty):: python examples/linear_elasticity/dispersion_analysis.py meshes/2d/square_1m.mesh --solver-conf="kind='eig.scipy', method='eigh'" --log-std-waves -n 10 --range=0,640,101 --mesh-size=1e-2 --mode=omega --eigs-only --no-legends --unit-multipliers=1e-6,1e-2,1e-3 -o output/omega-h python script/plot_logs.py output/omega-h/frequencies.txt --no-legends -g 1 -o mode-omega-h.png Use the Brillouin stepper:: python examples/linear_elasticity/dispersion_analysis.py meshes/2d/special/circle_in_square.mesh --log-std-waves -n=60 --eigs-only --no-legends --stepper=brillouin python script/plot_logs.py output/frequencies.txt -g 0 --rc="'font.size':14, 'lines.linewidth' : 3, 'lines.markersize' : 4" -o brillouin-stepper-kappas.png python script/plot_logs.py output/frequencies.txt -g 1 --no-legends --rc="'font.size':14, 'lines.linewidth' : 3, 'lines.markersize' : 4" -o brillouin-stepper-omegas.png Additional arguments can be passed to the problem configuration's :func:`define()` function using the ``--define-kwargs`` option. In this file, only the mesh vertex separation parameter `mesh_eps` can be used:: python examples/linear_elasticity/dispersion_analysis.py meshes/2d/special/circle_in_square.mesh --log-std-waves --eigs-only --define-kwargs="mesh_eps=1e-10" --save-regions """ from __future__ import absolute_import import os import sys sys.path.append('.') import gc from copy import copy from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import import_file, output, Struct from sfepy.base.conf import dict_from_string, ProblemConf from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options from sfepy.base.log import Log from sfepy.discrete.fem import MeshIO from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson as stiffness import sfepy.mechanics.matcoefs as mc from sfepy.mechanics.units import apply_unit_multipliers import sfepy.discrete.fem.periodic as per from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.homogenization.utils import define_box_regions from sfepy.discrete import Problem from sfepy.mechanics.tensors import get_von_mises_stress from sfepy.solvers import Solver from sfepy.solvers.ts import get_print_info, TimeStepper from sfepy.linalg.utils import output_array_stats, max_diff_csr def apply_units(pars, unit_multipliers): new_pars = apply_unit_multipliers(pars, ['stress', 'one', 'density', 'stress', 'one' ,'density'], unit_multipliers) return new_pars def compute_von_mises(out, pb, state, extend=False, wmag=None, wdir=None): """ Calculate the von Mises stress. """ stress = pb.evaluate('ev_cauchy_stress.i.Omega(m.D, u)', mode='el_avg') vms = get_von_mises_stress(stress.squeeze()) vms.shape = (vms.shape[0], 1, 1, 1) out['von_mises_stress'] = Struct(name='output_data', mode='cell', data=vms) return out def define(filename_mesh, pars, approx_order, refinement_level, solver_conf, plane='strain', post_process=False, mesh_eps=1e-8): io = MeshIO.any_from_filename(filename_mesh) bbox = io.read_bounding_box() dim = bbox.shape[1] options = { 'absolute_mesh_path' : True, 'refinement_level' : refinement_level, 'allow_empty_regions' : True, 'post_process_hook' : 'compute_von_mises' if post_process else None, } fields = { 'displacement': ('complex', dim, 'Omega', approx_order), } young1, poisson1, density1, young2, poisson2, density2 = pars materials = { 'm' : ({ 'D' : {'Y1' : stiffness(dim, young=young1, poisson=poisson1, plane=plane), 'Y2' : stiffness(dim, young=young2, poisson=poisson2, plane=plane)}, 'density' : {'Y1' : density1, 'Y2' : density2}, },), 'wave' : 'get_wdir', } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Y1': 'cells of group 1', 'Y2': 'cells of group 2', } regions.update(define_box_regions(dim, bbox[0], bbox[1], mesh_eps)) ebcs = { } if dim == 3: epbcs = { 'periodic_x' : (['Left', 'Right'], {'u.all' : 'u.all'}, 'match_x_plane'), 'periodic_y' : (['Near', 'Far'], {'u.all' : 'u.all'}, 'match_y_plane'), 'periodic_z' : (['Top', 'Bottom'], {'u.all' : 'u.all'}, 'match_z_plane'), } else: epbcs = { 'periodic_x' : (['Left', 'Right'], {'u.all' : 'u.all'}, 'match_y_line'), 'periodic_y' : (['Bottom', 'Top'], {'u.all' : 'u.all'}, 'match_x_line'), } per.set_accuracy(mesh_eps) functions = { 'match_x_plane' : (per.match_x_plane,), 'match_y_plane' : (per.match_y_plane,), 'match_z_plane' : (per.match_z_plane,), 'match_x_line' : (per.match_x_line,), 'match_y_line' : (per.match_y_line,), 'get_wdir' : (get_wdir,), } integrals = { 'i' : 2 * approx_order, } equations = { 'K' : 'dw_lin_elastic.i.Omega(m.D, v, u)', 'S' : 'dw_elastic_wave.i.Omega(m.D, wave.vec, v, u)', 'R' : """1j * dw_elastic_wave_cauchy.i.Omega(m.D, wave.vec, u, v) - 1j * dw_elastic_wave_cauchy.i.Omega(m.D, wave.vec, v, u)""", 'M' : 'dw_volume_dot.i.Omega(m.density, v, u)', } solver_0 = solver_conf.copy() solver_0['name'] = 'eig' return locals() def get_wdir(ts, coors, mode=None, equations=None, term=None, problem=None, wdir=None, **kwargs): if mode == 'special': return {'vec' : wdir} def set_wave_dir(pb, wdir): materials = pb.get_materials() wave_mat = materials['wave'] wave_mat.set_extra_args(wdir=wdir) def save_materials(output_dir, pb, options): stiffness = pb.evaluate('ev_volume_integrate_mat.2.Omega(m.D, u)', mode='el_avg', copy_materials=False, verbose=False) young, poisson = mc.youngpoisson_from_stiffness(stiffness, plane=options.plane) density = pb.evaluate('ev_volume_integrate_mat.2.Omega(m.density, u)', mode='el_avg', copy_materials=False, verbose=False) out = {} out['young'] = Struct(name='young', mode='cell', data=young[..., None, None]) out['poisson'] = Struct(name='poisson', mode='cell', data=poisson[..., None, None]) out['density'] = Struct(name='density', mode='cell', data=density) materials_filename = os.path.join(output_dir, 'materials.vtk') pb.save_state(materials_filename, out=out) def get_std_wave_fun(pb, options): stiffness = pb.evaluate('ev_volume_integrate_mat.2.Omega(m.D, u)', mode='el_avg', copy_materials=False, verbose=False) young, poisson = mc.youngpoisson_from_stiffness(stiffness, plane=options.plane) density = pb.evaluate('ev_volume_integrate_mat.2.Omega(m.density, u)', mode='el_avg', copy_materials=False, verbose=False) lam, mu = mc.lame_from_youngpoisson(young, poisson, plane=options.plane) alam = nm.average(lam) amu = nm.average(mu) adensity = nm.average(density) cp = nm.sqrt((alam + 2.0 * amu) / adensity) cs = nm.sqrt(amu / adensity) output('average p-wave speed:', cp) output('average shear wave speed:', cs) log_names = [r'$\omega_p$', r'$\omega_s$'] log_plot_kwargs = [{'ls' : '--', 'color' : 'k'}, {'ls' : '--', 'color' : 'gray'}] if options.mode == 'omega': fun = lambda wmag, wdir: (cp * wmag, cs * wmag) else: fun = lambda wmag, wdir: (wmag / cp, wmag / cs) return fun, log_names, log_plot_kwargs def get_stepper(rng, pb, options): if options.stepper == 'linear': stepper = TimeStepper(rng[0], rng[1], dt=None, n_step=rng[2]) return stepper bbox = pb.domain.mesh.get_bounding_box() bzone = 2.0 * nm.pi / (bbox[1] - bbox[0]) num = rng[2] // 3 class BrillouinStepper(Struct): """ Step over 1. Brillouin zone in xy plane. """ def __init__(self, t0, t1, dt=None, n_step=None, step=None, **kwargs): Struct.__init__(self, t0=t0, t1=t1, dt=dt, n_step=n_step, step=step) self.n_digit, self.format, self.suffix = get_print_info(self.n_step) def __iter__(self): ts = TimeStepper(0, bzone[0], dt=None, n_step=num) for ii, val in ts: yield ii, val, nm.array([1.0, 0.0]) if ii == (num-2): break ts = TimeStepper(0, bzone[1], dt=None, n_step=num) for ii, k1 in ts: wdir = nm.array([bzone[0], k1]) val = nm.linalg.norm(wdir) wdir = wdir / val yield num + ii, val, wdir if ii == (num-2): break wdir = nm.array([bzone[0], bzone[1]]) val = nm.linalg.norm(wdir) wdir = wdir / val ts = TimeStepper(0, 1, dt=None, n_step=num) for ii, _ in ts: yield 2 * num + ii, val * (1.0 - float(ii)/(num-1)), wdir stepper = BrillouinStepper(0, 1, n_step=rng[2]) return stepper def save_eigenvectors(filename, svecs, wmag, wdir, pb): if svecs is None: return variables = pb.get_variables() # Make full eigenvectors (add DOFs fixed by boundary conditions). vecs = nm.empty((variables.di.ptr[-1], svecs.shape[1]), dtype=svecs.dtype) for ii in range(svecs.shape[1]): vecs[:, ii] = variables.make_full_vec(svecs[:, ii]) # Save the eigenvectors. out = {} state = pb.create_state() pp_name = pb.conf.options.get('post_process_hook') pp = getattr(pb.conf.funmod, pp_name if pp_name is not None else '', lambda out, *args, **kwargs: out) for ii in range(svecs.shape[1]): state.set_full(vecs[:, ii]) aux = state.create_output_dict() aux2 = {} pp(aux2, pb, state, wmag=wmag, wdir=wdir) aux.update(convert_complex_output(aux2)) out.update({key + '%03d' % ii : aux[key] for key in aux}) pb.save_state(filename, out=out) def assemble_matrices(define, mod, pars, set_wave_dir, options, wdir=None): """ Assemble the blocks of dispersion eigenvalue problem matrices. """ define_dict = define(filename_mesh=options.mesh_filename, pars=pars, approx_order=options.order, refinement_level=options.refine, solver_conf=options.solver_conf, plane=options.plane, post_process=options.post_process, **options.define_kwargs) conf = ProblemConf.from_dict(define_dict, mod) pb = Problem.from_conf(conf) pb.dispersion_options = options pb.set_output_dir(options.output_dir) dim = pb.domain.shape.dim # Set the normalized wave vector direction to the material(s). if wdir is None: wdir = nm.asarray(options.wave_dir[:dim], dtype=nm.float64) wdir = wdir / nm.linalg.norm(wdir) set_wave_dir(pb, wdir) bbox = pb.domain.mesh.get_bounding_box() size = (bbox[1] - bbox[0]).max() scaling0 = apply_unit_multipliers([1.0], ['length'], options.unit_multipliers)[0] scaling = scaling0 if options.mesh_size is not None: scaling *= options.mesh_size / size output('scaling factor of periodic cell mesh coordinates:', scaling) output('new mesh size with applied unit multipliers:', scaling * size) pb.domain.mesh.coors[:] *= scaling pb.set_mesh_coors(pb.domain.mesh.coors, update_fields=True) bzone = 2.0 * nm.pi / (scaling * size) output('1. Brillouin zone size:', bzone * scaling0) output('1. Brillouin zone size with applied unit multipliers:', bzone) pb.time_update() pb.update_materials() # Assemble the matrices. mtxs = {} for key, eq in pb.equations.iteritems(): mtxs[key] = mtx = pb.mtx_a.copy() mtx = eq.evaluate(mode='weak', dw_mode='matrix', asm_obj=mtx) mtx.eliminate_zeros() output_array_stats(mtx.data, 'nonzeros in %s' % key) output('symmetry checks:') output('%s - %s^T:' % (key, key), max_diff_csr(mtx, mtx.T)) output('%s - %s^H:' % (key, key), max_diff_csr(mtx, mtx.H)) return pb, wdir, bzone, mtxs def setup_n_eigs(options, pb, mtxs): """ Setup the numbers of eigenvalues based on options and numbers of DOFs. """ solver_n_eigs = n_eigs = options.n_eigs n_dof = mtxs['K'].shape[0] if options.mode == 'omega': if options.n_eigs > n_dof: n_eigs = n_dof solver_n_eigs = None else: if options.n_eigs > 2 * n_dof: n_eigs = 2 * n_dof solver_n_eigs = None return solver_n_eigs, n_eigs def build_evp_matrices(mtxs, val, mode, pb): """ Build the matrices of the dispersion eigenvalue problem. """ if mode == 'omega': mtx_a = mtxs['K'] + val**2 * mtxs['S'] + val * mtxs['R'] output('A - A^H:', max_diff_csr(mtx_a, mtx_a.H)) evp_mtxs = (mtx_a, mtxs['M']) else: evp_mtxs = (mtxs['S'], mtxs['R'], mtxs['K'] - val**2 * mtxs['M']) return evp_mtxs def process_evp_results(eigs, svecs, val, wdir, bzone, pb, mtxs, options, std_wave_fun=None): """ Transform eigenvalues to either omegas or kappas, depending on `mode`. Transform eigenvectors, if available, depending on `mode`. Return also the values to log. """ if options.mode == 'omega': omegas = nm.sqrt(eigs) output('eigs, omegas:') for ii, om in enumerate(omegas): output('{:>3}. {: .10e}, {:.10e}'.format(ii, eigs[ii], om)) if options.stepper == 'linear': out = tuple(eigs) + tuple(omegas) else: out = tuple(val * wdir) + tuple(omegas) if std_wave_fun is not None: out = out + std_wave_fun(val, wdir) return omegas, svecs, out else: kappas = eigs.copy() rks = kappas.copy() # Mask modes far from 1. Brillouin zone. max_kappa = 1.2 * bzone kappas[kappas.real > max_kappa] = nm.nan # Mask non-physical modes. kappas[kappas.real < 0] = nm.nan kappas[nm.abs(kappas.imag) > 1e-10] = nm.nan out = tuple(kappas.real) output('raw kappas, masked real part:',) for ii, kr in enumerate(kappas.real): output('{:>3}. {: 23.5e}, {:.10e}'.format(ii, rks[ii], kr)) if svecs is not None: n_dof = mtxs['K'].shape[0] # Select only vectors corresponding to physical modes. ii = nm.isfinite(kappas.real) svecs = svecs[:n_dof, ii] if std_wave_fun is not None: out = out + tuple(ii if ii <= max_kappa else nm.nan for ii in std_wave_fun(val, wdir)) return kappas, svecs, out helps = { 'pars' : 'material parameters in Y1, Y2 subdomains in basic units' ' [default: %(default)s]', 'conf' : 'if given, an alternative problem description file with apply_units() and' ' define() functions [default: %(default)s]', 'define_kwargs' : 'additional keyword arguments passed to define()', 'mesh_size' : 'desired mesh size (max. of bounding box dimensions) in basic units' ' - the input periodic cell mesh is rescaled to this size' ' [default: %(default)s]', 'unit_multipliers' : 'basic unit multipliers (time, length, mass) [default: %(default)s]', 'plane' : 'for 2D problems, plane strain or stress hypothesis selection' ' [default: %(default)s]', 'wave_dir' : 'the wave vector direction (will be normalized)' ' [default: %(default)s]', 'mode' : 'solution mode: omega = solve a generalized EVP for omega,' ' kappa = solve a quadratic generalized EVP for kappa' ' [default: %(default)s]', 'stepper' : 'the range stepper. For "brillouin", only the number' ' of items from --range is used' ' [default: %(default)s]', 'range' : 'the wave vector magnitude / frequency range' ' (like numpy.linspace) depending on the mode option' ' [default: %(default)s]', 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'number of uniform mesh refinements [default: %(default)s]', 'n_eigs' : 'the number of eigenvalues to compute [default: %(default)s]', 'eigs_only' : 'compute only eigenvalues, not eigenvectors', 'post_process' : 'post-process eigenvectors', 'solver_conf' : 'eigenvalue problem solver configuration options' ' [default: %(default)s]', 'save_regions' : 'save defined regions into' ' <output_directory>/regions.vtk', 'save_materials' : 'save material parameters into' ' <output_directory>/materials.vtk', 'log_std_waves' : 'log also standard pressure dilatation and shear waves', 'no_legends' : 'do not show legends in the log plots', 'no_show' : 'do not show the log figure', 'silent' : 'do not print messages to screen', 'clear' : 'clear old solution files from output directory', 'output_dir' : 'output directory [default: %(default)s]', 'mesh_filename' : 'input periodic cell mesh file name [default: %(default)s]', } def main(): # Aluminium and epoxy. default_pars = '70e9,0.35,2.799e3, 3.8e9,0.27,1.142e3' default_solver_conf = ("kind='eig.scipy',method='eigsh',tol=1.0e-5," "maxiter=1000,which='LM',sigma=0.0") parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--pars', metavar='young1,poisson1,density1' ',young2,poisson2,density2', action='store', dest='pars', default=default_pars, help=helps['pars']) parser.add_argument('--conf', metavar='filename', action='store', dest='conf', default=None, help=helps['conf']) parser.add_argument('--define-kwargs', metavar='dict-like', action='store', dest='define_kwargs', default=None, help=helps['define_kwargs']) parser.add_argument('--mesh-size', type=float, metavar='float', action='store', dest='mesh_size', default=None, help=helps['mesh_size']) parser.add_argument('--unit-multipliers', metavar='c_time,c_length,c_mass', action='store', dest='unit_multipliers', default='1.0,1.0,1.0', help=helps['unit_multipliers']) parser.add_argument('--plane', action='store', dest='plane', choices=['strain', 'stress'], default='strain', help=helps['plane']) parser.add_argument('--wave-dir', metavar='float,float[,float]', action='store', dest='wave_dir', default='1.0,0.0,0.0', help=helps['wave_dir']) parser.add_argument('--mode', action='store', dest='mode', choices=['omega', 'kappa'], default='omega', help=helps['mode']) parser.add_argument('--stepper', action='store', dest='stepper', choices=['linear', 'brillouin'], default='linear', help=helps['stepper']) parser.add_argument('--range', metavar='start,stop,count', action='store', dest='range', default='0,6.4,33', help=helps['range']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-n', '--n-eigs', metavar='int', type=int, action='store', dest='n_eigs', default=6, help=helps['n_eigs']) group = parser.add_mutually_exclusive_group() group.add_argument('--eigs-only', action='store_true', dest='eigs_only', default=False, help=helps['eigs_only']) group.add_argument('--post-process', action='store_true', dest='post_process', default=False, help=helps['post_process']) parser.add_argument('--solver-conf', metavar='dict-like', action='store', dest='solver_conf', default=default_solver_conf, help=helps['solver_conf']) parser.add_argument('--save-regions', action='store_true', dest='save_regions', default=False, help=helps['save_regions']) parser.add_argument('--save-materials', action='store_true', dest='save_materials', default=False, help=helps['save_materials']) parser.add_argument('--log-std-waves', action='store_true', dest='log_std_waves', default=False, help=helps['log_std_waves']) parser.add_argument('--no-legends', action='store_false', dest='show_legends', default=True, help=helps['no_legends']) parser.add_argument('--no-show', action='store_false', dest='show', default=True, help=helps['no_show']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('-c', '--clear', action='store_true', dest='clear', default=False, help=helps['clear']) parser.add_argument('-o', '--output-dir', metavar='path', action='store', dest='output_dir', default='output', help=helps['output_dir']) parser.add_argument('mesh_filename', default='', help=helps['mesh_filename']) options = parser.parse_args() output_dir = options.output_dir output.set_output(filename=os.path.join(output_dir,'output_log.txt'), combined=options.silent == False) if options.conf is not None: mod = import_file(options.conf) else: mod = sys.modules[__name__] apply_units = mod.apply_units define = mod.define set_wave_dir = mod.set_wave_dir setup_n_eigs = mod.setup_n_eigs build_evp_matrices = mod.build_evp_matrices save_materials = mod.save_materials get_std_wave_fun = mod.get_std_wave_fun get_stepper = mod.get_stepper process_evp_results = mod.process_evp_results options.pars = [float(ii) for ii in options.pars.split(',')] options.unit_multipliers = [float(ii) for ii in options.unit_multipliers.split(',')] options.wave_dir = [float(ii) for ii in options.wave_dir.split(',')] aux = options.range.split(',') options.range = [float(aux[0]), float(aux[1]), int(aux[2])] options.solver_conf = dict_from_string(options.solver_conf) options.define_kwargs = dict_from_string(options.define_kwargs) if options.clear: remove_files_patterns(output_dir, ['*.h5', '*.vtk', '*.txt'], ignores=['output_log.txt'], verbose=True) filename = os.path.join(output_dir, 'options.txt') ensure_path(filename) save_options(filename, [('options', vars(options))], quote_command_line=True) pars = apply_units(options.pars, options.unit_multipliers) output('material parameters with applied unit multipliers:') output(pars) if options.mode == 'omega': rng = copy(options.range) rng[:2] = apply_unit_multipliers(options.range[:2], ['wave_number', 'wave_number'], options.unit_multipliers) output('wave number range with applied unit multipliers:', rng) else: if options.stepper == 'brillouin': raise ValueError('Cannot use "brillouin" stepper in kappa mode!') rng = copy(options.range) rng[:2] = apply_unit_multipliers(options.range[:2], ['frequency', 'frequency'], options.unit_multipliers) output('frequency range with applied unit multipliers:', rng) pb, wdir, bzone, mtxs = assemble_matrices(define, mod, pars, set_wave_dir, options) dim = pb.domain.shape.dim if dim != 2: options.plane = 'strain' if options.save_regions: pb.save_regions_as_groups(os.path.join(output_dir, 'regions')) if options.save_materials: save_materials(output_dir, pb, options) conf = pb.solver_confs['eig'] eig_solver = Solver.any_from_conf(conf) n_eigs, options.n_eigs = setup_n_eigs(options, pb, mtxs) get_color = lambda ii: plt.cm.viridis((float(ii) / (options.n_eigs - 1))) plot_kwargs = [{'color' : get_color(ii), 'ls' : '', 'marker' : 'o'} for ii in range(options.n_eigs)] get_color_dim = lambda ii: plt.cm.viridis((float(ii) / (dim-1))) plot_kwargs_dim = [{'color' : get_color_dim(ii), 'ls' : '', 'marker' : 'o'} for ii in range(dim)] log_names = [] log_plot_kwargs = [] if options.log_std_waves: std_wave_fun, log_names, log_plot_kwargs = get_std_wave_fun( pb, options) else: std_wave_fun = None stepper = get_stepper(rng, pb, options) if options.mode == 'omega': eigenshapes_filename = os.path.join(output_dir, 'frequency-eigenshapes-%s.vtk' % stepper.suffix) if options.stepper == 'linear': log = Log([[r'$\lambda_{%d}$' % ii for ii in range(options.n_eigs)], [r'$\omega_{%d}$' % ii for ii in range(options.n_eigs)] + log_names], plot_kwargs=[plot_kwargs, plot_kwargs + log_plot_kwargs], formats=[['{:.5e}'] * options.n_eigs, ['{:.5e}'] * (options.n_eigs + len(log_names))], yscales=['linear', 'linear'], xlabels=[r'$\kappa$', r'$\kappa$'], ylabels=[r'eigenvalues $\lambda_i$', r'frequencies $\omega_i$'], show_legends=options.show_legends, is_plot=options.show, log_filename=os.path.join(output_dir, 'frequencies.txt'), aggregate=1000, sleep=0.1) else: log = Log([[r'$\kappa_{%d}$'% ii for ii in range(dim)], [r'$\omega_{%d}$' % ii for ii in range(options.n_eigs)] + log_names], plot_kwargs=[plot_kwargs_dim, plot_kwargs + log_plot_kwargs], formats=[['{:.5e}'] * dim, ['{:.5e}'] * (options.n_eigs + len(log_names))], yscales=['linear', 'linear'], xlabels=[r'', r''], ylabels=[r'wave vector $\kappa$', r'frequencies $\omega_i$'], show_legends=options.show_legends, is_plot=options.show, log_filename=os.path.join(output_dir, 'frequencies.txt'), aggregate=1000, sleep=0.1) for aux in stepper: if options.stepper == 'linear': iv, wmag = aux else: iv, wmag, wdir = aux output('step %d: wave vector %s' % (iv, wmag * wdir)) if options.stepper == 'brillouin': pb, _, bzone, mtxs = assemble_matrices( define, mod, pars, set_wave_dir, options, wdir=wdir) evp_mtxs = build_evp_matrices(mtxs, wmag, options.mode, pb) if options.eigs_only: eigs = eig_solver(*evp_mtxs, n_eigs=n_eigs, eigenvectors=False) svecs = None else: eigs, svecs = eig_solver(*evp_mtxs, n_eigs=n_eigs, eigenvectors=True) omegas, svecs, out = process_evp_results( eigs, svecs, wmag, wdir, bzone, pb, mtxs, options, std_wave_fun=std_wave_fun ) if options.stepper == 'linear': log(*out, x=[wmag, wmag]) else: log(*out, x=[iv, iv]) save_eigenvectors(eigenshapes_filename % iv, svecs, wmag, wdir, pb) gc.collect() log(save_figure=os.path.join(output_dir, 'frequencies.png')) log(finished=True) else: eigenshapes_filename = os.path.join(output_dir, 'wave-number-eigenshapes-%s.vtk' % stepper.suffix) log = Log([[r'$\kappa_{%d}$' % ii for ii in range(options.n_eigs)] + log_names], plot_kwargs=[plot_kwargs + log_plot_kwargs], formats=[['{:.5e}'] * (options.n_eigs + len(log_names))], yscales=['linear'], xlabels=[r'$\omega$'], ylabels=[r'wave numbers $\kappa_i$'], show_legends=options.show_legends, is_plot=options.show, log_filename=os.path.join(output_dir, 'wave-numbers.txt'), aggregate=1000, sleep=0.1) for io, omega in stepper: output('step %d: frequency %s' % (io, omega)) evp_mtxs = build_evp_matrices(mtxs, omega, options.mode, pb) if options.eigs_only: eigs = eig_solver(*evp_mtxs, n_eigs=n_eigs, eigenvectors=False) svecs = None else: eigs, svecs = eig_solver(*evp_mtxs, n_eigs=n_eigs, eigenvectors=True) kappas, svecs, out = process_evp_results( eigs, svecs, omega, wdir, bzone, pb, mtxs, options, std_wave_fun=std_wave_fun ) log(*out, x=[omega]) save_eigenvectors(eigenshapes_filename % io, svecs, kappas, wdir, pb) gc.collect() log(save_figure=os.path.join(output_dir, 'wave-numbers.png')) log(finished=True) if __name__ == '__main__': main()
[ "sfepy.base.conf.dict_from_string", "sfepy.solvers.ts.TimeStepper", "sfepy.linalg.utils.output_array_stats", "sfepy.base.ioutils.remove_files_patterns", "sfepy.base.base.Struct.__init__", "sfepy.base.ioutils.ensure_path", "sfepy.discrete.fem.periodic.set_accuracy", "sfepy.mechanics.matcoefs.lame_from_...
[((4031, 4051), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (4046, 4051), False, 'import sys\n'), ((5102, 5210), 'sfepy.mechanics.units.apply_unit_multipliers', 'apply_unit_multipliers', (['pars', "['stress', 'one', 'density', 'stress', 'one', 'density']", 'unit_multipliers'], {}), "(pars, ['stress', 'one', 'density', 'stress', 'one',\n 'density'], unit_multipliers)\n", (5124, 5210), False, 'from sfepy.mechanics.units import apply_unit_multipliers\n'), ((5666, 5715), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'vms'}), "(name='output_data', mode='cell', data=vms)\n", (5672, 5715), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((5919, 5958), 'sfepy.discrete.fem.MeshIO.any_from_filename', 'MeshIO.any_from_filename', (['filename_mesh'], {}), '(filename_mesh)\n', (5943, 5958), False, 'from sfepy.discrete.fem import MeshIO\n'), ((7812, 7838), 'sfepy.discrete.fem.periodic.set_accuracy', 'per.set_accuracy', (['mesh_eps'], {}), '(mesh_eps)\n', (7828, 7838), True, 'import sfepy.discrete.fem.periodic as per\n'), ((9143, 9205), 'sfepy.mechanics.matcoefs.youngpoisson_from_stiffness', 'mc.youngpoisson_from_stiffness', (['stiffness'], {'plane': 'options.plane'}), '(stiffness, plane=options.plane)\n', (9173, 9205), True, 'import sfepy.mechanics.matcoefs as mc\n'), ((9444, 9506), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""young"""', 'mode': '"""cell"""', 'data': 'young[..., None, None]'}), "(name='young', mode='cell', data=young[..., None, None])\n", (9450, 9506), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((9554, 9620), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""poisson"""', 'mode': '"""cell"""', 'data': 'poisson[..., None, None]'}), "(name='poisson', mode='cell', data=poisson[..., None, None])\n", (9560, 9620), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((9670, 9719), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""density"""', 'mode': '"""cell"""', 'data': 'density'}), "(name='density', mode='cell', data=density)\n", (9676, 9719), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((9745, 9786), 'os.path.join', 'os.path.join', (['output_dir', '"""materials.vtk"""'], {}), "(output_dir, 'materials.vtk')\n", (9757, 9786), False, 'import os\n'), ((10042, 10104), 'sfepy.mechanics.matcoefs.youngpoisson_from_stiffness', 'mc.youngpoisson_from_stiffness', (['stiffness'], {'plane': 'options.plane'}), '(stiffness, plane=options.plane)\n', (10072, 10104), True, 'import sfepy.mechanics.matcoefs as mc\n'), ((10325, 10387), 'sfepy.mechanics.matcoefs.lame_from_youngpoisson', 'mc.lame_from_youngpoisson', (['young', 'poisson'], {'plane': 'options.plane'}), '(young, poisson, plane=options.plane)\n', (10350, 10387), True, 'import sfepy.mechanics.matcoefs as mc\n'), ((10439, 10454), 'numpy.average', 'nm.average', (['lam'], {}), '(lam)\n', (10449, 10454), True, 'import numpy as nm\n'), ((10465, 10479), 'numpy.average', 'nm.average', (['mu'], {}), '(mu)\n', (10475, 10479), True, 'import numpy as nm\n'), ((10495, 10514), 'numpy.average', 'nm.average', (['density'], {}), '(density)\n', (10505, 10514), True, 'import numpy as nm\n'), ((10525, 10563), 'numpy.sqrt', 'nm.sqrt', (['((alam + 2.0 * amu) / adensity)'], {}), '((alam + 2.0 * amu) / adensity)\n', (10532, 10563), True, 'import numpy as nm\n'), ((10573, 10596), 'numpy.sqrt', 'nm.sqrt', (['(amu / adensity)'], {}), '(amu / adensity)\n', (10580, 10596), True, 'import numpy as nm\n'), ((10601, 10636), 'sfepy.base.base.output', 'output', (['"""average p-wave speed:"""', 'cp'], {}), "('average p-wave speed:', cp)\n", (10607, 10636), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((10641, 10680), 'sfepy.base.base.output', 'output', (['"""average shear wave speed:"""', 'cs'], {}), "('average shear wave speed:', cs)\n", (10647, 10680), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((12742, 12809), 'numpy.empty', 'nm.empty', (['(variables.di.ptr[-1], svecs.shape[1])'], {'dtype': 'svecs.dtype'}), '((variables.di.ptr[-1], svecs.shape[1]), dtype=svecs.dtype)\n', (12750, 12809), True, 'import numpy as nm\n'), ((14111, 14150), 'sfepy.base.conf.ProblemConf.from_dict', 'ProblemConf.from_dict', (['define_dict', 'mod'], {}), '(define_dict, mod)\n', (14132, 14150), False, 'from sfepy.base.conf import dict_from_string, ProblemConf\n'), ((14161, 14184), 'sfepy.discrete.Problem.from_conf', 'Problem.from_conf', (['conf'], {}), '(conf)\n', (14178, 14184), False, 'from sfepy.discrete import Problem\n'), ((14836, 14904), 'sfepy.base.base.output', 'output', (['"""scaling factor of periodic cell mesh coordinates:"""', 'scaling'], {}), "('scaling factor of periodic cell mesh coordinates:', scaling)\n", (14842, 14904), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((14909, 14979), 'sfepy.base.base.output', 'output', (['"""new mesh size with applied unit multipliers:"""', '(scaling * size)'], {}), "('new mesh size with applied unit multipliers:', scaling * size)\n", (14915, 14979), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((15131, 15182), 'sfepy.base.base.output', 'output', (['"""1. Brillouin zone size:"""', '(bzone * scaling0)'], {}), "('1. Brillouin zone size:', bzone * scaling0)\n", (15137, 15182), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((15187, 15257), 'sfepy.base.base.output', 'output', (['"""1. Brillouin zone size with applied unit multipliers:"""', 'bzone'], {}), "('1. Brillouin zone size with applied unit multipliers:', bzone)\n", (15193, 15257), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((21060, 21145), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '__doc__', 'formatter_class': 'RawDescriptionHelpFormatter'}), '(description=__doc__, formatter_class=RawDescriptionHelpFormatter\n )\n', (21074, 21145), False, 'from argparse import ArgumentParser, RawDescriptionHelpFormatter\n'), ((26795, 26832), 'sfepy.base.conf.dict_from_string', 'dict_from_string', (['options.solver_conf'], {}), '(options.solver_conf)\n', (26811, 26832), False, 'from sfepy.base.conf import dict_from_string, ProblemConf\n'), ((26861, 26900), 'sfepy.base.conf.dict_from_string', 'dict_from_string', (['options.define_kwargs'], {}), '(options.define_kwargs)\n', (26877, 26900), False, 'from sfepy.base.conf import dict_from_string, ProblemConf\n'), ((27142, 27181), 'os.path.join', 'os.path.join', (['output_dir', '"""options.txt"""'], {}), "(output_dir, 'options.txt')\n", (27154, 27181), False, 'import os\n'), ((27186, 27207), 'sfepy.base.ioutils.ensure_path', 'ensure_path', (['filename'], {}), '(filename)\n', (27197, 27207), False, 'from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options\n'), ((27375, 27435), 'sfepy.base.base.output', 'output', (['"""material parameters with applied unit multipliers:"""'], {}), "('material parameters with applied unit multipliers:')\n", (27381, 27435), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((27440, 27452), 'sfepy.base.base.output', 'output', (['pars'], {}), '(pars)\n', (27446, 27452), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((28674, 28700), 'sfepy.solvers.Solver.any_from_conf', 'Solver.any_from_conf', (['conf'], {}), '(conf)\n', (28694, 28700), False, 'from sfepy.solvers import Solver\n'), ((7046, 7097), 'sfepy.homogenization.utils.define_box_regions', 'define_box_regions', (['dim', 'bbox[0]', 'bbox[1]', 'mesh_eps'], {}), '(dim, bbox[0], bbox[1], mesh_eps)\n', (7064, 7097), False, 'from sfepy.homogenization.utils import define_box_regions\n'), ((11128, 11179), 'sfepy.solvers.ts.TimeStepper', 'TimeStepper', (['rng[0]', 'rng[1]'], {'dt': 'None', 'n_step': 'rng[2]'}), '(rng[0], rng[1], dt=None, n_step=rng[2])\n', (11139, 11179), False, 'from sfepy.solvers.ts import get_print_info, TimeStepper\n'), ((14397, 14449), 'numpy.asarray', 'nm.asarray', (['options.wave_dir[:dim]'], {'dtype': 'nm.float64'}), '(options.wave_dir[:dim], dtype=nm.float64)\n', (14407, 14449), True, 'import numpy as nm\n'), ((14618, 14685), 'sfepy.mechanics.units.apply_unit_multipliers', 'apply_unit_multipliers', (['[1.0]', "['length']", 'options.unit_multipliers'], {}), "([1.0], ['length'], options.unit_multipliers)\n", (14640, 14685), False, 'from sfepy.mechanics.units import apply_unit_multipliers\n'), ((15545, 15597), 'sfepy.linalg.utils.output_array_stats', 'output_array_stats', (['mtx.data', "('nonzeros in %s' % key)"], {}), "(mtx.data, 'nonzeros in %s' % key)\n", (15563, 15597), False, 'from sfepy.linalg.utils import output_array_stats, max_diff_csr\n'), ((15607, 15633), 'sfepy.base.base.output', 'output', (['"""symmetry checks:"""'], {}), "('symmetry checks:')\n", (15613, 15633), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((17054, 17067), 'numpy.sqrt', 'nm.sqrt', (['eigs'], {}), '(eigs)\n', (17061, 17067), True, 'import numpy as nm\n'), ((17077, 17100), 'sfepy.base.base.output', 'output', (['"""eigs, omegas:"""'], {}), "('eigs, omegas:')\n", (17083, 17100), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((17860, 17899), 'sfepy.base.base.output', 'output', (['"""raw kappas, masked real part:"""'], {}), "('raw kappas, masked real part:')\n", (17866, 17899), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((25966, 25991), 'sfepy.base.base.import_file', 'import_file', (['options.conf'], {}), '(options.conf)\n', (25977, 25991), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((26932, 27040), 'sfepy.base.ioutils.remove_files_patterns', 'remove_files_patterns', (['output_dir', "['*.h5', '*.vtk', '*.txt']"], {'ignores': "['output_log.txt']", 'verbose': '(True)'}), "(output_dir, ['*.h5', '*.vtk', '*.txt'], ignores=[\n 'output_log.txt'], verbose=True)\n", (26953, 27040), False, 'from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options\n'), ((27500, 27519), 'copy.copy', 'copy', (['options.range'], {}), '(options.range)\n', (27504, 27519), False, 'from copy import copy\n'), ((27538, 27641), 'sfepy.mechanics.units.apply_unit_multipliers', 'apply_unit_multipliers', (['options.range[:2]', "['wave_number', 'wave_number']", 'options.unit_multipliers'], {}), "(options.range[:2], ['wave_number', 'wave_number'],\n options.unit_multipliers)\n", (27560, 27641), False, 'from sfepy.mechanics.units import apply_unit_multipliers\n'), ((27728, 27791), 'sfepy.base.base.output', 'output', (['"""wave number range with applied unit multipliers:"""', 'rng'], {}), "('wave number range with applied unit multipliers:', rng)\n", (27734, 27791), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((27939, 27958), 'copy.copy', 'copy', (['options.range'], {}), '(options.range)\n', (27943, 27958), False, 'from copy import copy\n'), ((27977, 28076), 'sfepy.mechanics.units.apply_unit_multipliers', 'apply_unit_multipliers', (['options.range[:2]', "['frequency', 'frequency']", 'options.unit_multipliers'], {}), "(options.range[:2], ['frequency', 'frequency'],\n options.unit_multipliers)\n", (27999, 28076), False, 'from sfepy.mechanics.units import apply_unit_multipliers\n'), ((28163, 28224), 'sfepy.base.base.output', 'output', (['"""frequency range with applied unit multipliers:"""', 'rng'], {}), "('frequency range with applied unit multipliers:', rng)\n", (28169, 28224), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((29476, 29549), 'os.path.join', 'os.path.join', (['output_dir', "('frequency-eigenshapes-%s.vtk' % stepper.suffix)"], {}), "(output_dir, 'frequency-eigenshapes-%s.vtk' % stepper.suffix)\n", (29488, 29549), False, 'import os\n'), ((32758, 32833), 'os.path.join', 'os.path.join', (['output_dir', "('wave-number-eigenshapes-%s.vtk' % stepper.suffix)"], {}), "(output_dir, 'wave-number-eigenshapes-%s.vtk' % stepper.suffix)\n", (32770, 32833), False, 'import os\n'), ((11520, 11588), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'t0': 't0', 't1': 't1', 'dt': 'dt', 'n_step': 'n_step', 'step': 'step'}), '(self, t0=t0, t1=t1, dt=dt, n_step=n_step, step=step)\n', (11535, 11588), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((11643, 11670), 'sfepy.solvers.ts.get_print_info', 'get_print_info', (['self.n_step'], {}), '(self.n_step)\n', (11657, 11670), False, 'from sfepy.solvers.ts import get_print_info, TimeStepper\n'), ((11717, 11762), 'sfepy.solvers.ts.TimeStepper', 'TimeStepper', (['(0)', 'bzone[0]'], {'dt': 'None', 'n_step': 'num'}), '(0, bzone[0], dt=None, n_step=num)\n', (11728, 11762), False, 'from sfepy.solvers.ts import get_print_info, TimeStepper\n'), ((11904, 11949), 'sfepy.solvers.ts.TimeStepper', 'TimeStepper', (['(0)', 'bzone[1]'], {'dt': 'None', 'n_step': 'num'}), '(0, bzone[1], dt=None, n_step=num)\n', (11915, 11949), False, 'from sfepy.solvers.ts import get_print_info, TimeStepper\n'), ((12207, 12237), 'numpy.array', 'nm.array', (['[bzone[0], bzone[1]]'], {}), '([bzone[0], bzone[1]])\n', (12215, 12237), True, 'import numpy as nm\n'), ((12256, 12276), 'numpy.linalg.norm', 'nm.linalg.norm', (['wdir'], {}), '(wdir)\n', (12270, 12276), True, 'import numpy as nm\n'), ((12324, 12362), 'sfepy.solvers.ts.TimeStepper', 'TimeStepper', (['(0)', '(1)'], {'dt': 'None', 'n_step': 'num'}), '(0, 1, dt=None, n_step=num)\n', (12335, 12362), False, 'from sfepy.solvers.ts import get_print_info, TimeStepper\n'), ((13382, 13410), 'sfepy.discrete.fem.meshio.convert_complex_output', 'convert_complex_output', (['aux2'], {}), '(aux2)\n', (13404, 13410), False, 'from sfepy.discrete.fem.meshio import convert_complex_output\n'), ((14472, 14492), 'numpy.linalg.norm', 'nm.linalg.norm', (['wdir'], {}), '(wdir)\n', (14486, 14492), True, 'import numpy as nm\n'), ((15676, 15700), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx', 'mtx.T'], {}), '(mtx, mtx.T)\n', (15688, 15700), False, 'from sfepy.linalg.utils import output_array_stats, max_diff_csr\n'), ((15744, 15768), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx', 'mtx.H'], {}), '(mtx, mtx.H)\n', (15756, 15768), False, 'from sfepy.linalg.utils import output_array_stats, max_diff_csr\n'), ((16522, 16550), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx_a', 'mtx_a.H'], {}), '(mtx_a, mtx_a.H)\n', (16534, 16550), False, 'from sfepy.linalg.utils import output_array_stats, max_diff_csr\n'), ((18173, 18197), 'numpy.isfinite', 'nm.isfinite', (['kappas.real'], {}), '(kappas.real)\n', (18184, 18197), True, 'import numpy as nm\n'), ((25819, 25861), 'os.path.join', 'os.path.join', (['output_dir', '"""output_log.txt"""'], {}), "(output_dir, 'output_log.txt')\n", (25831, 25861), False, 'import os\n'), ((28505, 28540), 'os.path.join', 'os.path.join', (['output_dir', '"""regions"""'], {}), "(output_dir, 'regions')\n", (28517, 28540), False, 'import os\n'), ((31563, 31616), 'sfepy.base.base.output', 'output', (["('step %d: wave vector %s' % (iv, wmag * wdir))"], {}), "('step %d: wave vector %s' % (iv, wmag * wdir))\n", (31569, 31616), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((32606, 32618), 'gc.collect', 'gc.collect', ([], {}), '()\n', (32616, 32618), False, 'import gc\n'), ((33566, 33611), 'sfepy.base.base.output', 'output', (["('step %d: frequency %s' % (io, omega))"], {}), "('step %d: frequency %s' % (io, omega))\n", (33572, 33611), False, 'from sfepy.base.base import import_file, output, Struct\n'), ((34348, 34360), 'gc.collect', 'gc.collect', ([], {}), '()\n', (34358, 34360), False, 'import gc\n'), ((12003, 12027), 'numpy.array', 'nm.array', (['[bzone[0], k1]'], {}), '([bzone[0], k1])\n', (12011, 12027), True, 'import numpy as nm\n'), ((12050, 12070), 'numpy.linalg.norm', 'nm.linalg.norm', (['wdir'], {}), '(wdir)\n', (12064, 12070), True, 'import numpy as nm\n'), ((17780, 17799), 'numpy.abs', 'nm.abs', (['kappas.imag'], {}), '(kappas.imag)\n', (17786, 17799), True, 'import numpy as nm\n'), ((32644, 32687), 'os.path.join', 'os.path.join', (['output_dir', '"""frequencies.png"""'], {}), "(output_dir, 'frequencies.png')\n", (32656, 32687), False, 'import os\n'), ((33429, 33473), 'os.path.join', 'os.path.join', (['output_dir', '"""wave-numbers.txt"""'], {}), "(output_dir, 'wave-numbers.txt')\n", (33441, 33473), False, 'import os\n'), ((34386, 34430), 'os.path.join', 'os.path.join', (['output_dir', '"""wave-numbers.png"""'], {}), "(output_dir, 'wave-numbers.png')\n", (34398, 34430), False, 'import os\n'), ((6454, 6513), 'sfepy.mechanics.matcoefs.stiffness_from_youngpoisson', 'stiffness', (['dim'], {'young': 'young1', 'poisson': 'poisson1', 'plane': 'plane'}), '(dim, young=young1, poisson=poisson1, plane=plane)\n', (6463, 6513), True, 'from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson as stiffness\n'), ((6577, 6636), 'sfepy.mechanics.matcoefs.stiffness_from_youngpoisson', 'stiffness', (['dim'], {'young': 'young2', 'poisson': 'poisson2', 'plane': 'plane'}), '(dim, young=young2, poisson=poisson2, plane=plane)\n', (6586, 6636), True, 'from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson as stiffness\n'), ((30413, 30456), 'os.path.join', 'os.path.join', (['output_dir', '"""frequencies.txt"""'], {}), "(output_dir, 'frequencies.txt')\n", (30425, 30456), False, 'import os\n'), ((31296, 31339), 'os.path.join', 'os.path.join', (['output_dir', '"""frequencies.txt"""'], {}), "(output_dir, 'frequencies.txt')\n", (31308, 31339), False, 'import os\n'), ((11825, 11845), 'numpy.array', 'nm.array', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (11833, 11845), True, 'import numpy as nm\n')]
from __future__ import absolute_import from copy import copy import numpy as nm from sfepy.base.testing import TestCommon from sfepy.base.base import ordered_iteritems from sfepy import data_dir filename_meshes = [data_dir + '/meshes/elements/%s_2.mesh' % geom for geom in ['1_2', '2_3', '2_4', '3_4', '3_8', '3_2_4']] def make_term_args(arg_shapes, arg_kinds, arg_types, ats_mode, domain, material_value=None, poly_space_base=None): from sfepy.base.base import basestr from sfepy.discrete import FieldVariable, Material, Variables, Materials from sfepy.discrete.fem import Field from sfepy.solvers.ts import TimeStepper from sfepy.mechanics.tensors import dim2sym omega = domain.regions['Omega'] dim = domain.shape.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number ;) return 1 else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return [_parse_scalar_shape(ii.strip()) for ii in sh.split(',')] else: return (int(sh),) args = {} str_args = [] materials = [] variables = [] for ii, arg_kind in enumerate(arg_kinds): if arg_kind != 'ts': if ats_mode is not None: extended_ats = arg_types[ii] + ('/%s' % ats_mode) else: extended_ats = arg_types[ii] try: sh = arg_shapes[arg_types[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) field = Field.from_args('f%d' % ii, nm.float64, shape, omega, approx_order=1, poly_space_base=poly_space_base) if arg_kind == 'virtual_variable': if sh[1] is not None: istate = arg_types.index(sh[1]) else: # Only virtual variable in arguments. istate = -1 # -> Make fake variable. var = FieldVariable('u-1', 'unknown', field) var.set_constant(0.0) variables.append(var) var = FieldVariable('v', 'test', field, primary_var_name='u%d' % istate) elif arg_kind == 'state_variable': var = FieldVariable('u%d' % ii, 'unknown', field) var.set_constant(0.0) elif arg_kind == 'parameter_variable': var = FieldVariable('p%d' % ii, 'parameter', field, primary_var_name='(set-to-None)') var.set_constant(0.0) variables.append(var) str_args.append(var.name) args[var.name] = var elif arg_kind.endswith('material'): if sh is None: # Switched-off opt_material. continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if material_value is None: material_value = 1.0 shape = _parse_tuple_shape(sh) if (len(shape) > 1) or (shape[0] > 1): if ((len(shape) == 2) and (shape[0] == shape[1]) and (material_value != 0.0)): # Identity matrix. val = nm.eye(shape[0], dtype=nm.float64) else: # Array. val = nm.empty(shape, dtype=nm.float64) val.fill(material_value) values = {'%sc%d' % (prefix, ii) : val} elif (len(shape) == 1) and (shape[0] == 1): # Single scalar as a special value. values = {'.c%d' % ii : material_value} else: raise ValueError('wrong material shape! (%s)' % shape) mat = Material('m%d' % ii, values=values) materials.append(mat) str_args.append(mat.name + '.' + 'c%d' % ii) args[mat.name] = mat elif arg_kind == 'ts': ts = TimeStepper(0.0, 1.0, 1.0, 5) str_args.append('ts') args['ts'] = ts else: str_args.append('user%d' % ii) args[str_args[-1]] = None materials = Materials(materials) variables = Variables(variables) return args, str_args, materials, variables class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import Integral from sfepy.discrete.fem import Mesh, FEDomain domains = [] for filename in filename_meshes: mesh = Mesh.from_file(filename) domain = FEDomain('domain_%s' % mesh.name.replace(data_dir, ''), mesh) domain.create_region('Omega', 'all') domain.create_region('Gamma', 'vertices of surface', 'facet') domains.append(domain) integral = Integral('i', order=3) qp_coors, qp_weights = integral.get_qp('3_8') custom_integral = Integral('i', coors=qp_coors, weights=qp_weights, order='custom') test = Test(domains=domains, integral=integral, custom_integral=custom_integral, conf=conf, options=options) return test def test_term_call_modes(self): from sfepy.terms import term_table ok = True failed = [] for domain in self.domains: self.report('domain: %s' % domain.name) domain_geometry = list(domain.geom_els.values())[0].name if domain.shape.dim != domain.shape.tdim: domain_geometry = '%d_%s' % (domain.shape.dim, domain_geometry) for _, term_cls in ordered_iteritems(term_table): if (domain_geometry not in term_cls.geometries) \ or ("dg" in term_cls.name) \ or (term_cls.name == "dw_ns_dot_grad_s"): continue vint = ('volume', 'point', 'custom') rname = 'Omega' if term_cls.integration in vint else 'Gamma' self.report('<-- %s ...' % term_cls.name) if rname == 'Gamma' and domain.mesh.dim == 1: self.report('--> 1D Gamma region: not tested!') elif term_cls.arg_shapes: try: _ok = self._test_single_term(term_cls, domain, rname) except: _ok = False if not _ok: failed.append((domain.name, term_cls.name)) ok = ok and _ok self.report('--> ok: %s' % _ok) else: self.report('--> not tested!') self.report('failed:', failed) return ok def _test_single_term(self, term_cls, domain, rname): from sfepy.terms import Term from sfepy.terms.terms import get_arg_kinds ok = True term_call = term_cls.name + '(%s)' arg_shapes_list = term_cls.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] if term_cls.integration != 'custom': integral = self.integral else: integral = self.custom_integral poly_space_base = getattr(term_cls, 'poly_space_base', 'lagrange') prev_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes self.report('arg_shapes:', arg_shapes) arg_types = term_cls.arg_types if not isinstance(arg_types[0], tuple): arg_types = (arg_types,) for iat, ats in enumerate(arg_types): self.report('arg_types:', ats) arg_kinds = get_arg_kinds(ats) modes = getattr(term_cls, 'modes', None) mode = modes[iat] if modes is not None else None if 'dw_s_dot_grad_i_s' in term_cls.name: material_value = 0.0 else: material_value = 1.0 aux = make_term_args(arg_shapes, arg_kinds, ats, mode, domain, material_value=material_value, poly_space_base=poly_space_base) args, str_args, materials, variables = aux self.report('args:', str_args) name = term_call % (', '.join(str_args)) term = Term.new(name, integral, domain.regions[rname], **args) term.setup() call_mode = 'weak' if term.names.virtual else 'eval' self.report('call mode:', call_mode) out = term.evaluate(mode=call_mode, ret_status=True) if call_mode == 'eval': vals, status = out vals = nm.array(vals) else: vals, iels, status = out if isinstance(vals, tuple): # Dynamic connectivity terms. vals = vals[0] _ok = nm.isfinite(vals).all() ok = ok and _ok self.report('values shape: %s' % (vals.shape,)) if not _ok: self.report('values are not finite!') self.report(vals) _ok = status == 0 if not _ok: self.report('status is %s!' % status) ok = ok and _ok if term.names.virtual: # Test differentiation w.r.t. state variables in the weak # mode. svars = term.get_state_variables(unknown_only=True) for svar in svars: vals, iels, status = term.evaluate(mode=call_mode, diff_var=svar.name, ret_status=True) if isinstance(vals, tuple): # Dynamic connectivity terms. vals = vals[0] _ok = status == 0 ok = ok and _ok self.report('diff: %s' % svar.name) if not _ok: self.report('status is %s!' % status) _ok = nm.isfinite(vals).all() ok = ok and _ok self.report('values shape: %s' % (vals.shape,)) if not _ok: self.report('values are not finite!') self.report(vals) return ok
[ "sfepy.discrete.Variables", "sfepy.discrete.fem.Mesh.from_file", "sfepy.discrete.Integral", "sfepy.discrete.fem.Field.from_args", "sfepy.base.base.ordered_iteritems", "sfepy.terms.Term.new", "sfepy.solvers.ts.TimeStepper", "sfepy.discrete.FieldVariable", "sfepy.mechanics.tensors.dim2sym", "sfepy.d...
[((801, 813), 'sfepy.mechanics.tensors.dim2sym', 'dim2sym', (['dim'], {}), '(dim)\n', (808, 813), False, 'from sfepy.mechanics.tensors import dim2sym\n'), ((4849, 4869), 'sfepy.discrete.Materials', 'Materials', (['materials'], {}), '(materials)\n', (4858, 4869), False, 'from sfepy.discrete import FieldVariable, Material, Variables, Materials\n'), ((4886, 4906), 'sfepy.discrete.Variables', 'Variables', (['variables'], {}), '(variables)\n', (4895, 4906), False, 'from sfepy.discrete import FieldVariable, Material, Variables, Materials\n'), ((5531, 5553), 'sfepy.discrete.Integral', 'Integral', (['"""i"""'], {'order': '(3)'}), "('i', order=3)\n", (5539, 5553), False, 'from sfepy.discrete import Integral\n'), ((5634, 5699), 'sfepy.discrete.Integral', 'Integral', (['"""i"""'], {'coors': 'qp_coors', 'weights': 'qp_weights', 'order': '"""custom"""'}), "('i', coors=qp_coors, weights=qp_weights, order='custom')\n", (5642, 5699), False, 'from sfepy.discrete import Integral\n'), ((2002, 2108), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (["('f%d' % ii)", 'nm.float64', 'shape', 'omega'], {'approx_order': '(1)', 'poly_space_base': 'poly_space_base'}), "('f%d' % ii, nm.float64, shape, omega, approx_order=1,\n poly_space_base=poly_space_base)\n", (2017, 2108), False, 'from sfepy.discrete.fem import Field\n'), ((5214, 5238), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['filename'], {}), '(filename)\n', (5228, 5238), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((6356, 6385), 'sfepy.base.base.ordered_iteritems', 'ordered_iteritems', (['term_table'], {}), '(term_table)\n', (6373, 6385), False, 'from sfepy.base.base import ordered_iteritems\n'), ((8181, 8198), 'copy.copy', 'copy', (['prev_shapes'], {}), '(prev_shapes)\n', (8185, 8198), False, 'from copy import copy\n'), ((2645, 2711), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""v"""', '"""test"""', 'field'], {'primary_var_name': "('u%d' % istate)"}), "('v', 'test', field, primary_var_name='u%d' % istate)\n", (2658, 2711), False, 'from sfepy.discrete import FieldVariable, Material, Variables, Materials\n'), ((4434, 4469), 'sfepy.discrete.Material', 'Material', (["('m%d' % ii)"], {'values': 'values'}), "('m%d' % ii, values=values)\n", (4442, 4469), False, 'from sfepy.discrete import FieldVariable, Material, Variables, Materials\n'), ((8594, 8612), 'sfepy.terms.terms.get_arg_kinds', 'get_arg_kinds', (['ats'], {}), '(ats)\n', (8607, 8612), False, 'from sfepy.terms.terms import get_arg_kinds\n'), ((9303, 9358), 'sfepy.terms.Term.new', 'Term.new', (['name', 'integral', 'domain.regions[rname]'], {}), '(name, integral, domain.regions[rname], **args)\n', (9311, 9358), False, 'from sfepy.terms import Term\n'), ((2499, 2537), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""u-1"""', '"""unknown"""', 'field'], {}), "('u-1', 'unknown', field)\n", (2512, 2537), False, 'from sfepy.discrete import FieldVariable, Material, Variables, Materials\n'), ((2818, 2861), 'sfepy.discrete.FieldVariable', 'FieldVariable', (["('u%d' % ii)", '"""unknown"""', 'field'], {}), "('u%d' % ii, 'unknown', field)\n", (2831, 2861), False, 'from sfepy.discrete import FieldVariable, Material, Variables, Materials\n'), ((4644, 4673), 'sfepy.solvers.ts.TimeStepper', 'TimeStepper', (['(0.0)', '(1.0)', '(1.0)', '(5)'], {}), '(0.0, 1.0, 1.0, 5)\n', (4655, 4673), False, 'from sfepy.solvers.ts import TimeStepper\n'), ((9688, 9702), 'numpy.array', 'nm.array', (['vals'], {}), '(vals)\n', (9696, 9702), True, 'import numpy as nm\n'), ((2974, 3053), 'sfepy.discrete.FieldVariable', 'FieldVariable', (["('p%d' % ii)", '"""parameter"""', 'field'], {'primary_var_name': '"""(set-to-None)"""'}), "('p%d' % ii, 'parameter', field, primary_var_name='(set-to-None)')\n", (2987, 3053), False, 'from sfepy.discrete import FieldVariable, Material, Variables, Materials\n'), ((3885, 3919), 'numpy.eye', 'nm.eye', (['shape[0]'], {'dtype': 'nm.float64'}), '(shape[0], dtype=nm.float64)\n', (3891, 3919), True, 'import numpy as nm\n'), ((3998, 4031), 'numpy.empty', 'nm.empty', (['shape'], {'dtype': 'nm.float64'}), '(shape, dtype=nm.float64)\n', (4006, 4031), True, 'import numpy as nm\n'), ((9924, 9941), 'numpy.isfinite', 'nm.isfinite', (['vals'], {}), '(vals)\n', (9935, 9941), True, 'import numpy as nm\n'), ((11238, 11255), 'numpy.isfinite', 'nm.isfinite', (['vals'], {}), '(vals)\n', (11249, 11255), True, 'import numpy as nm\n')]
""" Basic uniform mesh refinement functions. """ import numpy as nm from sfepy.discrete.fem import Mesh def refine_2_3(mesh_in): """ Refines mesh out of triangles by cutting cutting each edge in half and making 4 new finer triangles out of one coarser one. """ cmesh = mesh_in.cmesh # Unique edge centres. e_centres = cmesh.get_centroids(cmesh.dim - 1) # New coordinates after the original ones. coors = nm.r_[mesh_in.coors, e_centres] o1 = mesh_in.n_nod cc = cmesh.get_conn(cmesh.dim, cmesh.dim - 1) conn = mesh_in.get_conn('2_3') n_el = conn.shape[0] e_nodes = cc.indices.reshape((n_el, 3)) + o1 c = nm.c_[conn, e_nodes].T new_conn = nm.vstack([c[0], c[3], c[5], c[3], c[4], c[5], c[1], c[4], c[3], c[2], c[5], c[4]]).T new_conn = new_conn.reshape((4 * n_el, 3)) new_mat_id = cmesh.cell_groups.repeat(4) mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, [new_conn], [new_mat_id], mesh_in.descs ) return mesh def refine_2_4(mesh_in): """ Refines mesh out of quadrilaterals by cutting cutting each edge in half and making 4 new finer quadrilaterals out of one coarser one. """ cmesh = mesh_in.cmesh # Unique edge centres. e_centres = cmesh.get_centroids(cmesh.dim - 1) # Unique element centres. centres = cmesh.get_centroids(cmesh.dim) # New coordinates after the original ones. coors = nm.r_[mesh_in.coors, e_centres, centres] o1 = mesh_in.n_nod o2 = o1 + e_centres.shape[0] cc = cmesh.get_conn(cmesh.dim, cmesh.dim - 1) conn = mesh_in.get_conn('2_4') n_el = conn.shape[0] e_nodes = cc.indices.reshape((n_el, 4)) + o1 nodes = nm.arange(n_el) + o2 c = nm.c_[conn, e_nodes, nodes].T new_conn = nm.vstack([c[0], c[4], c[8], c[7], c[1], c[5], c[8], c[4], c[2], c[6], c[8], c[5], c[3], c[7], c[8], c[6]]).T new_conn = new_conn.reshape((4 * n_el, 4)) new_mat_id = cmesh.cell_groups.repeat(4) mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, [new_conn], [new_mat_id], mesh_in.descs ) return mesh def refine_3_4(mesh_in): """ Refines tetrahedra by cutting each edge in half and making 8 new finer tetrahedra out of one coarser one. Old nodal coordinates come first in `coors`, then the new ones. The new tetrahedra are similar to the old one, no degeneration is supposed to occur as at most 3 congruence classes of tetrahedra appear, even when re-applied iteratively (provided that `conns` are not modified between two applications - ordering of vertices in tetrahedra matters not only for positivity of volumes). References: - <NAME>: Simplicial grid refinement: on Freudenthal s algorithm and the optimal number of congruence classes, Numer.Math. 85 (2000), no. 1, 1--29, or - <NAME>: Tetrahedral grid refinement, Computing 55 (1995), no. 4, 355--378, or http://citeseer.ist.psu.edu/bey95tetrahedral.html """ cmesh = mesh_in.cmesh # Unique edge centres. e_centres = cmesh.get_centroids(cmesh.dim - 2) # New coordinates after the original ones. coors = nm.r_[mesh_in.coors, e_centres] o1 = mesh_in.n_nod cc = cmesh.get_conn(cmesh.dim, cmesh.dim - 2) conn = mesh_in.get_conn('3_4') n_el = conn.shape[0] e_nodes = cc.indices.reshape((n_el, 6)) + o1 c = nm.c_[conn, e_nodes].T new_conn = nm.vstack([c[0], c[4], c[6], c[7], c[4], c[1], c[5], c[8], c[6], c[5], c[2], c[9], c[7], c[8], c[9], c[3], c[4], c[6], c[7], c[8], c[4], c[6], c[8], c[5], c[6], c[7], c[8], c[9], c[6], c[5], c[9], c[8]]).T new_conn = new_conn.reshape((8 * n_el, 4)) new_mat_id = cmesh.cell_groups.repeat(8) mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, [new_conn], [new_mat_id], mesh_in.descs ) return mesh def refine_3_8(mesh_in): """ Refines hexahedral mesh by cutting cutting each edge in half and making 8 new finer hexahedrons out of one coarser one. """ cmesh = mesh_in.cmesh # Unique edge centres. e_centres = cmesh.get_centroids(cmesh.dim - 2) # Unique face centres. f_centres = cmesh.get_centroids(cmesh.dim - 1) # Unique element centres. centres = cmesh.get_centroids(cmesh.dim) # New coordinates after the original ones. coors = nm.r_[mesh_in.coors, e_centres, f_centres, centres] o1 = mesh_in.n_nod o2 = o1 + e_centres.shape[0] o3 = o2 + f_centres.shape[0] ecc = cmesh.get_conn(cmesh.dim, cmesh.dim - 2) fcc = cmesh.get_conn(cmesh.dim, cmesh.dim - 1) conn = mesh_in.get_conn('3_8') n_el = conn.shape[0] st = nm.vstack e_nodes = ecc.indices.reshape((n_el, 12)) + o1 f_nodes = fcc.indices.reshape((n_el, 6)) + o2 nodes = nm.arange(n_el) + o3 c = nm.c_[conn, e_nodes, f_nodes, nodes].T new_conn = st([c[0], c[8], c[20], c[11], c[16], c[22], c[26], c[21], c[1], c[9], c[20], c[8], c[17], c[24], c[26], c[22], c[2], c[10], c[20], c[9], c[18], c[25], c[26], c[24], c[3], c[11], c[20], c[10], c[19], c[21], c[26], c[25], c[4], c[15], c[23], c[12], c[16], c[21], c[26], c[22], c[5], c[12], c[23], c[13], c[17], c[22], c[26], c[24], c[6], c[13], c[23], c[14], c[18], c[24], c[26], c[25], c[7], c[14], c[23], c[15], c[19], c[25], c[26], c[21]]).T new_conn = new_conn.reshape((8 * n_el, 8)) new_mat_id = cmesh.cell_groups.repeat(8) mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, [new_conn], [new_mat_id], mesh_in.descs ) return mesh def refine_reference(geometry, level): """ Refine reference element given by `geometry`. Notes ----- The error edges must be generated in the order of the connectivity of the previous (lower) level. """ from sfepy.discrete.fem import FEDomain from sfepy.discrete.fem.geometry_element import geometry_data gcoors, gconn = geometry.coors, geometry.conn if level == 0: return gcoors, gconn, None gd = geometry_data[geometry.name] conn = nm.array([gd.conn], dtype=nm.int32) mat_id = conn[:, 0].copy() mat_id[:] = 0 mesh = Mesh.from_data('aux', gd.coors, None, [conn], [mat_id], [geometry.name]) domain = FEDomain('aux', mesh) for ii in range(level): domain = domain.refine() coors = domain.mesh.coors conn = domain.get_conn() n_el = conn.shape[0] if geometry.name == '2_3': aux_conn = conn.reshape((n_el / 4, 4, 3)) ir = [[0, 1, 2], [2, 2, 3], [3, 3, 0]] ic = [[0, 0, 0], [0, 1, 0], [0, 1, 0]] elif geometry.name == '2_4': aux_conn = conn.reshape((n_el / 4, 4, 4)) ir = [[0, 0, 1], [1, 1, 2], [2, 2, 3], [3, 3, 0], [0, 0, 2], [3, 3, 1]] ic = [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [1, 2, 1], [1, 2, 1]] elif geometry.name == '3_4': aux_conn = conn.reshape((n_el / 8, 8, 4)) ir = [[0, 0, 1], [1, 1, 2], [2, 0, 0], [3, 1, 1], [3, 2, 2], [3, 0, 0]] ic = [[0, 1, 1], [1, 2, 2], [2, 2, 0], [3, 3, 1], [3, 3, 2], [3, 3, 0]] elif geometry.name == '3_8': aux_conn = conn.reshape((n_el / 8, 8, 8)) ir = [[0, 0, 1], [1, 1, 2], [2, 2, 3], [3, 0, 0], [0, 0, 2], [0, 0, 1], [0, 0, 1], [1, 1, 2], [2, 2, 3], [3, 0, 0], [0, 0, 2], [0, 0, 1], [4, 4, 5], [5, 5, 6], [6, 6, 7], [7, 4, 4], [4, 4, 6], [4, 4, 5], [0, 0, 4], [1, 1, 5], [2, 2, 6], [3, 3, 7], [0, 0, 4], [1, 1, 5], [2, 2, 6], [0, 0, 4], [0, 0, 4]] ic = [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 3, 0], [1, 2, 1], [3, 2, 1], [4, 5, 4], [4, 5, 4], [4, 5, 4], [4, 7, 4], [5, 6, 5], [7, 6, 5], [0, 3, 0], [0, 3, 0], [0, 3, 0], [0, 1, 0], [3, 2, 3], [1, 2, 3], [0, 4, 0], [0, 4, 0], [0, 4, 0], [0, 4, 0], [1, 5, 3], [1, 5, 3], [1, 5, 3], [3, 7, 1], [2, 6, 2]] else: raise ValueError('unsupported geometry! (%s)' % geometry.name) conn = nm.array(conn, dtype=nm.int32) error_edges = aux_conn[:, ir, ic] return coors, conn, error_edges
[ "sfepy.discrete.fem.Mesh.from_data", "sfepy.discrete.fem.FEDomain" ]
[((979, 1072), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (["(mesh_in.name + '_r')", 'coors', 'None', '[new_conn]', '[new_mat_id]', 'mesh_in.descs'], {}), "(mesh_in.name + '_r', coors, None, [new_conn], [new_mat_id],\n mesh_in.descs)\n", (993, 1072), False, 'from sfepy.discrete.fem import Mesh\n'), ((2179, 2272), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (["(mesh_in.name + '_r')", 'coors', 'None', '[new_conn]', '[new_mat_id]', 'mesh_in.descs'], {}), "(mesh_in.name + '_r', coors, None, [new_conn], [new_mat_id],\n mesh_in.descs)\n", (2193, 2272), False, 'from sfepy.discrete.fem import Mesh\n'), ((4133, 4226), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (["(mesh_in.name + '_r')", 'coors', 'None', '[new_conn]', '[new_mat_id]', 'mesh_in.descs'], {}), "(mesh_in.name + '_r', coors, None, [new_conn], [new_mat_id],\n mesh_in.descs)\n", (4147, 4226), False, 'from sfepy.discrete.fem import Mesh\n'), ((5963, 6056), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (["(mesh_in.name + '_r')", 'coors', 'None', '[new_conn]', '[new_mat_id]', 'mesh_in.descs'], {}), "(mesh_in.name + '_r', coors, None, [new_conn], [new_mat_id],\n mesh_in.descs)\n", (5977, 6056), False, 'from sfepy.discrete.fem import Mesh\n'), ((6595, 6630), 'numpy.array', 'nm.array', (['[gd.conn]'], {'dtype': 'nm.int32'}), '([gd.conn], dtype=nm.int32)\n', (6603, 6630), True, 'import numpy as nm\n'), ((6692, 6764), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (['"""aux"""', 'gd.coors', 'None', '[conn]', '[mat_id]', '[geometry.name]'], {}), "('aux', gd.coors, None, [conn], [mat_id], [geometry.name])\n", (6706, 6764), False, 'from sfepy.discrete.fem import Mesh\n'), ((6804, 6825), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""aux"""', 'mesh'], {}), "('aux', mesh)\n", (6812, 6825), False, 'from sfepy.discrete.fem import FEDomain\n'), ((8582, 8612), 'numpy.array', 'nm.array', (['conn'], {'dtype': 'nm.int32'}), '(conn, dtype=nm.int32)\n', (8590, 8612), True, 'import numpy as nm\n'), ((710, 797), 'numpy.vstack', 'nm.vstack', (['[c[0], c[3], c[5], c[3], c[4], c[5], c[1], c[4], c[3], c[2], c[5], c[4]]'], {}), '([c[0], c[3], c[5], c[3], c[4], c[5], c[1], c[4], c[3], c[2], c[5],\n c[4]])\n', (719, 797), True, 'import numpy as nm\n'), ((1810, 1825), 'numpy.arange', 'nm.arange', (['n_el'], {}), '(n_el)\n', (1819, 1825), True, 'import numpy as nm\n'), ((1886, 1997), 'numpy.vstack', 'nm.vstack', (['[c[0], c[4], c[8], c[7], c[1], c[5], c[8], c[4], c[2], c[6], c[8], c[5], c[\n 3], c[7], c[8], c[6]]'], {}), '([c[0], c[4], c[8], c[7], c[1], c[5], c[8], c[4], c[2], c[6], c[8],\n c[5], c[3], c[7], c[8], c[6]])\n', (1895, 1997), True, 'import numpy as nm\n'), ((3640, 3851), 'numpy.vstack', 'nm.vstack', (['[c[0], c[4], c[6], c[7], c[4], c[1], c[5], c[8], c[6], c[5], c[2], c[9], c[\n 7], c[8], c[9], c[3], c[4], c[6], c[7], c[8], c[4], c[6], c[8], c[5], c\n [6], c[7], c[8], c[9], c[6], c[5], c[9], c[8]]'], {}), '([c[0], c[4], c[6], c[7], c[4], c[1], c[5], c[8], c[6], c[5], c[2],\n c[9], c[7], c[8], c[9], c[3], c[4], c[6], c[7], c[8], c[4], c[6], c[8],\n c[5], c[6], c[7], c[8], c[9], c[6], c[5], c[9], c[8]])\n', (3649, 3851), True, 'import numpy as nm\n'), ((5197, 5212), 'numpy.arange', 'nm.arange', (['n_el'], {}), '(n_el)\n', (5206, 5212), True, 'import numpy as nm\n')]
"from __future__ import print_function\nfrom __future__ import absolute_import\nimport numpy as nm\n(...TRUNCATED)
["sfepy.linalg.cycle","sfepy.discrete.fem.mesh.Mesh.from_data","sfepy.base.ioutils.ensure_path","sfe(...TRUNCATED)
"[((135, 155), 'sys.path.append', 'sys.path.append', (['\"\"\".\"\"\"'], {}), \"('.')\\n\", (150, 15(...TRUNCATED)
"# 30.05.2007, c\n# last revision: 25.02.2008\nfrom __future__ import absolute_import\nfrom sfepy im(...TRUNCATED)
["sfepy.applications.solve_pde","sfepy.linalg.rotation_matrix2d","sfepy.discrete.Material.from_conf"(...TRUNCATED)
"[((2386, 2421), 'sfepy.applications.solve_pde', 'solve_pde', (['conf'], {'save_results': '(False)'}(...TRUNCATED)
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
6