code stringlengths 768 64.5k | apis list | 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
from __future__ import absolute_import
import numpy as nm
import sys
from six.moves import range
sys.path.append('.')
from sfepy.base.base import output, assert_
from sfepy.base.ioutils import ensure_path
from sfepy.linalg import cycle
from sfepy.discrete.fem.mesh import Mesh
from sfepy.mesh.mesh_tools import elems_q2t
def get_tensor_product_conn(shape):
"""
Generate vertex connectivity for cells of a tensor-product mesh of the
given shape.
Parameters
----------
shape : array of 2 or 3 ints
Shape (counts of nodes in x, y, z) of the mesh.
Returns
-------
conn : array
The vertex connectivity array.
desc : str
The cell kind.
"""
shape = nm.asarray(shape)
dim = len(shape)
assert_(1 <= dim <= 3)
n_nod = nm.prod(shape)
n_el = nm.prod(shape - 1)
grid = nm.arange(n_nod, dtype=nm.int32)
grid.shape = shape
if dim == 1:
conn = nm.zeros((n_el, 2), dtype=nm.int32)
conn[:, 0] = grid[:-1]
conn[:, 1] = grid[1:]
desc = '1_2'
elif dim == 2:
conn = nm.zeros((n_el, 4), dtype=nm.int32)
conn[:, 0] = grid[:-1, :-1].flat
conn[:, 1] = grid[1:, :-1].flat
conn[:, 2] = grid[1:, 1:].flat
conn[:, 3] = grid[:-1, 1:].flat
desc = '2_4'
else:
conn = nm.zeros((n_el, 8), dtype=nm.int32)
conn[:, 0] = grid[:-1, :-1, :-1].flat
conn[:, 1] = grid[1:, :-1, :-1].flat
conn[:, 2] = grid[1:, 1:, :-1].flat
conn[:, 3] = grid[:-1, 1:, :-1].flat
conn[:, 4] = grid[:-1, :-1, 1:].flat
conn[:, 5] = grid[1:, :-1, 1:].flat
conn[:, 6] = grid[1:, 1:, 1:].flat
conn[:, 7] = grid[:-1, 1:, 1:].flat
desc = '3_8'
return conn, desc
def gen_block_mesh(dims, shape, centre, mat_id=0, name='block',
coors=None, verbose=True):
"""
Generate a 2D or 3D block mesh. The dimension is determined by the
lenght of the shape argument.
Parameters
----------
dims : array of 2 or 3 floats
Dimensions of the block.
shape : array of 2 or 3 ints
Shape (counts of nodes in x, y, z) of the block mesh.
centre : array of 2 or 3 floats
Centre of the block.
mat_id : int, optional
The material id of all elements.
name : string
Mesh name.
verbose : bool
If True, show progress of the mesh generation.
Returns
-------
mesh : Mesh instance
"""
dims = nm.asarray(dims, dtype=nm.float64)
shape = nm.asarray(shape, dtype=nm.int32)
centre = nm.asarray(centre, dtype=nm.float64)
dim = shape.shape[0]
centre = centre[:dim]
dims = dims[:dim]
n_nod = nm.prod(shape)
output('generating %d vertices...' % n_nod, verbose=verbose)
x0 = centre - 0.5 * dims
dd = dims / (shape - 1)
ngrid = nm.mgrid[[slice(ii) for ii in shape]]
ngrid.shape = (dim, n_nod)
coors = x0 + ngrid.T * dd
output('...done', verbose=verbose)
n_el = nm.prod(shape - 1)
output('generating %d cells...' % n_el, verbose=verbose)
mat_ids = nm.empty((n_el,), dtype=nm.int32)
mat_ids.fill(mat_id)
conn, desc = get_tensor_product_conn(shape)
output('...done', verbose=verbose)
mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc])
return mesh
def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False,
is_open=False, open_angle=0.0, non_uniform=False,
name='cylinder', verbose=True):
"""
Generate a cylindrical mesh along an axis. Its cross-section can be
ellipsoidal.
Parameters
----------
dims : array of 5 floats
Dimensions of the cylinder: inner surface semi-axes a1, b1, outer
surface semi-axes a2, b2, length.
shape : array of 3 ints
Shape (counts of nodes in radial, circumferential and longitudinal
directions) of the cylinder mesh.
centre : array of 3 floats
Centre of the cylinder.
axis: one of 'x', 'y', 'z'
The axis of the cylinder.
force_hollow : boolean
Force hollow mesh even if inner radii a1 = b1 = 0.
is_open : boolean
Generate an open cylinder segment.
open_angle : float
Opening angle in radians.
non_uniform : boolean
If True, space the mesh nodes in radial direction so that the element
volumes are (approximately) the same, making thus the elements towards
the outer surface thinner.
name : string
Mesh name.
verbose : bool
If True, show progress of the mesh generation.
Returns
-------
mesh : Mesh instance
"""
dims = nm.asarray(dims, dtype=nm.float64)
shape = nm.asarray(shape, dtype=nm.int32)
centre = nm.asarray(centre, dtype=nm.float64)
a1, b1, a2, b2, length = dims
nr, nfi, nl = shape
origin = centre - nm.array([0.5 * length, 0.0, 0.0])
dfi = 2.0 * (nm.pi - open_angle) / nfi
if is_open:
nnfi = nfi + 1
else:
nnfi = nfi
is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15)
if is_hollow:
mr = 0
else:
mr = (nnfi - 1) * nl
grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32)
n_nod = nr * nnfi * nl - mr
coors = nm.zeros((n_nod, 3), dtype=nm.float64)
angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1)
xs = nm.linspace(0.0, length, nl)
if non_uniform:
ras = nm.zeros((nr,), dtype=nm.float64)
rbs = nm.zeros_like(ras)
advol = (a2**2 - a1**2) / (nr - 1)
bdvol = (b2**2 - b1**2) / (nr - 1)
ras[0], rbs[0] = a1, b1
for ii in range(1, nr):
ras[ii] = nm.sqrt(advol + ras[ii-1]**2)
rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2)
else:
ras = nm.linspace(a1, a2, nr)
rbs = nm.linspace(b1, b2, nr)
# This is 3D only...
output('generating %d vertices...' % n_nod, verbose=verbose)
ii = 0
for ix in range(nr):
a, b = ras[ix], rbs[ix]
for iy, fi in enumerate(angles[:nnfi]):
for iz, x in enumerate(xs):
grid[ix,iy,iz] = ii
coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)]
ii += 1
if not is_hollow and (ix == 0):
if iy > 0:
grid[ix,iy,iz] = grid[ix,0,iz]
ii -= 1
assert_(ii == n_nod)
output('...done', verbose=verbose)
n_el = (nr - 1) * nfi * (nl - 1)
conn = nm.zeros((n_el, 8), dtype=nm.int32)
output('generating %d cells...' % n_el, verbose=verbose)
ii = 0
for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]):
if iy < (nnfi - 1):
conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ],
grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ],
grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1],
grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]]
ii += 1
elif not is_open:
conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ],
grid[ix+1,0,iz ], grid[ix ,0,iz ],
grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1],
grid[ix+1,0,iz+1], grid[ix ,0,iz+1]]
ii += 1
mat_id = nm.zeros((n_el,), dtype = nm.int32)
desc = '3_8'
assert_(n_nod == (conn.max() + 1))
output('...done', verbose=verbose)
if axis == 'z':
coors = coors[:,[1,2,0]]
elif axis == 'y':
coors = coors[:,[2,0,1]]
mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc])
return mesh
def _spread_along_axis(axis, coors, tangents, grading_fun):
"""
Spread the coordinates along the given axis using the grading function, and
the tangents in the other two directions.
"""
oo = list(set([0, 1, 2]).difference([axis]))
c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]]
out = nm.empty_like(coors)
mi, ma = c0.min(), c0.max()
nc0 = (c0 - mi) / (ma - mi)
out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi
nc = oc0 - oc0.min()
mi, ma = c1.min(), c1.max()
n1 = 2 * (c1 - mi) / (ma - mi) - 1
out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]]
mi, ma = c2.min(), c2.max()
n2 = 2 * (c2 - mi) / (ma - mi) - 1
out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]]
return out
def _get_extension_side(side, grading_fun, mat_id,
b_dims, b_shape, e_dims, e_shape, centre):
"""
Get a mesh extending the given side of a block mesh.
"""
# Pure extension dimensions.
pe_dims = 0.5 * (e_dims - b_dims)
coff = 0.5 * (b_dims + pe_dims)
cc = centre + coff * nm.eye(3)[side]
if side == 0: # x axis.
dims = [pe_dims[0], b_dims[1], b_dims[2]]
shape = [e_shape, b_shape[1], b_shape[2]]
tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]]
elif side == 1: # y axis.
dims = [b_dims[0], pe_dims[1], b_dims[2]]
shape = [b_shape[0], e_shape, b_shape[2]]
tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]]
elif side == 2: # z axis.
dims = [b_dims[0], b_dims[1], pe_dims[2]]
shape = [b_shape[0], b_shape[1], e_shape]
tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0]
e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False)
e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents,
grading_fun)
return e_mesh, shape
def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre,
grading_fun=None, name=None):
"""
Generate a 3D mesh with a central block and (coarse) extending side meshes.
The resulting mesh is again a block. Each of the components has a different
material id.
Parameters
----------
b_dims : array of 3 floats
The dimensions of the central block.
b_shape : array of 3 ints
The shape (counts of nodes in x, y, z) of the central block mesh.
e_dims : array of 3 floats
The dimensions of the complete block (central block + extensions).
e_shape : int
The count of nodes of extending blocks in the direction from the
central block.
centre : array of 3 floats
The centre of the mesh.
grading_fun : callable, optional
A function of :math:`x \in [0, 1]` that can be used to shift nodes in
the extension axis directions to allow smooth grading of element sizes
from the centre. The default function is :math:`x**p` with :math:`p`
determined so that the element sizes next to the central block have the
size of the shortest edge of the central block.
name : string, optional
The mesh name.
Returns
-------
mesh : Mesh instance
"""
b_dims = nm.asarray(b_dims, dtype=nm.float64)
b_shape = nm.asarray(b_shape, dtype=nm.int32)
e_dims = nm.asarray(e_dims, dtype=nm.float64)
centre = nm.asarray(centre, dtype=nm.float64)
# Pure extension dimensions.
pe_dims = 0.5 * (e_dims - b_dims)
# Central block element sizes.
dd = (b_dims / (b_shape - 1))
# The "first x" going to grading_fun.
nc = 1.0 / (e_shape - 1)
# Grading power and function.
power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc)
grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun
# Central block mesh.
b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False)
# 'x' extension.
e_mesh, xs = _get_extension_side(0, grading_fun, 10,
b_dims, b_shape, e_dims, e_shape, centre)
mesh = b_mesh + e_mesh
# Mirror by 'x'.
e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0]
e_mesh.cmesh.cell_groups.fill(11)
mesh = mesh + e_mesh
# 'y' extension.
e_mesh, ys = _get_extension_side(1, grading_fun, 20,
b_dims, b_shape, e_dims, e_shape, centre)
mesh = mesh + e_mesh
# Mirror by 'y'.
e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1]
e_mesh.cmesh.cell_groups.fill(21)
mesh = mesh + e_mesh
# 'z' extension.
e_mesh, zs = _get_extension_side(2, grading_fun, 30,
b_dims, b_shape, e_dims, e_shape, centre)
mesh = mesh + e_mesh
# Mirror by 'z'.
e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2]
e_mesh.cmesh.cell_groups.fill(31)
mesh = mesh + e_mesh
if name is not None:
mesh.name = name
# Verify merging by checking the number of nodes.
n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs)
+ 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2])
+ 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2]))
if n_nod != mesh.n_nod:
raise ValueError('Merge of meshes failed! (%d == %d)'
% (n_nod, mesh.n_nod))
return mesh
def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False):
from sfepy.discrete.fem.periodic import match_grid_plane
s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0]
s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0]
if s1.shape != s2.shape:
raise ValueError('incompatible shapes: %s == %s'\
% (s1.shape, s2.shape))
(nnod0, dim) = coors.shape
nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1)
(nel0, nnel) = conn.shape
nel = nel0 * n_rep
dd = nm.zeros((dim,), dtype=nm.float64)
dd[idim] = bb[1] - bb[0]
m1, m2 = match_grid_plane(coors[s1], coors[s2], idim)
oconn = nm.zeros((nel, nnel), dtype=nm.int32)
ocoors = nm.zeros((nnod, dim), dtype=nm.float64)
ongrps = nm.zeros((nnod,), dtype=nm.int32)
if type(ndmap) is bool:
ret_ndmap = ndmap
else:
ret_ndmap= True
ndmap_out = nm.zeros((nnod,), dtype=nm.int32)
el_off = 0
nd_off = 0
for ii in range(n_rep):
if ii == 0:
oconn[0:nel0,:] = conn
ocoors[0:nnod0,:] = coors
ongrps[0:nnod0] = ngrps.squeeze()
nd_off += nnod0
mapto = s2[m2]
mask = nm.ones((nnod0,), dtype=nm.int32)
mask[s1] = 0
remap0 = nm.cumsum(mask) - 1
nnod0r = nnod0 - s1.shape[0]
cidx = nm.where(mask)
if ret_ndmap:
ndmap_out[0:nnod0] = nm.arange(nnod0)
else:
remap = remap0 + nd_off
remap[s1[m1]] = mapto
mapto = remap[s2[m2]]
ocoors[nd_off:(nd_off + nnod0r),:] =\
(coors[cidx,:] + ii * dd)
ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze()
oconn[el_off:(el_off + nel0),:] = remap[conn]
if ret_ndmap:
ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0]
nd_off += nnod0r
el_off += nel0
if ret_ndmap:
if ndmap is not None:
max_nd_ref = nm.max(ndmap)
idxs = nm.where(ndmap_out > max_nd_ref)
ndmap_out[idxs] = ndmap[ndmap_out[idxs]]
return oconn, ocoors, ongrps, ndmap_out
else:
return oconn, ocoors, ongrps
def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False):
"""
Generate a new mesh by repeating a given periodic element
along each axis.
Parameters
----------
mesh : Mesh instance
The input periodic FE mesh.
grid : array
Number of repetition along each axis.
scale : float, optional
Scaling factor.
eps : float, optional
Tolerance for boundary detection.
ret_ndmap : bool, optional
If True, return global node map.
Returns
-------
mesh_out : Mesh instance
FE mesh.
ndmap : array
Maps: actual node id --> node id in the reference cell.
"""
bbox = mesh.get_bounding_box()
if grid is None:
iscale = max(int(1.0 / scale), 1)
grid = [iscale] * mesh.dim
conn = mesh.get_conn(mesh.descs[0])
mat_ids = mesh.cmesh.cell_groups
coors = mesh.coors
ngrps = mesh.cmesh.vertex_groups
nrep = nm.prod(grid)
ndmap = None
output('repeating %s ...' % grid)
nblk = 1
for ii, gr in enumerate(grid):
if ret_ndmap:
(conn, coors,
ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps,
ii, gr, bbox.transpose()[ii],
eps=eps, ndmap=ndmap)
ndmap = ndmap0
else:
conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps,
ii, gr, bbox.transpose()[ii],
eps=eps)
nblk *= gr
output('...done')
mat_ids = nm.tile(mat_ids, (nrep,))
mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps,
[conn], [mat_ids], [mesh.descs[0]])
if ret_ndmap:
return mesh_out, ndmap
else:
return mesh_out
def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh',
verbose=False):
"""
Create sphere or cube mesh according to `kind` in the given
directory if it does not exist and return path to it.
"""
import os
from sfepy import data_dir
defdir = os.path.join(data_dir, 'meshes')
if mesh_dir is None:
mesh_dir = defdir
def retype(args, types, defaults):
args=list(args)
args.extend(defaults[len(args):len(defaults)])
return tuple([type(value) for type, value in zip(types, args) ])
if kind == 'sphere':
default = [5, 41, args[0]]
args = retype(args, [float, int, float], default)
mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i')
else:
assert_(kind == 'cube')
args = retype(args,
(int, float, int, float, int, float),
(args[0], args[1], args[0], args[1], args[0], args[1]))
mesh_pattern = os.path.join(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f')
if verbose:
output(args)
filename = mesh_pattern % args
if not force_create:
if os.path.exists(filename): return filename
if os.path.exists(filename + '.mesh') : return filename + '.mesh'
if os.path.exists(filename + '.vtk'): return filename + '.vtk'
if kind == 'cube':
filename = filename + suffix
ensure_path(filename)
output('creating new cube mesh')
output('(%i nodes in %.2f) x (%i nodes in %.2f) x (%i nodes in %.2f)'
% args)
output('to file %s...' % filename)
mesh = gen_block_mesh(args[1::2], args[0::2],
(0.0, 0.0, 0.0), name=filename)
mesh.write(filename, io='auto')
output('...done')
else:
import subprocess, shutil, tempfile
filename = filename + '.mesh'
ensure_path(filename)
output('creating new sphere mesh (%i nodes, r=%.2f) and gradation %d'
% args)
output('to file %s...' % filename)
f = open(os.path.join(defdir, 'quantum', 'sphere.geo'))
tmp_dir = tempfile.mkdtemp()
tmpfile = os.path.join(tmp_dir, 'sphere.geo.temp')
ff = open(tmpfile, "w")
ff.write("""
R = %i.0;
n = %i.0;
dens = %f;
""" % args)
ff.write(f.read())
f.close()
ff.close()
subprocess.call(['gmsh', '-3', tmpfile, '-format', 'mesh',
'-o', filename])
shutil.rmtree(tmp_dir)
output('...done')
return filename
def gen_mesh_from_string(mesh_name, mesh_dir):
import re
result = re.match('^\\s*([a-zA-Z]+)[:\\(]([^\\):]*)[:\\)](\\*)?\\s*$',
mesh_name)
if result is None:
return mesh_name
else:
args = re.split(',', result.group(2))
kind = result.group(1)
return gen_misc_mesh(mesh_dir, result.group(3)=='*', kind, args)
def gen_mesh_from_geom(geo, a=None, verbose=False, refine=False):
"""
Runs mesh generator - tetgen for 3D or triangle for 2D meshes.
Parameters
----------
geo : geometry
geometry description
a : int, optional
a maximum area/volume constraint
verbose : bool, optional
detailed information
refine : bool, optional
refines mesh
Returns
-------
mesh : Mesh instance
triangular or tetrahedral mesh
"""
import os.path as op
import pexpect
import tempfile
import shutil
tmp_dir = tempfile.mkdtemp()
polyfilename = op.join(tmp_dir, 'meshgen.poly')
# write geometry to poly file
geo.to_poly_file(polyfilename)
meshgen_call = {2: ('triangle', ''), 3: ('tetgen', 'BFENk')}
params = "-ACp"
params += "q" if refine else ''
params += "V" if verbose else "Q"
params += meshgen_call[geo.dim][1]
if a is not None:
params += "a%f" % (a)
params += " %s" % (polyfilename)
cmd = "%s %s" % (meshgen_call[geo.dim][0], params)
if verbose: print("Generating mesh using", cmd)
p=pexpect.run(cmd, timeout=None)
bname, ext = op.splitext(polyfilename)
if geo.dim == 2:
mesh = Mesh.from_file(bname + '.1.node')
if geo.dim == 3:
mesh = Mesh.from_file(bname + '.1.vtk')
shutil.rmtree(tmp_dir)
return mesh
def gen_mesh_from_voxels(voxels, dims, etype='q'):
"""
Generate FE mesh from voxels (volumetric data).
Parameters
----------
voxels : array
Voxel matrix, 1=material.
dims : array
Size of one voxel.
etype : integer, optional
'q' - quadrilateral or hexahedral elements
't' - triangular or tetrahedral elements
Returns
-------
mesh : Mesh instance
Finite element mesh.
"""
dims = nm.array(dims).squeeze()
dim = len(dims)
nddims = nm.array(voxels.shape) + 2
nodemtx = nm.zeros(nddims, dtype=nm.int32)
if dim == 2:
#iy, ix = nm.where(voxels.transpose())
iy, ix = nm.where(voxels)
nel = ix.shape[0]
if etype == 'q':
nodemtx[ix,iy] += 1
nodemtx[ix + 1,iy] += 1
nodemtx[ix + 1,iy + 1] += 1
nodemtx[ix,iy + 1] += 1
elif etype == 't':
nodemtx[ix,iy] += 2
nodemtx[ix + 1,iy] += 1
nodemtx[ix + 1,iy + 1] += 2
nodemtx[ix,iy + 1] += 1
nel *= 2
elif dim == 3:
#iy, ix, iz = nm.where(voxels.transpose(1, 0, 2))
iy, ix, iz = nm.where(voxels)
nel = ix.shape[0]
if etype == 'q':
nodemtx[ix,iy,iz] += 1
nodemtx[ix + 1,iy,iz] += 1
nodemtx[ix + 1,iy + 1,iz] += 1
nodemtx[ix,iy + 1,iz] += 1
nodemtx[ix,iy,iz + 1] += 1
nodemtx[ix + 1,iy,iz + 1] += 1
nodemtx[ix + 1,iy + 1,iz + 1] += 1
nodemtx[ix,iy + 1,iz + 1] += 1
elif etype == 't':
nodemtx[ix,iy,iz] += 6
nodemtx[ix + 1,iy,iz] += 2
nodemtx[ix + 1,iy + 1,iz] += 2
nodemtx[ix,iy + 1,iz] += 2
nodemtx[ix,iy,iz + 1] += 2
nodemtx[ix + 1,iy,iz + 1] += 2
nodemtx[ix + 1,iy + 1,iz + 1] += 6
nodemtx[ix,iy + 1,iz + 1] += 2
nel *= 6
else:
msg = 'incorrect voxel dimension! (%d)' % dim
raise ValueError(msg)
ndidx = nm.where(nodemtx)
coors = nm.array(ndidx).transpose() * dims
nnod = coors.shape[0]
nodeid = -nm.ones(nddims, dtype=nm.int32)
nodeid[ndidx] = nm.arange(nnod)
# generate elements
if dim == 2:
elems = nm.array([nodeid[ix,iy],
nodeid[ix + 1,iy],
nodeid[ix + 1,iy + 1],
nodeid[ix,iy + 1]]).transpose()
elif dim == 3:
elems = nm.array([nodeid[ix,iy,iz],
nodeid[ix + 1,iy,iz],
nodeid[ix + 1,iy + 1,iz],
nodeid[ix,iy + 1,iz],
nodeid[ix,iy,iz + 1],
nodeid[ix + 1,iy,iz + 1],
nodeid[ix + 1,iy + 1,iz + 1],
nodeid[ix,iy + 1,iz + 1]]).transpose()
if etype == 't':
elems = elems_q2t(elems)
eid = etype + str(dim)
eltab = {'q2': 4, 'q3': 8, 't2': 3, 't3': 4}
mesh = Mesh.from_data('voxel_data',
coors, nm.ones((nnod,), dtype=nm.int32),
[nm.ascontiguousarray(elems)],
[nm.ones((nel,), dtype=nm.int32)],
['%d_%d' % (dim, eltab[eid])])
return mesh
def main():
mesh = gen_block_mesh(nm.array((1.0, 2.0, 3.0)),
nm.array((10,10,10)), nm.array((1.0, 2.0, 3.0)),
name='')
mesh.write('0.mesh', io = 'auto')
mesh = gen_cylinder_mesh(nm.array((1.0, 1.0, 2.0, 2.0, 3)),
nm.array((10,10,10)), nm.array((1.0, 2.0, 3.0)),
is_open=False, open_angle = 0.0,
name='')
mesh.write('1.mesh', io = 'auto')
mesh = gen_cylinder_mesh(nm.array((1.0, 1.0, 2.0, 2.0, 3)),
nm.array((10,10,10)), nm.array((1.0, 2.0, 3.0)),
is_open=True, open_angle = 0.0,
name='')
mesh.write('2.mesh', io = 'auto')
mesh = gen_cylinder_mesh(nm.array((1.0, 1.0, 2.0, 2.0, 3)),
nm.array((10,10,10)), nm.array((1.0, 2.0, 3.0)),
is_open=True, open_angle = 0.5,
name='')
mesh.write('3.mesh', io = 'auto')
mesh = gen_cylinder_mesh(nm.array((0.0, 0.0, 2.0, 2.0, 3)),
nm.array((10,10,10)), nm.array((1.0, 2.0, 3.0)),
is_open=False, open_angle = 0.0,
name='')
mesh.write('4.mesh', io = 'auto')
mesh = gen_cylinder_mesh(nm.array((0.0, 0.0, 1.0, 2.0, 3)),
nm.array((10,10,10)), nm.array((1.0, 2.0, 3.0)),
is_open=True, open_angle = 0.5,
name='')
mesh.write('5.mesh', io = 'auto')
mesh = gen_cylinder_mesh(nm.array((0.0, 0.0, 1.0, 2.0, 3)),
nm.array((10,10,10)), nm.array((1.0, 2.0, 3.0)),
is_open=True, open_angle = 0.5, non_uniform=True,
name='')
mesh.write('6.mesh', io = 'auto')
mesh = gen_cylinder_mesh(nm.array((0.5, 0.5, 1.0, 2.0, 3)),
nm.array((10,10,10)), nm.array((1.0, 2.0, 3.0)),
is_open=True, open_angle = 0.5, non_uniform=True,
name='')
mesh.write('7.mesh', io = 'auto')
if __name__ == '__main__':
main()
| [
"sfepy.linalg.cycle",
"sfepy.discrete.fem.mesh.Mesh.from_data",
"sfepy.base.ioutils.ensure_path",
"sfepy.discrete.fem.mesh.Mesh.from_file",
"sfepy.discrete.fem.periodic.match_grid_plane",
"sfepy.base.base.output",
"sfepy.base.base.assert_",
"sfepy.mesh.mesh_tools.elems_q2t"
] | [((135, 155), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (150, 155), False, 'import sys\n'), ((756, 773), 'numpy.asarray', 'nm.asarray', (['shape'], {}), '(shape)\n', (766, 773), True, 'import numpy as nm\n'), ((799, 821), 'sfepy.base.base.assert_', 'assert_', (['(1 <= dim <= 3)'], {}), '(1 <= dim <= 3)\n', (806, 821), False, 'from sfepy.base.base import output, assert_\n'), ((835, 849), 'numpy.prod', 'nm.prod', (['shape'], {}), '(shape)\n', (842, 849), True, 'import numpy as nm\n'), ((861, 879), 'numpy.prod', 'nm.prod', (['(shape - 1)'], {}), '(shape - 1)\n', (868, 879), True, 'import numpy as nm\n'), ((892, 924), 'numpy.arange', 'nm.arange', (['n_nod'], {'dtype': 'nm.int32'}), '(n_nod, dtype=nm.int32)\n', (901, 924), True, 'import numpy as nm\n'), ((2543, 2577), 'numpy.asarray', 'nm.asarray', (['dims'], {'dtype': 'nm.float64'}), '(dims, dtype=nm.float64)\n', (2553, 2577), True, 'import numpy as nm\n'), ((2590, 2623), 'numpy.asarray', 'nm.asarray', (['shape'], {'dtype': 'nm.int32'}), '(shape, dtype=nm.int32)\n', (2600, 2623), True, 'import numpy as nm\n'), ((2637, 2673), 'numpy.asarray', 'nm.asarray', (['centre'], {'dtype': 'nm.float64'}), '(centre, dtype=nm.float64)\n', (2647, 2673), True, 'import numpy as nm\n'), ((2762, 2776), 'numpy.prod', 'nm.prod', (['shape'], {}), '(shape)\n', (2769, 2776), True, 'import numpy as nm\n'), ((2781, 2841), 'sfepy.base.base.output', 'output', (["('generating %d vertices...' % n_nod)"], {'verbose': 'verbose'}), "('generating %d vertices...' % n_nod, verbose=verbose)\n", (2787, 2841), False, 'from sfepy.base.base import output, assert_\n'), ((3017, 3051), 'sfepy.base.base.output', 'output', (['"""...done"""'], {'verbose': 'verbose'}), "('...done', verbose=verbose)\n", (3023, 3051), False, 'from sfepy.base.base import output, assert_\n'), ((3064, 3082), 'numpy.prod', 'nm.prod', (['(shape - 1)'], {}), '(shape - 1)\n', (3071, 3082), True, 'import numpy as nm\n'), ((3087, 3143), 'sfepy.base.base.output', 'output', (["('generating %d cells...' % n_el)"], {'verbose': 'verbose'}), "('generating %d cells...' % n_el, verbose=verbose)\n", (3093, 3143), False, 'from sfepy.base.base import output, assert_\n'), ((3159, 3192), 'numpy.empty', 'nm.empty', (['(n_el,)'], {'dtype': 'nm.int32'}), '((n_el,), dtype=nm.int32)\n', (3167, 3192), True, 'import numpy as nm\n'), ((3271, 3305), 'sfepy.base.base.output', 'output', (['"""...done"""'], {'verbose': 'verbose'}), "('...done', verbose=verbose)\n", (3277, 3305), False, 'from sfepy.base.base import output, assert_\n'), ((3318, 3378), 'sfepy.discrete.fem.mesh.Mesh.from_data', 'Mesh.from_data', (['name', 'coors', 'None', '[conn]', '[mat_ids]', '[desc]'], {}), '(name, coors, None, [conn], [mat_ids], [desc])\n', (3332, 3378), False, 'from sfepy.discrete.fem.mesh import Mesh\n'), ((4747, 4781), 'numpy.asarray', 'nm.asarray', (['dims'], {'dtype': 'nm.float64'}), '(dims, dtype=nm.float64)\n', (4757, 4781), True, 'import numpy as nm\n'), ((4794, 4827), 'numpy.asarray', 'nm.asarray', (['shape'], {'dtype': 'nm.int32'}), '(shape, dtype=nm.int32)\n', (4804, 4827), True, 'import numpy as nm\n'), ((4841, 4877), 'numpy.asarray', 'nm.asarray', (['centre'], {'dtype': 'nm.float64'}), '(centre, dtype=nm.float64)\n', (4851, 4877), True, 'import numpy as nm\n'), ((5260, 5300), 'numpy.zeros', 'nm.zeros', (['(nr, nnfi, nl)'], {'dtype': 'nm.int32'}), '((nr, nnfi, nl), dtype=nm.int32)\n', (5268, 5300), True, 'import numpy as nm\n'), ((5346, 5384), 'numpy.zeros', 'nm.zeros', (['(n_nod, 3)'], {'dtype': 'nm.float64'}), '((n_nod, 3), dtype=nm.float64)\n', (5354, 5384), True, 'import numpy as nm\n'), ((5399, 5455), 'numpy.linspace', 'nm.linspace', (['open_angle', '(open_angle + nfi * dfi)', '(nfi + 1)'], {}), '(open_angle, open_angle + nfi * dfi, nfi + 1)\n', (5410, 5455), True, 'import numpy as nm\n'), ((5461, 5489), 'numpy.linspace', 'nm.linspace', (['(0.0)', 'length', 'nl'], {}), '(0.0, length, nl)\n', (5472, 5489), True, 'import numpy as nm\n'), ((5961, 6021), 'sfepy.base.base.output', 'output', (["('generating %d vertices...' % n_nod)"], {'verbose': 'verbose'}), "('generating %d vertices...' % n_nod, verbose=verbose)\n", (5967, 6021), False, 'from sfepy.base.base import output, assert_\n'), ((6047, 6056), 'six.moves.range', 'range', (['nr'], {}), '(nr)\n', (6052, 6056), False, 'from six.moves import range\n'), ((6482, 6502), 'sfepy.base.base.assert_', 'assert_', (['(ii == n_nod)'], {}), '(ii == n_nod)\n', (6489, 6502), False, 'from sfepy.base.base import output, assert_\n'), ((6507, 6541), 'sfepy.base.base.output', 'output', (['"""...done"""'], {'verbose': 'verbose'}), "('...done', verbose=verbose)\n", (6513, 6541), False, 'from sfepy.base.base import output, assert_\n'), ((6591, 6626), 'numpy.zeros', 'nm.zeros', (['(n_el, 8)'], {'dtype': 'nm.int32'}), '((n_el, 8), dtype=nm.int32)\n', (6599, 6626), True, 'import numpy as nm\n'), ((6632, 6688), 'sfepy.base.base.output', 'output', (["('generating %d cells...' % n_el)"], {'verbose': 'verbose'}), "('generating %d cells...' % n_el, verbose=verbose)\n", (6638, 6688), False, 'from sfepy.base.base import output, assert_\n'), ((6724, 6753), 'sfepy.linalg.cycle', 'cycle', (['[nr - 1, nnfi, nl - 1]'], {}), '([nr - 1, nnfi, nl - 1])\n', (6729, 6753), False, 'from sfepy.linalg import cycle\n'), ((7407, 7440), 'numpy.zeros', 'nm.zeros', (['(n_el,)'], {'dtype': 'nm.int32'}), '((n_el,), dtype=nm.int32)\n', (7415, 7440), True, 'import numpy as nm\n'), ((7504, 7538), 'sfepy.base.base.output', 'output', (['"""...done"""'], {'verbose': 'verbose'}), "('...done', verbose=verbose)\n", (7510, 7538), False, 'from sfepy.base.base import output, assert_\n'), ((7660, 7719), 'sfepy.discrete.fem.mesh.Mesh.from_data', 'Mesh.from_data', (['name', 'coors', 'None', '[conn]', '[mat_id]', '[desc]'], {}), '(name, coors, None, [conn], [mat_id], [desc])\n', (7674, 7719), False, 'from sfepy.discrete.fem.mesh import Mesh\n'), ((8065, 8085), 'numpy.empty_like', 'nm.empty_like', (['coors'], {}), '(coors)\n', (8078, 8085), True, 'import numpy as nm\n'), ((11013, 11049), 'numpy.asarray', 'nm.asarray', (['b_dims'], {'dtype': 'nm.float64'}), '(b_dims, dtype=nm.float64)\n', (11023, 11049), True, 'import numpy as nm\n'), ((11064, 11099), 'numpy.asarray', 'nm.asarray', (['b_shape'], {'dtype': 'nm.int32'}), '(b_shape, dtype=nm.int32)\n', (11074, 11099), True, 'import numpy as nm\n'), ((11113, 11149), 'numpy.asarray', 'nm.asarray', (['e_dims'], {'dtype': 'nm.float64'}), '(e_dims, dtype=nm.float64)\n', (11123, 11149), True, 'import numpy as nm\n'), ((11163, 11199), 'numpy.asarray', 'nm.asarray', (['centre'], {'dtype': 'nm.float64'}), '(centre, dtype=nm.float64)\n', (11173, 11199), True, 'import numpy as nm\n'), ((13654, 13688), 'numpy.zeros', 'nm.zeros', (['(dim,)'], {'dtype': 'nm.float64'}), '((dim,), dtype=nm.float64)\n', (13662, 13688), True, 'import numpy as nm\n'), ((13732, 13776), 'sfepy.discrete.fem.periodic.match_grid_plane', 'match_grid_plane', (['coors[s1]', 'coors[s2]', 'idim'], {}), '(coors[s1], coors[s2], idim)\n', (13748, 13776), False, 'from sfepy.discrete.fem.periodic import match_grid_plane\n'), ((13790, 13827), 'numpy.zeros', 'nm.zeros', (['(nel, nnel)'], {'dtype': 'nm.int32'}), '((nel, nnel), dtype=nm.int32)\n', (13798, 13827), True, 'import numpy as nm\n'), ((13841, 13880), 'numpy.zeros', 'nm.zeros', (['(nnod, dim)'], {'dtype': 'nm.float64'}), '((nnod, dim), dtype=nm.float64)\n', (13849, 13880), True, 'import numpy as nm\n'), ((13894, 13927), 'numpy.zeros', 'nm.zeros', (['(nnod,)'], {'dtype': 'nm.int32'}), '((nnod,), dtype=nm.int32)\n', (13902, 13927), True, 'import numpy as nm\n'), ((14118, 14130), 'six.moves.range', 'range', (['n_rep'], {}), '(n_rep)\n', (14123, 14130), False, 'from six.moves import range\n'), ((16329, 16342), 'numpy.prod', 'nm.prod', (['grid'], {}), '(grid)\n', (16336, 16342), True, 'import numpy as nm\n'), ((16365, 16398), 'sfepy.base.base.output', 'output', (["('repeating %s ...' % grid)"], {}), "('repeating %s ...' % grid)\n", (16371, 16398), False, 'from sfepy.base.base import output, assert_\n'), ((16959, 16976), 'sfepy.base.base.output', 'output', (['"""...done"""'], {}), "('...done')\n", (16965, 16976), False, 'from sfepy.base.base import output, assert_\n'), ((16992, 17017), 'numpy.tile', 'nm.tile', (['mat_ids', '(nrep,)'], {}), '(mat_ids, (nrep,))\n', (16999, 17017), True, 'import numpy as nm\n'), ((17033, 17124), 'sfepy.discrete.fem.mesh.Mesh.from_data', 'Mesh.from_data', (['"""tiled mesh"""', '(coors * scale)', 'ngrps', '[conn]', '[mat_ids]', '[mesh.descs[0]]'], {}), "('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh\n .descs[0]])\n", (17047, 17124), False, 'from sfepy.discrete.fem.mesh import Mesh\n'), ((17536, 17568), 'os.path.join', 'os.path.join', (['data_dir', '"""meshes"""'], {}), "(data_dir, 'meshes')\n", (17548, 17568), False, 'import os\n'), ((19896, 19968), 're.match', 're.match', (['"""^\\\\s*([a-zA-Z]+)[:\\\\(]([^\\\\):]*)[:\\\\)](\\\\*)?\\\\s*$"""', 'mesh_name'], {}), "('^\\\\s*([a-zA-Z]+)[:\\\\(]([^\\\\):]*)[:\\\\)](\\\\*)?\\\\s*$', mesh_name)\n", (19904, 19968), False, 'import re\n'), ((20787, 20805), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (20803, 20805), False, 'import subprocess, shutil, tempfile\n'), ((20825, 20857), 'os.path.join', 'op.join', (['tmp_dir', '"""meshgen.poly"""'], {}), "(tmp_dir, 'meshgen.poly')\n", (20832, 20857), True, 'import os.path as op\n'), ((21331, 21361), 'pexpect.run', 'pexpect.run', (['cmd'], {'timeout': 'None'}), '(cmd, timeout=None)\n', (21342, 21361), False, 'import pexpect\n'), ((21379, 21404), 'os.path.splitext', 'op.splitext', (['polyfilename'], {}), '(polyfilename)\n', (21390, 21404), True, 'import os.path as op\n'), ((21549, 21571), 'shutil.rmtree', 'shutil.rmtree', (['tmp_dir'], {}), '(tmp_dir)\n', (21562, 21571), False, 'import subprocess, shutil, tempfile\n'), ((22157, 22189), 'numpy.zeros', 'nm.zeros', (['nddims'], {'dtype': 'nm.int32'}), '(nddims, dtype=nm.int32)\n', (22165, 22189), True, 'import numpy as nm\n'), ((23659, 23676), 'numpy.where', 'nm.where', (['nodemtx'], {}), '(nodemtx)\n', (23667, 23676), True, 'import numpy as nm\n'), ((23817, 23832), 'numpy.arange', 'nm.arange', (['nnod'], {}), '(nnod)\n', (23826, 23832), True, 'import numpy as nm\n'), ((981, 1016), 'numpy.zeros', 'nm.zeros', (['(n_el, 2)'], {'dtype': 'nm.int32'}), '((n_el, 2), dtype=nm.int32)\n', (989, 1016), True, 'import numpy as nm\n'), ((4959, 4993), 'numpy.array', 'nm.array', (['[0.5 * length, 0.0, 0.0]'], {}), '([0.5 * length, 0.0, 0.0])\n', (4967, 4993), True, 'import numpy as nm\n'), ((5524, 5557), 'numpy.zeros', 'nm.zeros', (['(nr,)'], {'dtype': 'nm.float64'}), '((nr,), dtype=nm.float64)\n', (5532, 5557), True, 'import numpy as nm\n'), ((5572, 5590), 'numpy.zeros_like', 'nm.zeros_like', (['ras'], {}), '(ras)\n', (5585, 5590), True, 'import numpy as nm\n'), ((5727, 5739), 'six.moves.range', 'range', (['(1)', 'nr'], {}), '(1, nr)\n', (5732, 5739), False, 'from six.moves import range\n'), ((5869, 5892), 'numpy.linspace', 'nm.linspace', (['a1', 'a2', 'nr'], {}), '(a1, a2, nr)\n', (5880, 5892), True, 'import numpy as nm\n'), ((5907, 5930), 'numpy.linspace', 'nm.linspace', (['b1', 'b2', 'nr'], {}), '(b1, b2, nr)\n', (5918, 5930), True, 'import numpy as nm\n'), ((11493, 11503), 'numpy.log', 'nm.log', (['nc'], {}), '(nc)\n', (11499, 11503), True, 'import numpy as nm\n'), ((13281, 13321), 'numpy.nonzero', 'nm.nonzero', (['(coors[:, idim] < bb[0] + eps)'], {}), '(coors[:, idim] < bb[0] + eps)\n', (13291, 13321), True, 'import numpy as nm\n'), ((13335, 13375), 'numpy.nonzero', 'nm.nonzero', (['(coors[:, idim] > bb[1] - eps)'], {}), '(coors[:, idim] > bb[1] - eps)\n', (13345, 13375), True, 'import numpy as nm\n'), ((14038, 14071), 'numpy.zeros', 'nm.zeros', (['(nnod,)'], {'dtype': 'nm.int32'}), '((nnod,), dtype=nm.int32)\n', (14046, 14071), True, 'import numpy as nm\n'), ((17954, 17999), 'os.path.join', 'os.path.join', (['mesh_dir', '"""sphere-%.2f-%.2f-%i"""'], {}), "(mesh_dir, 'sphere-%.2f-%.2f-%i')\n", (17966, 17999), False, 'import os\n'), ((18019, 18042), 'sfepy.base.base.assert_', 'assert_', (["(kind == 'cube')"], {}), "(kind == 'cube')\n", (18026, 18042), False, 'from sfepy.base.base import output, assert_\n'), ((18233, 18287), 'os.path.join', 'os.path.join', (['mesh_dir', '"""cube-%i_%.2f-%i_%.2f-%i_%.2f"""'], {}), "(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f')\n", (18245, 18287), False, 'import os\n'), ((18313, 18325), 'sfepy.base.base.output', 'output', (['args'], {}), '(args)\n', (18319, 18325), False, 'from sfepy.base.base import output, assert_\n'), ((18398, 18422), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (18412, 18422), False, 'import os\n'), ((18451, 18485), 'os.path.exists', 'os.path.exists', (["(filename + '.mesh')"], {}), "(filename + '.mesh')\n", (18465, 18485), False, 'import os\n'), ((18525, 18558), 'os.path.exists', 'os.path.exists', (["(filename + '.vtk')"], {}), "(filename + '.vtk')\n", (18539, 18558), False, 'import os\n'), ((18654, 18675), 'sfepy.base.ioutils.ensure_path', 'ensure_path', (['filename'], {}), '(filename)\n', (18665, 18675), False, 'from sfepy.base.ioutils import ensure_path\n'), ((18685, 18717), 'sfepy.base.base.output', 'output', (['"""creating new cube mesh"""'], {}), "('creating new cube mesh')\n", (18691, 18717), False, 'from sfepy.base.base import output, assert_\n'), ((18726, 18803), 'sfepy.base.base.output', 'output', (["('(%i nodes in %.2f) x (%i nodes in %.2f) x (%i nodes in %.2f)' % args)"], {}), "('(%i nodes in %.2f) x (%i nodes in %.2f) x (%i nodes in %.2f)' % args)\n", (18732, 18803), False, 'from sfepy.base.base import output, assert_\n'), ((18827, 18861), 'sfepy.base.base.output', 'output', (["('to file %s...' % filename)"], {}), "('to file %s...' % filename)\n", (18833, 18861), False, 'from sfepy.base.base import output, assert_\n'), ((19027, 19044), 'sfepy.base.base.output', 'output', (['"""...done"""'], {}), "('...done')\n", (19033, 19044), False, 'from sfepy.base.base import output, assert_\n'), ((19146, 19167), 'sfepy.base.ioutils.ensure_path', 'ensure_path', (['filename'], {}), '(filename)\n', (19157, 19167), False, 'from sfepy.base.ioutils import ensure_path\n'), ((19177, 19254), 'sfepy.base.base.output', 'output', (["('creating new sphere mesh (%i nodes, r=%.2f) and gradation %d' % args)"], {}), "('creating new sphere mesh (%i nodes, r=%.2f) and gradation %d' % args)\n", (19183, 19254), False, 'from sfepy.base.base import output, assert_\n'), ((19278, 19312), 'sfepy.base.base.output', 'output', (["('to file %s...' % filename)"], {}), "('to file %s...' % filename)\n", (19284, 19312), False, 'from sfepy.base.base import output, assert_\n'), ((19396, 19414), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (19412, 19414), False, 'import subprocess, shutil, tempfile\n'), ((19433, 19473), 'os.path.join', 'os.path.join', (['tmp_dir', '"""sphere.geo.temp"""'], {}), "(tmp_dir, 'sphere.geo.temp')\n", (19445, 19473), False, 'import os\n'), ((19642, 19717), 'subprocess.call', 'subprocess.call', (["['gmsh', '-3', tmpfile, '-format', 'mesh', '-o', filename]"], {}), "(['gmsh', '-3', tmpfile, '-format', 'mesh', '-o', filename])\n", (19657, 19717), False, 'import subprocess, shutil, tempfile\n'), ((19751, 19773), 'shutil.rmtree', 'shutil.rmtree', (['tmp_dir'], {}), '(tmp_dir)\n', (19764, 19773), False, 'import subprocess, shutil, tempfile\n'), ((19782, 19799), 'sfepy.base.base.output', 'output', (['"""...done"""'], {}), "('...done')\n", (19788, 19799), False, 'from sfepy.base.base import output, assert_\n'), ((21441, 21474), 'sfepy.discrete.fem.mesh.Mesh.from_file', 'Mesh.from_file', (["(bname + '.1.node')"], {}), "(bname + '.1.node')\n", (21455, 21474), False, 'from sfepy.discrete.fem.mesh import Mesh\n'), ((21511, 21543), 'sfepy.discrete.fem.mesh.Mesh.from_file', 'Mesh.from_file', (["(bname + '.1.vtk')"], {}), "(bname + '.1.vtk')\n", (21525, 21543), False, 'from sfepy.discrete.fem.mesh import Mesh\n'), ((22115, 22137), 'numpy.array', 'nm.array', (['voxels.shape'], {}), '(voxels.shape)\n', (22123, 22137), True, 'import numpy as nm\n'), ((22272, 22288), 'numpy.where', 'nm.where', (['voxels'], {}), '(voxels)\n', (22280, 22288), True, 'import numpy as nm\n'), ((23765, 23796), 'numpy.ones', 'nm.ones', (['nddims'], {'dtype': 'nm.int32'}), '(nddims, dtype=nm.int32)\n', (23772, 23796), True, 'import numpy as nm\n'), ((24539, 24555), 'sfepy.mesh.mesh_tools.elems_q2t', 'elems_q2t', (['elems'], {}), '(elems)\n', (24548, 24555), False, 'from sfepy.mesh.mesh_tools import elems_q2t\n'), ((24707, 24739), 'numpy.ones', 'nm.ones', (['(nnod,)'], {'dtype': 'nm.int32'}), '((nnod,), dtype=nm.int32)\n', (24714, 24739), True, 'import numpy as nm\n'), ((24973, 24998), 'numpy.array', 'nm.array', (['(1.0, 2.0, 3.0)'], {}), '((1.0, 2.0, 3.0))\n', (24981, 24998), True, 'import numpy as nm\n'), ((25026, 25048), 'numpy.array', 'nm.array', (['(10, 10, 10)'], {}), '((10, 10, 10))\n', (25034, 25048), True, 'import numpy as nm\n'), ((25048, 25073), 'numpy.array', 'nm.array', (['(1.0, 2.0, 3.0)'], {}), '((1.0, 2.0, 3.0))\n', (25056, 25073), True, 'import numpy as nm\n'), ((25178, 25211), 'numpy.array', 'nm.array', (['(1.0, 1.0, 2.0, 2.0, 3)'], {}), '((1.0, 1.0, 2.0, 2.0, 3))\n', (25186, 25211), True, 'import numpy as nm\n'), ((25242, 25264), 'numpy.array', 'nm.array', (['(10, 10, 10)'], {}), '((10, 10, 10))\n', (25250, 25264), True, 'import numpy as nm\n'), ((25264, 25289), 'numpy.array', 'nm.array', (['(1.0, 2.0, 3.0)'], {}), '((1.0, 2.0, 3.0))\n', (25272, 25289), True, 'import numpy as nm\n'), ((25458, 25491), 'numpy.array', 'nm.array', (['(1.0, 1.0, 2.0, 2.0, 3)'], {}), '((1.0, 1.0, 2.0, 2.0, 3))\n', (25466, 25491), True, 'import numpy as nm\n'), ((25522, 25544), 'numpy.array', 'nm.array', (['(10, 10, 10)'], {}), '((10, 10, 10))\n', (25530, 25544), True, 'import numpy as nm\n'), ((25544, 25569), 'numpy.array', 'nm.array', (['(1.0, 2.0, 3.0)'], {}), '((1.0, 2.0, 3.0))\n', (25552, 25569), True, 'import numpy as nm\n'), ((25737, 25770), 'numpy.array', 'nm.array', (['(1.0, 1.0, 2.0, 2.0, 3)'], {}), '((1.0, 1.0, 2.0, 2.0, 3))\n', (25745, 25770), True, 'import numpy as nm\n'), ((25801, 25823), 'numpy.array', 'nm.array', (['(10, 10, 10)'], {}), '((10, 10, 10))\n', (25809, 25823), True, 'import numpy as nm\n'), ((25823, 25848), 'numpy.array', 'nm.array', (['(1.0, 2.0, 3.0)'], {}), '((1.0, 2.0, 3.0))\n', (25831, 25848), True, 'import numpy as nm\n'), ((26017, 26050), 'numpy.array', 'nm.array', (['(0.0, 0.0, 2.0, 2.0, 3)'], {}), '((0.0, 0.0, 2.0, 2.0, 3))\n', (26025, 26050), True, 'import numpy as nm\n'), ((26081, 26103), 'numpy.array', 'nm.array', (['(10, 10, 10)'], {}), '((10, 10, 10))\n', (26089, 26103), True, 'import numpy as nm\n'), ((26103, 26128), 'numpy.array', 'nm.array', (['(1.0, 2.0, 3.0)'], {}), '((1.0, 2.0, 3.0))\n', (26111, 26128), True, 'import numpy as nm\n'), ((26298, 26331), 'numpy.array', 'nm.array', (['(0.0, 0.0, 1.0, 2.0, 3)'], {}), '((0.0, 0.0, 1.0, 2.0, 3))\n', (26306, 26331), True, 'import numpy as nm\n'), ((26362, 26384), 'numpy.array', 'nm.array', (['(10, 10, 10)'], {}), '((10, 10, 10))\n', (26370, 26384), True, 'import numpy as nm\n'), ((26384, 26409), 'numpy.array', 'nm.array', (['(1.0, 2.0, 3.0)'], {}), '((1.0, 2.0, 3.0))\n', (26392, 26409), True, 'import numpy as nm\n'), ((26578, 26611), 'numpy.array', 'nm.array', (['(0.0, 0.0, 1.0, 2.0, 3)'], {}), '((0.0, 0.0, 1.0, 2.0, 3))\n', (26586, 26611), True, 'import numpy as nm\n'), ((26642, 26664), 'numpy.array', 'nm.array', (['(10, 10, 10)'], {}), '((10, 10, 10))\n', (26650, 26664), True, 'import numpy as nm\n'), ((26664, 26689), 'numpy.array', 'nm.array', (['(1.0, 2.0, 3.0)'], {}), '((1.0, 2.0, 3.0))\n', (26672, 26689), True, 'import numpy as nm\n'), ((26876, 26909), 'numpy.array', 'nm.array', (['(0.5, 0.5, 1.0, 2.0, 3)'], {}), '((0.5, 0.5, 1.0, 2.0, 3))\n', (26884, 26909), True, 'import numpy as nm\n'), ((26940, 26962), 'numpy.array', 'nm.array', (['(10, 10, 10)'], {}), '((10, 10, 10))\n', (26948, 26962), True, 'import numpy as nm\n'), ((26962, 26987), 'numpy.array', 'nm.array', (['(1.0, 2.0, 3.0)'], {}), '((1.0, 2.0, 3.0))\n', (26970, 26987), True, 'import numpy as nm\n'), ((1134, 1169), 'numpy.zeros', 'nm.zeros', (['(n_el, 4)'], {'dtype': 'nm.int32'}), '((n_el, 4), dtype=nm.int32)\n', (1142, 1169), True, 'import numpy as nm\n'), ((1377, 1412), 'numpy.zeros', 'nm.zeros', (['(n_el, 8)'], {'dtype': 'nm.int32'}), '((n_el, 8), dtype=nm.int32)\n', (1385, 1412), True, 'import numpy as nm\n'), ((5763, 5796), 'numpy.sqrt', 'nm.sqrt', (['(advol + ras[ii - 1] ** 2)'], {}), '(advol + ras[ii - 1] ** 2)\n', (5770, 5796), True, 'import numpy as nm\n'), ((5815, 5848), 'numpy.sqrt', 'nm.sqrt', (['(bdvol + rbs[ii - 1] ** 2)'], {}), '(bdvol + rbs[ii - 1] ** 2)\n', (5822, 5848), True, 'import numpy as nm\n'), ((14346, 14379), 'numpy.ones', 'nm.ones', (['(nnod0,)'], {'dtype': 'nm.int32'}), '((nnod0,), dtype=nm.int32)\n', (14353, 14379), True, 'import numpy as nm\n'), ((14506, 14520), 'numpy.where', 'nm.where', (['mask'], {}), '(mask)\n', (14514, 14520), True, 'import numpy as nm\n'), ((15154, 15167), 'numpy.max', 'nm.max', (['ndmap'], {}), '(ndmap)\n', (15160, 15167), True, 'import numpy as nm\n'), ((15187, 15219), 'numpy.where', 'nm.where', (['(ndmap_out > max_nd_ref)'], {}), '(ndmap_out > max_nd_ref)\n', (15195, 15219), True, 'import numpy as nm\n'), ((19331, 19376), 'os.path.join', 'os.path.join', (['defdir', '"""quantum"""', '"""sphere.geo"""'], {}), "(defdir, 'quantum', 'sphere.geo')\n", (19343, 19376), False, 'import os\n'), ((22057, 22071), 'numpy.array', 'nm.array', (['dims'], {}), '(dims)\n', (22065, 22071), True, 'import numpy as nm\n'), ((22777, 22793), 'numpy.where', 'nm.where', (['voxels'], {}), '(voxels)\n', (22785, 22793), True, 'import numpy as nm\n'), ((24768, 24795), 'numpy.ascontiguousarray', 'nm.ascontiguousarray', (['elems'], {}), '(elems)\n', (24788, 24795), True, 'import numpy as nm\n'), ((24825, 24856), 'numpy.ones', 'nm.ones', (['(nel,)'], {'dtype': 'nm.int32'}), '((nel,), dtype=nm.int32)\n', (24832, 24856), True, 'import numpy as nm\n'), ((8822, 8831), 'numpy.eye', 'nm.eye', (['(3)'], {}), '(3)\n', (8828, 8831), True, 'import numpy as nm\n'), ((14426, 14441), 'numpy.cumsum', 'nm.cumsum', (['mask'], {}), '(mask)\n', (14435, 14441), True, 'import numpy as nm\n'), ((14584, 14600), 'numpy.arange', 'nm.arange', (['nnod0'], {}), '(nnod0)\n', (14593, 14600), True, 'import numpy as nm\n'), ((23689, 23704), 'numpy.array', 'nm.array', (['ndidx'], {}), '(ndidx)\n', (23697, 23704), True, 'import numpy as nm\n'), ((23891, 23985), 'numpy.array', 'nm.array', (['[nodeid[ix, iy], nodeid[ix + 1, iy], nodeid[ix + 1, iy + 1], nodeid[ix, iy + 1]\n ]'], {}), '([nodeid[ix, iy], nodeid[ix + 1, iy], nodeid[ix + 1, iy + 1],\n nodeid[ix, iy + 1]])\n', (23899, 23985), True, 'import numpy as nm\n'), ((12807, 12833), 'numpy.maximum', 'nm.maximum', (['(b_shape - 2)', '(0)'], {}), '(b_shape - 2, 0)\n', (12817, 12833), True, 'import numpy as nm\n'), ((12841, 12852), 'numpy.prod', 'nm.prod', (['xs'], {}), '(xs)\n', (12848, 12852), True, 'import numpy as nm\n'), ((24104, 24330), 'numpy.array', 'nm.array', (['[nodeid[ix, iy, iz], nodeid[ix + 1, iy, iz], nodeid[ix + 1, iy + 1, iz],\n nodeid[ix, iy + 1, iz], nodeid[ix, iy, iz + 1], nodeid[ix + 1, iy, iz +\n 1], nodeid[ix + 1, iy + 1, iz + 1], nodeid[ix, iy + 1, iz + 1]]'], {}), '([nodeid[ix, iy, iz], nodeid[ix + 1, iy, iz], nodeid[ix + 1, iy + 1,\n iz], nodeid[ix, iy + 1, iz], nodeid[ix, iy, iz + 1], nodeid[ix + 1, iy,\n iz + 1], nodeid[ix + 1, iy + 1, iz + 1], nodeid[ix, iy + 1, iz + 1]])\n', (24112, 24330), True, 'import numpy as nm\n'), ((6259, 6269), 'numpy.cos', 'nm.cos', (['fi'], {}), '(fi)\n', (6265, 6269), True, 'import numpy as nm\n'), ((6275, 6285), 'numpy.sin', 'nm.sin', (['fi'], {}), '(fi)\n', (6281, 6285), True, 'import numpy as nm\n')] |
# 30.05.2007, c
# last revision: 25.02.2008
from __future__ import absolute_import
from sfepy import data_dir
import six
filename_mesh = data_dir + '/meshes/2d/square_unit_tri.mesh'
material_1 = {
'name' : 'coef',
'values' : {
'val' : 1.0,
},
}
material_2 = {
'name' : 'm',
'values' : {
'K' : [[1.0, 0.0], [0.0, 1.0]],
},
}
field_1 = {
'name' : 'a_harmonic_field',
'dtype' : 'real',
'shape' : 'scalar',
'region' : 'Omega',
'approx_order' : 2,
}
variable_1 = {
'name' : 't',
'kind' : 'unknown field',
'field' : 'a_harmonic_field',
'order' : 0,
}
variable_2 = {
'name' : 's',
'kind' : 'test field',
'field' : 'a_harmonic_field',
'dual' : 't',
}
region_1000 = {
'name' : 'Omega',
'select' : 'all',
}
region_1 = {
'name' : 'Left',
'select' : 'vertices in (x < -0.499)',
'kind' : 'facet',
}
region_2 = {
'name' : 'Right',
'select' : 'vertices in (x > 0.499)',
'kind' : 'facet',
}
region_3 = {
'name' : 'Gamma',
'select' : 'vertices of surface',
'kind' : 'facet',
}
ebc_1 = {
'name' : 't_left',
'region' : 'Left',
'dofs' : {'t.0' : 5.0},
}
ebc_2 = {
'name' : 't_right',
'region' : 'Right',
'dofs' : {'t.0' : 0.0},
}
# 'Left' : ('T3', (30,), 'linear_y'),
integral_1 = {
'name' : 'i',
'order' : 2,
}
equations = {
'Temperature' : """dw_laplace.i.Omega( coef.val, s, t ) = 0"""
}
solution = {
't' : '- 5.0 * (x - 0.5)',
}
solver_0 = {
'name' : 'ls',
'kind' : 'ls.scipy_direct',
}
solver_1 = {
'name' : 'newton',
'kind' : 'nls.newton',
'i_max' : 1,
'eps_a' : 1e-10,
}
lin_min, lin_max = 0.0, 2.0
##
# 31.05.2007, c
def linear( bc, ts, coor, which ):
vals = coor[:,which]
min_val, max_val = vals.min(), vals.max()
vals = (vals - min_val) / (max_val - min_val) * (lin_max - lin_min) + lin_min
return vals
##
# 31.05.2007, c
def linear_x( bc, ts, coor ):
return linear( bc, ts, coor, 0 )
def linear_y( bc, ts, coor ):
return linear( bc, ts, coor, 1 )
def linear_z( bc, ts, coor ):
return linear( bc, ts, coor, 2 )
from sfepy.base.testing import TestCommon
##
# 30.05.2007, c
class Test( TestCommon ):
##
# 30.05.2007, c
def from_conf( conf, options ):
from sfepy.applications import solve_pde
problem, state = solve_pde(conf, save_results=False)
test = Test(problem=problem, state=state, conf=conf, options=options)
return test
from_conf = staticmethod( from_conf )
##
# 30.05.2007, c
def test_solution( self ):
sol = self.conf.solution
vec = self.state()
problem = self.problem
variables = problem.get_variables()
ok = True
for var_name, expression in six.iteritems(sol):
coor = variables[var_name].field.get_coor()
ana_sol = self.eval_coor_expression( expression, coor )
num_sol = variables.get_state_part_view( vec, var_name )
ret = self.compare_vectors( ana_sol, num_sol,
label1 = 'analytical %s' % var_name,
label2 = 'numerical %s' % var_name )
if not ret:
self.report( 'variable %s: failed' % var_name )
ok = ok and ret
return ok
##
# c: 30.05.2007, r: 19.02.2008
def test_boundary_fluxes( self ):
import os.path as op
from sfepy.linalg import rotation_matrix2d
from sfepy.discrete.evaluate import BasicEvaluator
from sfepy.discrete import Material
problem = self.problem
angles = [0, 30, 45]
region_names = ['Left', 'Right', 'Gamma']
values = [5.0, -5.0, 0.0]
variables = problem.get_variables()
get_state = variables.get_state_part_view
state = self.state.copy(deep=True)
problem.time_update(ebcs={}, epbcs={})
# problem.save_ebc( 'aux.vtk' )
state.apply_ebc()
ev = BasicEvaluator( problem )
aux = ev.eval_residual(state())
field = variables['t'].field
conf_m = problem.conf.get_item_by_name('materials', 'm')
m = Material.from_conf(conf_m, problem.functions)
name = op.join( self.options.out_dir,
op.split( problem.domain.mesh.name )[1] + '_%02d.mesh' )
orig_coors = problem.get_mesh_coors().copy()
ok = True
for ia, angle in enumerate( angles ):
self.report( '%d: mesh rotation %d degrees' % (ia, angle) )
problem.domain.mesh.transform_coors( rotation_matrix2d( angle ),
ref_coors = orig_coors )
problem.set_mesh_coors(problem.domain.mesh.coors,
update_fields=True)
problem.domain.mesh.write( name % angle, io = 'auto' )
for ii, region_name in enumerate( region_names ):
flux_term = 'd_surface_flux.i.%s( m.K, t )' % region_name
val1 = problem.evaluate(flux_term, t=variables['t'], m=m)
rvec = get_state( aux, 't', True )
reg = problem.domain.regions[region_name]
nods = field.get_dofs_in_region(reg, merge=True)
val2 = rvec[nods].sum() # Assume 1 dof per node.
ok = ok and ((abs( val1 - values[ii] ) < 1e-10) and
(abs( val2 - values[ii] ) < 1e-10))
self.report( ' %d. %s: %e == %e == %e'\
% (ii, region_name, val1, val2, values[ii]) )
# Restore original coordinates.
problem.domain.mesh.transform_coors(rotation_matrix2d(0),
ref_coors=orig_coors)
problem.set_mesh_coors(problem.domain.mesh.coors,
update_fields=True)
return ok
| [
"sfepy.applications.solve_pde",
"sfepy.linalg.rotation_matrix2d",
"sfepy.discrete.Material.from_conf",
"sfepy.discrete.evaluate.BasicEvaluator"
] | [((2386, 2421), 'sfepy.applications.solve_pde', 'solve_pde', (['conf'], {'save_results': '(False)'}), '(conf, save_results=False)\n', (2395, 2421), False, 'from sfepy.applications import solve_pde\n'), ((2813, 2831), 'six.iteritems', 'six.iteritems', (['sol'], {}), '(sol)\n', (2826, 2831), False, 'import six\n'), ((4046, 4069), 'sfepy.discrete.evaluate.BasicEvaluator', 'BasicEvaluator', (['problem'], {}), '(problem)\n', (4060, 4069), False, 'from sfepy.discrete.evaluate import BasicEvaluator\n'), ((4228, 4273), 'sfepy.discrete.Material.from_conf', 'Material.from_conf', (['conf_m', 'problem.functions'], {}), '(conf_m, problem.functions)\n', (4246, 4273), False, 'from sfepy.discrete import Material\n'), ((5729, 5749), 'sfepy.linalg.rotation_matrix2d', 'rotation_matrix2d', (['(0)'], {}), '(0)\n', (5746, 5749), False, 'from sfepy.linalg import rotation_matrix2d\n'), ((4642, 4666), 'sfepy.linalg.rotation_matrix2d', 'rotation_matrix2d', (['angle'], {}), '(angle)\n', (4659, 4666), False, 'from sfepy.linalg import rotation_matrix2d\n'), ((4345, 4379), 'os.path.split', 'op.split', (['problem.domain.mesh.name'], {}), '(problem.domain.mesh.name)\n', (4353, 4379), True, 'import os.path as op\n')] |
import numpy as nm
from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson
from sfepy.discrete.fem.meshio import UserMeshIO
from sfepy.mesh.mesh_generators import gen_block_mesh
from sfepy import data_dir
def mesh_hook(mesh, mode):
if mode == 'read':
mesh = gen_block_mesh([0.0098, 0.0011, 0.1], [5, 3, 17],
[0, 0, 0.05], name='specimen',
verbose=False)
return mesh
elif mode == 'write':
pass
def optimization_hook(pb):
cnf = pb.conf
out = []
yield pb, out
state = out[-1][1].get_parts()
coors = pb.domain.cmesh.coors
displ = state['u'].reshape((coors.shape[0],3))
# elongation
mcoors = coors[cnf.mnodes, 2]
mdispl = displ[cnf.mnodes, 2]
dl = (mdispl[1] - mdispl[0]) / (mcoors[1] - mcoors[0])
if hasattr(cnf, 'opt_data'):
# compute slope of the force-elongation curve
cnf.opt_data['k'] = cnf.F / dl
yield None
def get_mat(coors, mode, pb):
if mode == 'qp':
# get material data
if hasattr(pb.conf, 'opt_data'):
# from homogenization
D = pb.conf.opt_data['D_homog']
else:
# given values
D = stiffness_from_youngpoisson(3, 150.0e9, 0.3)
nqp = coors.shape[0]
return {'D': nm.tile(D, (nqp, 1, 1))}
def define(is_opt=False):
filename_mesh = UserMeshIO(mesh_hook)
mnodes = (107, 113) # nodes for elongation eval.
regions = {
'Omega': 'all',
'Bottom': ('vertices in (z < 0.001)', 'facet'),
'Top': ('vertices in (z > 0.099)', 'facet'),
}
functions = {
'get_mat': (lambda ts, coors, mode=None, problem=None, **kwargs:
get_mat(coors, mode, problem),),
}
S = 1.083500e-05 # specimen cross-section
F = 5.0e3 # force
materials = {
'solid': 'get_mat',
'load': ({'val': F / S},),
}
fields = {
'displacement': ('real', 'vector', 'Omega', 1),
}
variables = {
'u': ('unknown field', 'displacement', 0),
'v': ('test field', 'displacement', 'u'),
}
ebcs = {
'FixedBottom': ('Bottom', {'u.all': 0.0}),
'FixedTop': ('Top', {'u.0': 0.0, 'u.1': 0.0}),
}
equations = {
'balance_of_forces' :
"""dw_lin_elastic.5.Omega(solid.D, v, u)
= dw_surface_ltr.5.Top(load.val, v)""",
}
solvers = {
'ls': ('ls.scipy_direct', {}),
'newton': ('nls.newton', {'eps_a': 1e-6, 'eps_r': 1.e-6,
'check': 0, 'problem': 'nonlinear'}),
}
options = {
'parametric_hook': 'optimization_hook',
'output_dir' : 'output',
}
return locals()
| [
"sfepy.discrete.fem.meshio.UserMeshIO",
"sfepy.mesh.mesh_generators.gen_block_mesh",
"sfepy.mechanics.matcoefs.stiffness_from_youngpoisson"
] | [((1406, 1427), 'sfepy.discrete.fem.meshio.UserMeshIO', 'UserMeshIO', (['mesh_hook'], {}), '(mesh_hook)\n', (1416, 1427), False, 'from sfepy.discrete.fem.meshio import UserMeshIO\n'), ((281, 381), 'sfepy.mesh.mesh_generators.gen_block_mesh', 'gen_block_mesh', (['[0.0098, 0.0011, 0.1]', '[5, 3, 17]', '[0, 0, 0.05]'], {'name': '"""specimen"""', 'verbose': '(False)'}), "([0.0098, 0.0011, 0.1], [5, 3, 17], [0, 0, 0.05], name=\n 'specimen', verbose=False)\n", (295, 381), False, 'from sfepy.mesh.mesh_generators import gen_block_mesh\n'), ((1238, 1289), 'sfepy.mechanics.matcoefs.stiffness_from_youngpoisson', 'stiffness_from_youngpoisson', (['(3)', '(150000000000.0)', '(0.3)'], {}), '(3, 150000000000.0, 0.3)\n', (1265, 1289), False, 'from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson\n'), ((1334, 1357), 'numpy.tile', 'nm.tile', (['D', '(nqp, 1, 1)'], {}), '(D, (nqp, 1, 1))\n', (1341, 1357), True, 'import numpy as nm\n')] |
# -*- coding: utf-8 -*-
"""
Fields for Discontinous Galerkin method
"""
import numpy as nm
import six
from numpy.lib.stride_tricks import as_strided
from six.moves import range
from sfepy.base.base import (output, assert_, Struct)
from sfepy.discrete import Integral, PolySpace
from sfepy.discrete.common.fields import parse_shape
from sfepy.discrete.fem.fields_base import FEField
from sfepy.discrete.fem.mappings import VolumeMapping
def get_unraveler(n_el_nod, n_cell):
"""Returns function for unraveling i.e. unpacking dof data from
serialized array from shape (n_el_nod*n_cell, 1) to (n_cell, n_el_nod, 1).
The unraveler returns non-writeable view into the input array.
Parameters
----------
n_el_nod : int
expected dimensions of dofs array
n_cell : int
Returns
-------
unravel : callable
"""
def unravel(u):
"""Returns non-writeable view into the input array reshaped to
(n*m, 1) to (m, n, 1) .
Parameters
----------
u : array_like
solution in shape (n*m, 1)
Returns
-------
u : ndarray
unraveledsolution in shape (m, n, 1)
"""
ustride1 = u.strides[0]
ur = as_strided(u,
shape=(n_cell, n_el_nod, 1),
strides=(n_el_nod * ustride1, ustride1, ustride1),
writeable=False)
return ur
return unravel
def get_raveler(n_el_nod, n_cell):
"""Returns function for raveling i.e. packing dof data from
two dimensional array of shape (n_cell, n_el_nod, 1) to (n_el_nod*n_cell, 1)
The raveler returns view into the input array.
Parameters
----------
n_el_nod :
param n_el_nod, n_cell: expected dimensions of dofs array
n_cell : int
Returns
-------
ravel : callable
"""
def ravel(u):
"""Returns view into the input array reshaped from (m, n, 1) to (n*m, 1)
to (m, n, 1) .
Parameters
----------
u : array_like
Returns
-------
u : ndarray
"""
# ustride1 = u.strides[0]
# ur = as_strided(u, shape=(n_el_nod*n_cell, 1),
# strides=(n_cell*ustride1, ustride1))
ur = nm.ravel(u)[:, None]
# possibly use according to
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html
# ur = u.reshape(-1)
return ur
return ravel
# mapping between geometry element types
# and their facets types
# TODO move to sfepy/discrete/fem/geometry_element.py?
cell_facet_gel_name = {
"1_2": "0_1",
"2_3": "1_2",
"2_4": "1_2",
"3_4": "2_3",
"3_8": "2_4"
}
def get_gel(region):
"""
Parameters
----------
region : sfepy.discrete.common.region.Region
Returns
-------
gel :
base geometry element of the region
"""
cmesh = region.domain.cmesh
for key, gel in six.iteritems(region.domain.geom_els):
ct = cmesh.cell_types
if (ct[region.cells] == cmesh.key_to_index[gel.name]).all():
return gel
else:
raise ValueError('Region {} contains multiple'
' reference geometries!'.format(region))
class DGField(FEField):
"""Class for usage with DG terms, provides functionality for Discontinous
Galerkin method like neighbour look up, projection to discontinuous basis
and correct DOF treatment.
"""
family_name = 'volume_DG_legendre_discontinuous'
is_surface = False
def __init__(self, name, dtype, shape, region, space="H1",
poly_space_base="legendre", approx_order=1, integral=None):
"""
Creates DGField, with Legendre polyspace and default integral
corresponding to 2 * approx_order.
Parameters
----------
name : string
dtype : type
shape : string
'vector', 'scalar' or something else
region : sfepy.discrete.common.region.Region
space : string
default "H1"
poly_space_base : PolySpace
optionally force polyspace
approx_order : 0 for FVM, default 1
integral : Integral
if None integral of order 2*approx_order is created
"""
shape = parse_shape(shape, region.domain.shape.dim)
Struct.__init__(self, name=name, dtype=dtype, shape=shape,
region=region)
if isinstance(approx_order, tuple):
self.approx_order = approx_order[0]
else:
self.approx_order = approx_order
# geometry
self.domain = region.domain
self.region = region
self.dim = region.tdim
self._setup_geometry()
self._setup_connectivity()
# TODO treat domains embedded into higher dimensional spaces?
self.n_el_facets = self.dim + 1 if self.gel.is_simplex else 2**self.dim
# approximation space
self.space = space
self.poly_space_base = poly_space_base
self.force_bubble = False
self._create_interpolant()
# DOFs
self._setup_shape()
self._setup_all_dofs()
self.ravel_sol = get_raveler(self.n_el_nod, self.n_cell)
self.unravel_sol = get_unraveler(self.n_el_nod, self.n_cell)
# integral
self.clear_qp_base()
self.clear_facet_qp_base()
if integral is None:
self.integral = Integral("dg_fi", order = 2 * self.approx_order)
else:
self.integral = integral
self.ori = None
self.basis_transform = None
# mapping
self.mappings = {}
self.mapping = self.create_mapping(self.region, self.integral, "volume",
return_mapping=True)[1]
self.mappings0 = {}
# neighbour facet mapping and data caches
# TODO use lru cache or different method?
self.clear_facet_neighbour_idx_cache()
self.clear_normals_cache()
self.clear_facet_vols_cache()
self.boundary_facet_local_idx = {}
def _create_interpolant(self):
name = self.gel.name + '_DG_legendre'
ps = PolySpace.any_from_args(name, self.gel, self.approx_order,
base=self.poly_space_base,
force_bubble=False)
self.poly_space = ps
# 'legendre_simplex' is created for '1_2'.
if self.gel.name in ["2_4", "3_8"]:
self.extended = True
else:
self.extended = False
def _setup_all_dofs(self):
"""Sets up all the differet kinds of DOFs, for DG only bubble DOFs"""
self.n_el_nod = self.poly_space.n_nod
self.n_vertex_dof = 0 # in DG we will propably never need vertex DOFs
self.n_edge_dof = 0 # use facets DOFS for AFS methods
self.n_face_dof = 0 # use facet DOF for AFS methods
(self.n_bubble_dof,
self.bubble_remap,
self.bubble_dofs) = self._setup_bubble_dofs()
self.n_nod = self.n_vertex_dof + self.n_edge_dof \
+ self.n_face_dof + self.n_bubble_dof
def _setup_bubble_dofs(self):
"""Creates DOF information for so called element, cell or bubble DOFs
- the only DOFs used in DG
n_dof = n_cells * n_el_nod
remap optional remapping between cells
dofs is mapping between dofs and cells
Returns
-------
n_dof : int
remap : ndarray
dofs : ndarray
"""
self.n_cell = self.region.get_n_cells(self.is_surface)
n_dof = self.n_cell * self.n_el_nod
dofs = nm.arange(n_dof, dtype=nm.int32)\
.reshape(self.n_cell, self.n_el_nod)
remap = nm.arange(self.n_cell)
self.econn = dofs
self.dofs2cells = nm.repeat(nm.arange(self.n_cell), self.n_el_nod)
return n_dof, remap, dofs
def _setup_shape(self):
"""What is shape used for and what it really means.
Does it represent shape of the problem?
"""
self.n_components = nm.prod(self.shape)
self.val_shape = self.shape
def _setup_geometry(self):
"""Setup the field region geometry."""
# get_gel extracts the highest dimension geometry from self.region
self.gel = get_gel(self.region)
def _setup_connectivity(self):
"""Forces self.domain.mesh to build necessary conductivities
so they are available in self.get_nbrhd_dofs
"""
self.region.domain.mesh.cmesh.setup_connectivity(self.dim, self.dim)
self.region.domain.mesh.cmesh.setup_connectivity(self.dim - 1, self.dim)
self.region.domain.mesh.cmesh.setup_connectivity(self.dim, self.dim - 1)
def get_coor(self, nods=None):
"""Returns coors for matching nodes
# TODO revise DG_EPBC and EPBC matching?
Parameters
----------
nods :
if None use all nodes (Default value = None)
Returns
-------
coors : ndarray
coors on surface
"""
if nods is None:
nods = self.bubble_dofs
cells = self.dofs2cells[nods]
coors = self.domain.mesh.cmesh.get_centroids(self.dim)[cells]
eps = min(self.domain.cmesh.get_volumes(self.dim)) / (self.n_el_nod + 2)
if self.dim == 1:
extended_coors = nm.zeros(nm.shape(coors)[:-1] + (2,))
extended_coors[:, 0] = coors[:, 0]
coors = extended_coors
# shift centroid coors to lie within cells but be different for each dof
# use coors of facet QPs?
coors += eps * nm.repeat(nm.arange(self.n_el_nod),
len(nm.unique(cells)))[:, None]
return coors
def clear_facet_qp_base(self):
"""Clears facet_qp_base cache"""
self.facet_bf = {}
self.facet_qp = None
self.facet_whs = None
def _transform_qps_to_facets(self, qps, geo_name):
"""Transforms points given in qps to all facets of the reference element
with geometry geo_name.
Parameters
----------
qps :
qps corresponding to facet dimension to be transformed
geo_name :
element type
Returns
-------
tqps : ndarray
tqps is of shape shape(qps) + (n_el_facets, geo dim)
"""
if geo_name == "1_2":
tqps = nm.zeros(nm.shape(qps) + (2, 1,))
tqps[..., 0, 0] = 0.
tqps[..., 1, 0] = 1.
elif geo_name == "2_3":
tqps = nm.zeros(nm.shape(qps) + (3, 2,))
# 0.
tqps[..., 0, 0] = qps # x = 0 + t
tqps[..., 0, 1] = 0. # y = 0
# 1.
tqps[..., 1, 0] = 1 - qps # x = 1 - t
tqps[..., 1, 1] = qps # y = t
# 2.
tqps[..., 2, 0] = 0 # x = 0
tqps[..., 2, 1] = 1 - qps # y = 1 - t
elif geo_name == "2_4":
tqps = nm.zeros(nm.shape(qps) + (4, 2,))
# 0.
tqps[..., 0, 0] = qps # x = t
tqps[..., 0, 1] = 0. # y = 0
# 1.
tqps[..., 1, 0] = 1 # x = 1
tqps[..., 1, 1] = qps # y = t
# 2.
tqps[..., 2, 0] = 1 - qps # x = 1 -t
tqps[..., 2, 1] = 1 # y = 1
# 3.
tqps[..., 3, 0] = 0 # x = 0
tqps[..., 3, 1] = 1 - qps # y = 1 - t
elif geo_name == "3_4":
# tqps = nm.zeros(nm.shape(qps) + (4, 3,))
raise NotImplementedError("Geometry {} not supported, yet"
.format(geo_name))
elif geo_name == "3_8":
# tqps = nm.zeros(nm.shape(qps) + (8, 3,))
raise NotImplementedError("Geometry {} not supported, yet"
.format(geo_name))
else:
raise NotImplementedError("Geometry {} not supported, yet"
.format(geo_name))
return tqps
def get_facet_qp(self):
"""Returns quadrature points on all facets of the reference element in
array of shape (n_qp, 1 , n_el_facets, dim)
Returns
-------
qps : ndarray
quadrature points
weights : ndarray
Still needs to be transformed to actual facets!
"""
if self.dim == 1:
facet_qps = self._transform_qps_to_facets(nm.zeros((1, 1)), "1_2")
weights = nm.ones((1, 1, 1))
else:
qps, weights = self.integral.get_qp(cell_facet_gel_name[self.gel.name])
weights = weights[None, :, None]
facet_qps = self._transform_qps_to_facets(qps, self.gel.name)
return facet_qps, weights
def get_facet_base(self, derivative=False, base_only=False):
"""
Returns values of base in facets quadrature points, data shape is a bit
crazy right now:
(number of qps, 1, n_el_facets, 1, n_el_nod)
end for derivatine:
(1, number of qps, (dim,) * derivative, n_el_facets, 1, n_el_nod)
Parameters
----------
derivative: truthy or integer
base_only: do not return weights
Returns
-------
facet_bf : ndarray
values of basis functions in facet qps
weights : ndarray, optionally
weights of qps
"""
if derivative:
diff = int(derivative)
else:
diff = 0
if diff in self.facet_bf:
facet_bf = self.facet_bf[diff]
whs = self.facet_whs
else:
qps, whs = self.get_facet_qp()
ps = self.poly_space
self.facet_qp = qps
self.facet_whs = whs
if derivative:
facet_bf = nm.zeros((1,) + nm.shape(qps)[:-1] +
(self.dim,) * diff + (self.n_el_nod,))
else:
facet_bf = nm.zeros(nm.shape(qps)[:-1] + (1, self.n_el_nod,))
for i in range(self.n_el_facets):
facet_bf[..., i, :, :] = \
ps.eval_base(qps[..., i, :], diff=diff,
transform=self.basis_transform)
self.facet_bf[diff] = facet_bf
if base_only:
return facet_bf
else:
return facet_bf, whs
def clear_facet_neighbour_idx_cache(self, region=None):
"""
If region is None clear all!
Parameters
----------
region : sfepy.discrete.common.region.Region
If None clear all.
"""
if region is None:
self.facet_neighbour_index = {}
else:
self.facet_neighbour_index.pop(region.name)
def get_facet_neighbor_idx(self, region=None, eq_map=None):
"""
Returns index of cell neighbours sharing facet, along with local index
of the facet within neighbour, also treats periodic boundary conditions
i.e. plugs correct neighbours for cell on periodic boundary.
Where there are no neighbours specified puts -1 instead of neighbour
and facet id
Cashes neighbour index in self.facet_neighbours
Parameters
----------
region : sfepy.discrete.common.region.Region
Main region, must contain cells.
eq_map :
eq_map from state variable containing information on
EPBC and DG EPBC. (Default value = None)
Returns
-------
facet_neighbours : ndarray
Shape is
(n_cell, n_el_facet, 2),
first value is index of the neighbouring cell,
the second is index of the facet in said nb. cell.
"""
if region is None or eq_map is None:
# HOTFIX enabling limiter to obtain connectivity data without
# knowing eq_map or region
if self.region.name in self.facet_neighbour_index:
return self.facet_neighbour_index[self.region.name]
else:
raise ValueError("No facet neighbour mapping for main " +
"region {}".format(self.region.name) +
" cached yet, call with region and " +
"eq_map first.")
if region.name in self.facet_neighbour_index:
return self.facet_neighbour_index[region.name]
dim, n_cell, n_el_facets = self.get_region_info(region)
cmesh = region.domain.mesh.cmesh
cells = region.cells
facet_neighbours = nm.zeros((n_cell, n_el_facets, 2), dtype=nm.int32)
c2fi, c2fo = cmesh.get_incident(dim - 1, cells, dim, ret_offsets=True)
for ic, o1 in enumerate(c2fo[:-1]): # loop over cells
o2 = c2fo[ic + 1]
# get neighbours per facet of the cell
c2ci, c2co = cmesh.get_incident(dim, c2fi[o1:o2], dim - 1,
ret_offsets=True)
ii = cmesh.get_local_ids(c2fi[o1:o2], dim - 1, c2ci, c2co, dim)
fis = nm.c_[c2ci, ii]
nbrs = []
for ifa, of1 in enumerate(c2co[:-1]): # loop over facets
of2 = c2co[ifa + 1]
if of2 == (of1 + 1): # facet has only one cell
# Surface facet.
nbrs.append([-1, -1]) # c2ci[of1]) # append no neighbours
else:
if c2ci[of1] == cells[ic]: # do not append the cell itself
nbrs.append(fis[of2 - 1])
else:
nbrs.append(fis[of1])
facet_neighbours[ic, :, :] = nbrs
facet_neighbours = \
self._set_fem_periodic_facet_neighbours(facet_neighbours, eq_map)
facet_neighbours = \
self._set_dg_periodic_facet_neighbours(facet_neighbours, eq_map)
# cache results
self.facet_neighbour_index[region.name] = facet_neighbours
return facet_neighbours
def _set_dg_periodic_facet_neighbours(self, facet_neighbours, eq_map):
"""
Parameters
----------
facet_neighbours : array_like
Shape is
(n_cell, n_el_facet, 2),
first value is index of the neighbouring cell
the second is index of the facet in said nb. cell.
eq_map :
must contain dg_ep_bc a List with pairs of slave and master boundary
cell boundary facet mapping
Returns
-------
facet_neighbours : ndarray
Updated incidence array.
"""
# if eq_map.
# treat DG EPBC - these are definitely preferred
if eq_map.n_dg_epbc > 0 and self.gel.name not in ["1_2", "2_4", "3_6"]:
raise ValueError(
"Periodic boundary conditions not supported " +
"for geometry {} elements.".format(self.gel.name))
dg_epbc = eq_map.dg_epbc
for master_bc2bfi, slave_bc2bfi in dg_epbc:
# set neighbours of periodic cells to one another
facet_neighbours[master_bc2bfi[:, 0], master_bc2bfi[:, 1], 0] = \
slave_bc2bfi[:, 0]
facet_neighbours[slave_bc2bfi[:, 0], slave_bc2bfi[:, 1], 0] = \
master_bc2bfi[:, 0]
# set neighbours facets
facet_neighbours[slave_bc2bfi[:, 0], slave_bc2bfi[:, 1], 1] = \
master_bc2bfi[:, 1]
facet_neighbours[master_bc2bfi[:, 0], master_bc2bfi[:, 1], 1] =\
slave_bc2bfi[:, 1]
return facet_neighbours
def _set_fem_periodic_facet_neighbours(self, facet_neighbours, eq_map):
"""Maybe remove after DG EPBC revision in self.get_coor
Parameters
----------
facet_neighbours : array_like
Shape is (n_cell, n_el_facet, 2), first value is index of the
neighbouring cell the second is index of the facet in said nb. cell.
eq_map :
eq_map from state variable containing information on
EPBC and DG EPBC.
Returns
-------
facet_neighbours : ndarray
Updated incidence array.
"""
# treat classical FEM EPBCs - we need to correct neighbours
if eq_map.n_epbc > 0:
# set neighbours of periodic cells to one another
mcells = nm.unique(self.dofs2cells[eq_map.master])
scells = nm.unique(self.dofs2cells[eq_map.slave])
mcells_facets = nm.array(
nm.where(facet_neighbours[mcells] == -1))[1, 0] # facets mcells
scells_facets = nm.array(
nm.where(facet_neighbours[scells] == -1))[1, 0] # facets scells
# [1, 0] above, first we need second axis to get axis on which
# facet indices are stored, second we drop axis with neighbour
# local facet index,
#
# for multiple s/mcells this will have to be
# something like 1 + 2*nm.arange(len(mcells)) - to skip double
# entries for -1 tags in neighbours and neighbour local facet idx
# set neighbours of mcells to scells
facet_neighbours[mcells, mcells_facets, 0] = scells
# set neighbour facets to facets of scell missing neighbour
facet_neighbours[
mcells, mcells_facets, 1] = scells_facets
# we do not need to distinguish EBC and EPBC cells, EBC overwrite
# EPBC, we only need to fix shapes
# set neighbours of scells to mcells
facet_neighbours[scells, scells_facets, 0] = mcells
# set neighbour facets to facets of mcell missing neighbour0
facet_neighbours[
scells, scells_facets, 1] = mcells_facets
return facet_neighbours
@staticmethod
def get_region_info(region):
"""
Extracts information about region needed in various methods of DGField
Parameters
----------
region : sfepy.discrete.common.region.Region
Returns
-------
dim, n_cell, n_el_facets
"""
if not region.has_cells():
raise ValueError("Region {} has no cells".format(region.name))
n_cell = region.get_n_cells()
dim = region.tdim
gel = get_gel(region)
n_el_facets = dim + 1 if gel.is_simplex else 2 ** dim
return dim, n_cell, n_el_facets
def get_both_facet_state_vals(self, state, region,
derivative=None, reduce_nod=True):
"""Computes values of the variable represented by dofs in
quadrature points located at facets, returns both values -
inner and outer, along with weights.
Parameters
----------
state : state variable containing BC info
region : sfepy.discrete.common.region.Region
derivative : compute derivative if truthy,
compute n-th derivative if a number (Default value = None)
reduce_nod : if False DOES NOT sum nodes into values at QPs
(Default value = True)
Returns
-------
inner_facet_values (n_cell, n_el_facets, n_qp),
outer facet values (n_cell, n_el_facets, n_qp),
weights,
if derivative is True:
inner_facet_values (n_cell, n_el_facets, dim, n_qp),
outer_facet values (n_cell, n_el_facets, dim, n_qp)
"""
if derivative:
diff = int(derivative)
else:
diff = 0
unreduce_nod = int(not reduce_nod)
inner_base_vals, outer_base_vals, whs = \
self.get_both_facet_base_vals(state, region, derivative=derivative)
dofs = self.unravel_sol(state.data[0])
n_qp = whs.shape[-1]
outputs_shape = (self.n_cell, self.n_el_facets) + \
(self.n_el_nod,) * unreduce_nod + \
(self.dim,) * diff + \
(n_qp,)
inner_facet_vals = nm.zeros(outputs_shape)
if unreduce_nod:
inner_facet_vals[:] = nm.einsum('id...,idf...->ifd...',
dofs, inner_base_vals)
else:
inner_facet_vals[:] = nm.einsum('id...,id...->i...',
dofs, inner_base_vals)
per_facet_neighbours = self.get_facet_neighbor_idx(region, state.eq_map)
outer_facet_vals = nm.zeros(outputs_shape)
for facet_n in range(self.n_el_facets):
if unreduce_nod:
outer_facet_vals[:, facet_n, :] = \
nm.einsum('id...,id...->id...',
dofs[per_facet_neighbours[:, facet_n, 0]],
outer_base_vals[:, :, facet_n])
else:
outer_facet_vals[:, facet_n, :] = \
nm.einsum('id...,id...->i...',
dofs[per_facet_neighbours[:, facet_n, 0]],
outer_base_vals[:, :, facet_n])
boundary_cells = nm.array(nm.where(per_facet_neighbours[:, :, 0] < 0)).T
outer_facet_vals[boundary_cells[:, 0], boundary_cells[:, 1]] = 0.0
# TODO detect and print boundary cells without defined BCs?
for ebc, ebc_vals in zip(state.eq_map.dg_ebc.get(diff, []),
state.eq_map.dg_ebc_val.get(diff, [])):
if unreduce_nod:
raise NotImplementedError(
"Unreduced DOFs are not available for boundary " +
"outerfacets")
outer_facet_vals[ebc[:, 0], ebc[:, 1], :] = \
nm.einsum("id,id...->id...",
ebc_vals, inner_base_vals[0, :, ebc[:, 1]])
else:
# fix flipping qp order to accomodate for
# opposite facet orientation of neighbours
outer_facet_vals[ebc[:, 0], ebc[:, 1], :] = ebc_vals[:, ::-1]
# flip outer_facet_vals moved to get_both_facet_base_vals
return inner_facet_vals, outer_facet_vals, whs
def get_both_facet_base_vals(self, state, region, derivative=None):
"""Returns values of the basis function in quadrature points on facets
broadcasted to all cells inner to the element as well as outer ones
along with weights for the qps broadcasted and transformed to elements.
Contains quick fix to flip facet QPs for right integration order.
Parameters
----------
state : used to get EPBC info
region : sfepy.discrete.common.region.Region for connectivity
derivative : if u need derivative
(Default value = None)
Returns
-------
outer_facet_base_vals:
inner_facet_base_vals:
shape (n_cell, n_el_nod, n_el_facet, n_qp) or
(n_cell, n_el_nod, n_el_facet, dim, n_qp)
when derivative is True or 1
whs: shape (n_cell, n_el_facet, n_qp)
"""
if derivative:
diff = int(derivative)
else:
diff = 0
facet_bf, whs = self.get_facet_base(derivative=derivative)
n_qp = nm.shape(whs)[1]
facet_vols = self.get_facet_vols(region)
whs = facet_vols * whs[None, :, :, 0]
base_shape = (self.n_cell, self.n_el_nod, self.n_el_facets) + \
(self.dim,) * diff + \
(n_qp,)
inner_facet_base_vals = nm.zeros(base_shape)
outer_facet_base_vals = nm.zeros(base_shape)
if derivative:
inner_facet_base_vals[:] = facet_bf[0, :, 0, :, :, :]\
.swapaxes(-2, -3).T
else:
inner_facet_base_vals[:] = facet_bf[:, 0, :, 0, :].T
per_facet_neighbours = self.get_facet_neighbor_idx(region, state.eq_map)
# numpy prepends shape resulting from multiple
# indexing before remaining shape
if derivative:
outer_facet_base_vals[:] = \
inner_facet_base_vals[0, :, per_facet_neighbours[:, :, 1]]\
.swapaxes(-3, -4)
else:
outer_facet_base_vals[:] = \
inner_facet_base_vals[0, :, per_facet_neighbours[:, :, 1]]\
.swapaxes(-2, -3)
# fix to flip facet QPs for right integration order
return inner_facet_base_vals, outer_facet_base_vals[..., ::-1], whs
def clear_normals_cache(self, region=None):
"""Clears normals cache for given region or all regions.
Parameters
----------
region : sfepy.discrete.common.region.Region
region to clear cache or None to clear all
"""
if region is None:
self.normals_cache = {}
else:
if isinstance(region, str):
self.normals_cache.pop(region)
else:
self.normals_cache.pop(region.name)
def get_cell_normals_per_facet(self, region):
"""Caches results, use clear_normals_cache to clear the cache.
Parameters
----------
region: sfepy.discrete.common.region.Region
Main region, must contain cells.
Returns
-------
normals: ndarray
normals of facets in array of shape (n_cell, n_el_facets, dim)
"""
if region.name in self.normals_cache:
return self.normals_cache[region.name]
dim, n_cell, n_el_facets = self.get_region_info(region)
cmesh = region.domain.mesh.cmesh
normals = cmesh.get_facet_normals()
normals_out = nm.zeros((n_cell, n_el_facets, dim))
c2f = cmesh.get_conn(dim, dim - 1)
for ic, o1 in enumerate(c2f.offsets[:-1]):
o2 = c2f.offsets[ic + 1]
for ifal, ifa in enumerate(c2f.indices[o1:o2]):
normals_out[ic, ifal] = normals[o1 + ifal]
self.normals_cache[region.name] = normals_out
return normals_out
def clear_facet_vols_cache(self, region=None):
"""Clears facet volume cache for given region or all regions.
Parameters
----------
region : sfepy.discrete.common.region.Region
region to clear cache or None to clear all
"""
if region is None:
self.facet_vols_cache = {}
else:
if isinstance(region, str):
self.facet_vols_cache.pop(region)
else:
self.facet_vols_cache.pop(region.name)
def get_facet_vols(self, region):
"""Caches results, use clear_facet_vols_cache to clear the cache
Parameters
----------
region : sfepy.discrete.common.region.Region
Returns
-------
vols_out: ndarray
volumes of the facets by cells shape (n_cell, n_el_facets, 1)
"""
if region.name in self.facet_vols_cache:
return self.facet_vols_cache[region.name]
dim, n_cell, n_el_facets = self.get_region_info(region)
cmesh = region.domain.mesh.cmesh
if dim == 1:
vols = nm.ones((cmesh.num[0], 1))
else:
vols = cmesh.get_volumes(dim - 1)[:, None]
vols_out = nm.zeros((n_cell, n_el_facets, 1))
c2f = cmesh.get_conn(dim, dim - 1)
for ic, o1 in enumerate(c2f.offsets[:-1]):
o2 = c2f.offsets[ic + 1]
for ifal, ifa in enumerate(c2f.indices[o1:o2]):
vols_out[ic, ifal] = vols[ifa]
self.facet_vols_cache[region.name] = vols_out
return vols_out
def get_data_shape(self, integral, integration='volume', region_name=None):
"""Returns data shape
(n_nod, n_qp, self.gel.dim, self.n_el_nod)
Parameters
----------
integral : integral used
integration :
'volume' is only supported value (Default value = 'volume')
region_name : not used
(Default value = None)
Returns
-------
data_shape : tuple
"""
if integration in ('volume',):
# from FEField.get_data_shape()
_, weights = integral.get_qp(self.gel.name)
n_qp = weights.shape[0]
data_shape = (self.n_cell, n_qp, self.gel.dim, self.n_el_nod)
# econn.shape[1] == n_el_nod i.e. number nod in element
else:
raise NotImplementedError('unsupported integration! (%s)'
% integration)
return data_shape
def get_econn(self, conn_type, region, is_trace=False, integration=None):
"""Getter for econn
Parameters
----------
conn_type : string or Struct
'volume' is only supported
region : sfepy.discrete.common.region.Region
is_trace : ignored
(Default value = False)
integration : ignored
(Default value = None)
Returns
-------
econn : ndarray
connectivity information
"""
ct = conn_type.type if isinstance(conn_type, Struct) else conn_type
if ct == 'volume':
if region.name == self.region.name:
conn = self.econn
else:
raise ValueError("Bad region for the field")
else:
raise ValueError('unknown connectivity type! (%s)' % ct)
return conn
def setup_extra_data(self, geometry, info, is_trace):
"""This is called in create_adof_conns(conn_info, var_indx=None,
active_only=True, verbose=True)
for each variable but has no effect.
Parameters
----------
geometry :
ignored
info :
set to self.info
is_trace :
set to self.trace
"""
# placeholder, what is this used for?
# dct = info.dc_type.type
self.info = info
self.is_trace = is_trace
def get_dofs_in_region(self, region, merge=True):
"""Return indices of DOFs that belong to the given region.
Not Used in BC treatment
Parameters
----------
region : sfepy.discrete.common.region.Region
merge : bool
merge dof tuple into one numpy array, default True
Returns
-------
dofs : ndarray
"""
dofs = []
if region.has_cells(): # main region or its part
els = nm.ravel(self.bubble_remap[region.cells])
eldofs = self.bubble_dofs[els[els >= 0]]
dofs.append(eldofs)
else:
# return indices of cells adjacent to boundary facets
dim = self.dim
cmesh = region.domain.mesh.cmesh
bc_cells = cmesh.get_incident(dim, region.facets, dim - 1)
bc_dofs = self.bubble_dofs[bc_cells]
dofs.append(bc_dofs)
if merge:
dofs = nm.concatenate(dofs)
return dofs
def get_bc_facet_idx(self, region):
"""Caches results in self.boundary_facet_local_idx
Parameters
----------
region : sfepy.discrete.common.region.Region
surface region defining BCs
Returns
-------
bc2bfi : ndarray
index of cells on boundary along with corresponding facets
"""
if region.name in self.boundary_facet_local_idx:
return self.boundary_facet_local_idx[region.name]
bc2bfi = region.get_facet_indices()
self.boundary_facet_local_idx[region.name] = bc2bfi
return bc2bfi
def create_mapping(self, region, integral, integration,
return_mapping=True):
"""Creates and returns mapping
Parameters
----------
region : sfepy.discrete.common.region.Region
integral : Integral
integration : str
'volume' is only accepted option
return_mapping : default True
(Default value = True)
Returns
-------
mapping : VolumeMapping
"""
domain = self.domain
coors = domain.get_mesh_coors(actual=True)
dconn = domain.get_conn()
# from FEField
if integration == 'volume':
qp = self.get_qp('v', integral)
# qp = self.integral.get_qp(self.gel.name)
iels = region.get_cells()
geo_ps = self.gel.poly_space
ps = self.poly_space
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(dconn, iels.astype(nm.int32), axis=0)
mapping = VolumeMapping(coors, conn, poly_space=geo_ps)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori,
transform=self.basis_transform)
out = vg
else:
raise ValueError('unsupported integration geometry type: %s'
% integration)
if out is not None:
# Store the integral used.
out.integral = integral
out.qp = qp
out.ps = ps
# Update base.
out.bf[:] = bf
if return_mapping:
out = (out, mapping)
return out
def set_dofs(self, fun=0.0, region=None, dpn=None, warn=None):
"""Compute projection of fun into the basis, alternatively set DOFs
directly to provided value or values either in main volume region
or in boundary region.
Parameters
----------
fun : callable, scalar or array corresponding to dofs
(Default value = 0.0)
region : sfepy.discrete.common.region.Region
region to set DOFs on (Default value = None)
dpn : number of dofs per element
(Default value = None)
warn :
(Default value = None)
Returns
-------
nods : ndarray
vals : ndarray
"""
if region is None:
region = self.region
return self.set_cell_dofs(fun, region, dpn, warn)
elif region.has_cells():
return self.set_cell_dofs(fun, region, dpn, warn)
elif region.kind_tdim == self.dim - 1:
nods, vals = self.set_facet_dofs(fun, region, dpn, warn)
return nods, vals
def set_cell_dofs(self, fun=0.0, region=None, dpn=None, warn=None):
"""
Compute projection of fun onto the basis, in main region, alternatively
set DOFs directly to provided value or values
Parameters
----------
fun : callable, scallar or array corresponding to dofs
(Default value = 0.0)
region : sfepy.discrete.common.region.Region
region to set DOFs on (Default value = None)
dpn : number of dofs per element
(Default value = None)
warn : not used
(Default value = None)
Returns
-------
nods : ndarray
vals : ndarray
"""
aux = self.get_dofs_in_region(region)
nods = nm.unique(nm.hstack(aux))
if nm.isscalar(fun):
vals = nm.zeros(aux.shape)
vals[:, 0] = fun
vals = nm.hstack(vals)
elif isinstance(fun, nm.ndarray):
# useful for testing, allows to pass complete array of dofs as IC
if nm.shape(fun) == nm.shape(nods):
vals = fun
elif callable(fun):
qp, weights = self.integral.get_qp(self.gel.name)
coors = self.mapping.get_physical_qps(qp)
base_vals_qp = self.poly_space.eval_base(qp)[:, 0, :]
# this drops redundant axis that is returned by eval_base due to
# consistency with derivatives
# left hand, so far only orthogonal basis
# for legendre base this can be calculated exactly
# in 1D it is: 1 / (2 * nm.arange(self.n_el_nod) + 1)
lhs_diag = nm.einsum("q,q...->...", weights, base_vals_qp ** 2)
rhs_vec = nm.einsum("q,q...,iq...->i...",
weights, base_vals_qp, fun(coors))
vals = (rhs_vec / lhs_diag)
# plot for 1D
# from utils.visualizer import plot1D_legendre_dofs, reconstruct
# _legendre_dofs
# import matplotlib.pyplot as plt
# plot1D_legendre_dofs(self.domain.mesh.coors, (vals,), fun)
# ww, xx = reconstruct_legendre_dofs(self.domain.mesh.coors, 1,
# vals.T[..., None, None])
# plt.plot(xx, ww[:, 0], label="reconstructed dofs")
# plt.show()
return nods, vals
def set_facet_dofs(self, fun, region, dpn, warn):
"""Compute projection of fun onto the basis on facets, alternatively
set DOFs directly to provided value or values
Parameters
----------
fun : callable, scalar or array corresponding to dofs
region : sfepy.discrete.common.region.Region
region to set DOFs on
dpn : int
number of dofs per element
warn :
not used
Returns
-------
nods : ndarray
vals : ndarray
"""
raise NotImplementedError(
"Setting facet DOFs is not supported with DGField, " +
"use values at qp directly. " +
"This is usually result of using ebc instead of dgebc")
aux = self.get_dofs_in_region(region)
nods = nm.unique(nm.hstack(aux))
if nm.isscalar(fun):
vals = nm.zeros(aux.shape)
vals[:, 0] = fun
vals = nm.hstack(vals)
elif isinstance(fun, nm.ndarray):
assert_(len(fun) == dpn)
vals = nm.zeros(aux.shape)
vals[:, 0] = nm.repeat(fun, vals.shape[0])
elif callable(fun):
vals = nm.zeros(aux.shape)
# set zero DOF to value fun, set other DOFs to zero
# get facets QPs
qp, weights = self.get_facet_qp()
weights = weights[0, :, 0]
qp = qp[:, 0, :, :]
# get facets weights ?
# get coors
bc2bfi = self.get_bc_facet_idx(region)
coors = self.mapping.get_physical_qps(qp)
# get_physical_qps returns data in strange format, swapping
# some axis and flipping qps order
bcoors = coors[bc2bfi[:, 1], ::-1, bc2bfi[:, 0], :]
# get facet basis vals
base_vals_qp = self.poly_space.eval_base(qp)[:, 0, 0, :]
# solve for boundary cell DOFs
bc_val = fun(bcoors)
# this returns singular matrix - projection on the boundary should
# be into facet dim space
#lhs = nm.einsum("q,qd,qc->dc", weights, base_vals_qp, base_vals_qp)
# inv_lhs = nm.linalg.inv(lhs)
# rhs_vec = nm.einsum("q,q...,iq...->i...",
# weights, base_vals_qp, bc_val)
return nods, vals
def get_bc_facet_values(self, fun, region, ret_coors=False, diff=0):
"""Returns values of fun in facet QPs of the region
Parameters
----------
diff: derivative 0 or 1 supported
fun: Function value or values to set qps values to
region : sfepy.discrete.common.region.Region
boundary region
ret_coors: default False,
Return physical coors of qps in shape (n_cell, n_qp, dim).
Returns
-------
vals : ndarray
In shape (n_cell,) + (self.dim,) * diff + (n_qp,)
"""
if region.has_cells():
raise NotImplementedError(
"Region {} has cells and can't be used as boundary region".
format(region))
# get facets QPs
qp, weights = self.get_facet_qp()
weights = weights[0, :, 0]
qp = qp[:, 0, :, :]
n_qp = qp.shape[0]
# get facets weights ?
# get physical coors
bc2bfi = self.get_bc_facet_idx(region)
n_cell = bc2bfi.shape[0]
coors = self.mapping.get_physical_qps(qp)
# get_physical_qps returns data in strange format,
# swapping some axis and flipping qps order
# to get coors in shape (n_facet, n_qp, n_cell, dim)
if len(coors.shape) == 3:
coors = coors[:, None, :, :] # add axis for qps when it is missing
coors = coors.swapaxes(0, 2)
bcoors = coors[bc2bfi[:, 1], ::-1, bc2bfi[:, 0], :]
diff_shape = (self.dim,) * diff
output_shape = (n_cell,) + diff_shape + (n_qp,)
vals = nm.zeros(output_shape)
# we do not need last axis of coors, values are scalars
if nm.isscalar(fun):
if sum(diff_shape) > 1:
output(("Warning: Setting gradient of shape {} "
"in region {} with scalar value {}")
.format(diff_shape, region.name, fun))
vals[:] = fun
elif isinstance(fun, nm.ndarray):
try:
vals[:] = fun[:, None]
except ValueError:
raise ValueError(("Provided values of shape {} could not" +
" be used to set BC qps of shape {} in " +
"region {}")
.format(fun.shape, vals.shape, region.name))
elif callable(fun):
# get boundary values
vals[:] = fun(bcoors)
if ret_coors:
return bcoors, vals
return vals
def get_nodal_values(self, dofs, region, ref_nodes=None):
"""Computes nodal representation of the DOFs
Parameters
---------
dofs : array_like
dofs to transform to nodes
region : ignored
ref_nodes:
reference node to use instead of default qps
Parameters
----------
dofs : array_like
region : Region
ref_nodes : array_like
(Default value = None)
Returns
-------
nodes : ndarray
nodal_vals : ndarray
"""
if ref_nodes is None:
# poly_space could provide special nodes
ref_nodes = self.get_qp('v', self.integral).vals
base_vals_node = self.poly_space.eval_base(ref_nodes)[:, 0, :]
dofs = self.unravel_sol(dofs[:, 0])
nodal_vals = nm.sum(dofs * base_vals_node.T, axis=1)
nodes = self.mapping.get_physical_qps(ref_nodes)
# import matplotlib.pyplot as plt
# plt.plot(nodes[:, 0], nodal_vals)
# plt.show()
return nodes, nodal_vals
def create_output(self, dofs, var_name, dof_names=None,
key=None, extend=True, fill_value=None,
linearization=None):
"""Converts the DOFs corresponding to the field to a dictionary of
output data usable by Mesh.write().
For 1D puts DOFs into vairables u_modal{0} ... u_modal{n}, where
n = approx_order and marks them for writing as cell data.
For 2+D puts dofs into name_cell_nodes and creates sturct with:
mode = "cell_nodes", data and iterpolation scheme.
Also get node values and adds them to dictionary as cell_nodes
Parameters
----------
dofs : ndarray, shape (n_nod, n_component)
The array of DOFs reshaped so that each column corresponds
to one component.
var_name : str
The variable name corresponding to `dofs`.
dof_names : tuple of str
The names of DOF components. (Default value = None)
key : str, optional
The key to be used in the output dictionary instead of the
variable name. (Default value = None)
extend : bool, not used
Extend the DOF values to cover the whole domain.
(Default value = True)
fill_value : float or complex, not used
The value used to fill the missing DOF values if `extend` is True.
(Default value = None)
linearization : Struct or None, not used
The linearization configuration for higher order approximations.
(Default value = None)
Returns
-------
out : dict
"""
out = {}
udofs = self.unravel_sol(dofs)
name = var_name if key is None else key
if self.dim == 1:
for i in range(self.n_el_nod):
out[name + "_modal{}".format(i)] = \
Struct(mode="cell", data=udofs[:, i, None, None])
else:
interpolation_scheme = self.poly_space.get_interpol_scheme()
unravel = get_unraveler(self.n_el_nod, self.n_cell)
out[name + "_cell_nodes"] = Struct(mode="cell_nodes",
data=unravel(dofs)[..., 0],
scheme=interpolation_scheme)
return out | [
"sfepy.discrete.fem.mappings.VolumeMapping",
"sfepy.base.base.Struct.__init__",
"sfepy.discrete.Integral",
"sfepy.base.base.Struct",
"sfepy.discrete.common.fields.parse_shape",
"sfepy.discrete.PolySpace.any_from_args"
] | [((3017, 3054), 'six.iteritems', 'six.iteritems', (['region.domain.geom_els'], {}), '(region.domain.geom_els)\n', (3030, 3054), False, 'import six\n'), ((1255, 1369), 'numpy.lib.stride_tricks.as_strided', 'as_strided', (['u'], {'shape': '(n_cell, n_el_nod, 1)', 'strides': '(n_el_nod * ustride1, ustride1, ustride1)', 'writeable': '(False)'}), '(u, shape=(n_cell, n_el_nod, 1), strides=(n_el_nod * ustride1,\n ustride1, ustride1), writeable=False)\n', (1265, 1369), False, 'from numpy.lib.stride_tricks import as_strided\n'), ((4382, 4425), 'sfepy.discrete.common.fields.parse_shape', 'parse_shape', (['shape', 'region.domain.shape.dim'], {}), '(shape, region.domain.shape.dim)\n', (4393, 4425), False, 'from sfepy.discrete.common.fields import parse_shape\n'), ((4434, 4507), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'name': 'name', 'dtype': 'dtype', 'shape': 'shape', 'region': 'region'}), '(self, name=name, dtype=dtype, shape=shape, region=region)\n', (4449, 4507), False, 'from sfepy.base.base import output, assert_, Struct\n'), ((6283, 6393), 'sfepy.discrete.PolySpace.any_from_args', 'PolySpace.any_from_args', (['name', 'self.gel', 'self.approx_order'], {'base': 'self.poly_space_base', 'force_bubble': '(False)'}), '(name, self.gel, self.approx_order, base=self.\n poly_space_base, force_bubble=False)\n', (6306, 6393), False, 'from sfepy.discrete import Integral, PolySpace\n'), ((7878, 7900), 'numpy.arange', 'nm.arange', (['self.n_cell'], {}), '(self.n_cell)\n', (7887, 7900), True, 'import numpy as nm\n'), ((8214, 8233), 'numpy.prod', 'nm.prod', (['self.shape'], {}), '(self.shape)\n', (8221, 8233), True, 'import numpy as nm\n'), ((16796, 16846), 'numpy.zeros', 'nm.zeros', (['(n_cell, n_el_facets, 2)'], {'dtype': 'nm.int32'}), '((n_cell, n_el_facets, 2), dtype=nm.int32)\n', (16804, 16846), True, 'import numpy as nm\n'), ((24365, 24388), 'numpy.zeros', 'nm.zeros', (['outputs_shape'], {}), '(outputs_shape)\n', (24373, 24388), True, 'import numpy as nm\n'), ((24805, 24828), 'numpy.zeros', 'nm.zeros', (['outputs_shape'], {}), '(outputs_shape)\n', (24813, 24828), True, 'import numpy as nm\n'), ((24852, 24875), 'six.moves.range', 'range', (['self.n_el_facets'], {}), '(self.n_el_facets)\n', (24857, 24875), False, 'from six.moves import range\n'), ((27902, 27922), 'numpy.zeros', 'nm.zeros', (['base_shape'], {}), '(base_shape)\n', (27910, 27922), True, 'import numpy as nm\n'), ((27955, 27975), 'numpy.zeros', 'nm.zeros', (['base_shape'], {}), '(base_shape)\n', (27963, 27975), True, 'import numpy as nm\n'), ((30071, 30107), 'numpy.zeros', 'nm.zeros', (['(n_cell, n_el_facets, dim)'], {}), '((n_cell, n_el_facets, dim))\n', (30079, 30107), True, 'import numpy as nm\n'), ((31696, 31730), 'numpy.zeros', 'nm.zeros', (['(n_cell, n_el_facets, 1)'], {}), '((n_cell, n_el_facets, 1))\n', (31704, 31730), True, 'import numpy as nm\n'), ((39779, 39795), 'numpy.isscalar', 'nm.isscalar', (['fun'], {}), '(fun)\n', (39790, 39795), True, 'import numpy as nm\n'), ((42261, 42277), 'numpy.isscalar', 'nm.isscalar', (['fun'], {}), '(fun)\n', (42272, 42277), True, 'import numpy as nm\n'), ((45384, 45406), 'numpy.zeros', 'nm.zeros', (['output_shape'], {}), '(output_shape)\n', (45392, 45406), True, 'import numpy as nm\n'), ((45483, 45499), 'numpy.isscalar', 'nm.isscalar', (['fun'], {}), '(fun)\n', (45494, 45499), True, 'import numpy as nm\n'), ((47230, 47269), 'numpy.sum', 'nm.sum', (['(dofs * base_vals_node.T)'], {'axis': '(1)'}), '(dofs * base_vals_node.T, axis=1)\n', (47236, 47269), True, 'import numpy as nm\n'), ((2327, 2338), 'numpy.ravel', 'nm.ravel', (['u'], {}), '(u)\n', (2335, 2338), True, 'import numpy as nm\n'), ((5541, 5587), 'sfepy.discrete.Integral', 'Integral', (['"""dg_fi"""'], {'order': '(2 * self.approx_order)'}), "('dg_fi', order=2 * self.approx_order)\n", (5549, 5587), False, 'from sfepy.discrete import Integral, PolySpace\n'), ((7963, 7985), 'numpy.arange', 'nm.arange', (['self.n_cell'], {}), '(self.n_cell)\n', (7972, 7985), True, 'import numpy as nm\n'), ((12657, 12675), 'numpy.ones', 'nm.ones', (['(1, 1, 1)'], {}), '((1, 1, 1))\n', (12664, 12675), True, 'import numpy as nm\n'), ((14223, 14246), 'six.moves.range', 'range', (['self.n_el_facets'], {}), '(self.n_el_facets)\n', (14228, 14246), False, 'from six.moves import range\n'), ((20616, 20657), 'numpy.unique', 'nm.unique', (['self.dofs2cells[eq_map.master]'], {}), '(self.dofs2cells[eq_map.master])\n', (20625, 20657), True, 'import numpy as nm\n'), ((20679, 20719), 'numpy.unique', 'nm.unique', (['self.dofs2cells[eq_map.slave]'], {}), '(self.dofs2cells[eq_map.slave])\n', (20688, 20719), True, 'import numpy as nm\n'), ((24448, 24504), 'numpy.einsum', 'nm.einsum', (['"""id...,idf...->ifd..."""', 'dofs', 'inner_base_vals'], {}), "('id...,idf...->ifd...', dofs, inner_base_vals)\n", (24457, 24504), True, 'import numpy as nm\n'), ((24597, 24650), 'numpy.einsum', 'nm.einsum', (['"""id...,id...->i..."""', 'dofs', 'inner_base_vals'], {}), "('id...,id...->i...', dofs, inner_base_vals)\n", (24606, 24650), True, 'import numpy as nm\n'), ((27612, 27625), 'numpy.shape', 'nm.shape', (['whs'], {}), '(whs)\n', (27620, 27625), True, 'import numpy as nm\n'), ((31580, 31606), 'numpy.ones', 'nm.ones', (['(cmesh.num[0], 1)'], {}), '((cmesh.num[0], 1))\n', (31587, 31606), True, 'import numpy as nm\n'), ((35020, 35061), 'numpy.ravel', 'nm.ravel', (['self.bubble_remap[region.cells]'], {}), '(self.bubble_remap[region.cells])\n', (35028, 35061), True, 'import numpy as nm\n'), ((35490, 35510), 'numpy.concatenate', 'nm.concatenate', (['dofs'], {}), '(dofs)\n', (35504, 35510), True, 'import numpy as nm\n'), ((37212, 37257), 'sfepy.discrete.fem.mappings.VolumeMapping', 'VolumeMapping', (['coors', 'conn'], {'poly_space': 'geo_ps'}), '(coors, conn, poly_space=geo_ps)\n', (37225, 37257), False, 'from sfepy.discrete.fem.mappings import VolumeMapping\n'), ((39751, 39765), 'numpy.hstack', 'nm.hstack', (['aux'], {}), '(aux)\n', (39760, 39765), True, 'import numpy as nm\n'), ((39816, 39835), 'numpy.zeros', 'nm.zeros', (['aux.shape'], {}), '(aux.shape)\n', (39824, 39835), True, 'import numpy as nm\n'), ((39884, 39899), 'numpy.hstack', 'nm.hstack', (['vals'], {}), '(vals)\n', (39893, 39899), True, 'import numpy as nm\n'), ((42233, 42247), 'numpy.hstack', 'nm.hstack', (['aux'], {}), '(aux)\n', (42242, 42247), True, 'import numpy as nm\n'), ((42298, 42317), 'numpy.zeros', 'nm.zeros', (['aux.shape'], {}), '(aux.shape)\n', (42306, 42317), True, 'import numpy as nm\n'), ((42366, 42381), 'numpy.hstack', 'nm.hstack', (['vals'], {}), '(vals)\n', (42375, 42381), True, 'import numpy as nm\n'), ((49323, 49343), 'six.moves.range', 'range', (['self.n_el_nod'], {}), '(self.n_el_nod)\n', (49328, 49343), False, 'from six.moves import range\n'), ((7772, 7804), 'numpy.arange', 'nm.arange', (['n_dof'], {'dtype': 'nm.int32'}), '(n_dof, dtype=nm.int32)\n', (7781, 7804), True, 'import numpy as nm\n'), ((12610, 12626), 'numpy.zeros', 'nm.zeros', (['(1, 1)'], {}), '((1, 1))\n', (12618, 12626), True, 'import numpy as nm\n'), ((24978, 25088), 'numpy.einsum', 'nm.einsum', (['"""id...,id...->id..."""', 'dofs[per_facet_neighbours[:, facet_n, 0]]', 'outer_base_vals[:, :, facet_n]'], {}), "('id...,id...->id...', dofs[per_facet_neighbours[:, facet_n, 0]],\n outer_base_vals[:, :, facet_n])\n", (24987, 25088), True, 'import numpy as nm\n'), ((25235, 25344), 'numpy.einsum', 'nm.einsum', (['"""id...,id...->i..."""', 'dofs[per_facet_neighbours[:, facet_n, 0]]', 'outer_base_vals[:, :, facet_n]'], {}), "('id...,id...->i...', dofs[per_facet_neighbours[:, facet_n, 0]],\n outer_base_vals[:, :, facet_n])\n", (25244, 25344), True, 'import numpy as nm\n'), ((25436, 25479), 'numpy.where', 'nm.where', (['(per_facet_neighbours[:, :, 0] < 0)'], {}), '(per_facet_neighbours[:, :, 0] < 0)\n', (25444, 25479), True, 'import numpy as nm\n'), ((26027, 26099), 'numpy.einsum', 'nm.einsum', (['"""id,id...->id..."""', 'ebc_vals', 'inner_base_vals[0, :, ebc[:, 1]]'], {}), "('id,id...->id...', ebc_vals, inner_base_vals[0, :, ebc[:, 1]])\n", (26036, 26099), True, 'import numpy as nm\n'), ((42481, 42500), 'numpy.zeros', 'nm.zeros', (['aux.shape'], {}), '(aux.shape)\n', (42489, 42500), True, 'import numpy as nm\n'), ((42526, 42555), 'numpy.repeat', 'nm.repeat', (['fun', 'vals.shape[0]'], {}), '(fun, vals.shape[0])\n', (42535, 42555), True, 'import numpy as nm\n'), ((49418, 49467), 'sfepy.base.base.Struct', 'Struct', ([], {'mode': '"""cell"""', 'data': 'udofs[:, i, None, None]'}), "(mode='cell', data=udofs[:, i, None, None])\n", (49424, 49467), False, 'from sfepy.base.base import output, assert_, Struct\n'), ((9787, 9811), 'numpy.arange', 'nm.arange', (['self.n_el_nod'], {}), '(self.n_el_nod)\n', (9796, 9811), True, 'import numpy as nm\n'), ((10587, 10600), 'numpy.shape', 'nm.shape', (['qps'], {}), '(qps)\n', (10595, 10600), True, 'import numpy as nm\n'), ((20774, 20814), 'numpy.where', 'nm.where', (['(facet_neighbours[mcells] == -1)'], {}), '(facet_neighbours[mcells] == -1)\n', (20782, 20814), True, 'import numpy as nm\n'), ((20893, 20933), 'numpy.where', 'nm.where', (['(facet_neighbours[scells] == -1)'], {}), '(facet_neighbours[scells] == -1)\n', (20901, 20933), True, 'import numpy as nm\n'), ((40036, 40049), 'numpy.shape', 'nm.shape', (['fun'], {}), '(fun)\n', (40044, 40049), True, 'import numpy as nm\n'), ((40053, 40067), 'numpy.shape', 'nm.shape', (['nods'], {}), '(nods)\n', (40061, 40067), True, 'import numpy as nm\n'), ((40636, 40688), 'numpy.einsum', 'nm.einsum', (['"""q,q...->..."""', 'weights', '(base_vals_qp ** 2)'], {}), "('q,q...->...', weights, base_vals_qp ** 2)\n", (40645, 40688), True, 'import numpy as nm\n'), ((42604, 42623), 'numpy.zeros', 'nm.zeros', (['aux.shape'], {}), '(aux.shape)\n', (42612, 42623), True, 'import numpy as nm\n'), ((9528, 9543), 'numpy.shape', 'nm.shape', (['coors'], {}), '(coors)\n', (9536, 9543), True, 'import numpy as nm\n'), ((9850, 9866), 'numpy.unique', 'nm.unique', (['cells'], {}), '(cells)\n', (9859, 9866), True, 'import numpy as nm\n'), ((10738, 10751), 'numpy.shape', 'nm.shape', (['qps'], {}), '(qps)\n', (10746, 10751), True, 'import numpy as nm\n'), ((11149, 11162), 'numpy.shape', 'nm.shape', (['qps'], {}), '(qps)\n', (11157, 11162), True, 'import numpy as nm\n'), ((14159, 14172), 'numpy.shape', 'nm.shape', (['qps'], {}), '(qps)\n', (14167, 14172), True, 'import numpy as nm\n'), ((14009, 14022), 'numpy.shape', 'nm.shape', (['qps'], {}), '(qps)\n', (14017, 14022), True, 'import numpy as nm\n')] |
from __future__ import absolute_import
input_name = '../examples/multi_physics/piezo_elasticity.py'
output_name = 'test_piezo_elasticity.vtk'
from tests_basic import TestInput
class Test( TestInput ):
def from_conf( conf, options ):
return TestInput.from_conf( conf, options, cls = Test )
from_conf = staticmethod( from_conf )
def test_ebc( self ):
import numpy as nm
from sfepy.discrete import Problem
pb = Problem.from_conf(self.test_conf)
pb.time_update()
vvs = pb.get_variables()
setv = vvs.set_state_part
make_full = vvs.make_full_vec
svec_u = nm.ones( (vvs.adi.n_dof['u'],), dtype = nm.float64 )
svec_phi = nm.empty( (vvs.adi.n_dof['phi'],), dtype = nm.float64 )
svec_phi.fill( 2.0 )
svec = vvs.create_stripped_state_vector()
setv( svec, svec_u, 'u', stripped = True )
setv( svec, svec_phi, 'phi', stripped = True )
vec = make_full( svec )
ii_u = vvs.di.indx['u'].start + vvs['u'].eq_map.eqi
ii_phi = vvs.di.indx['phi'].start + vvs['phi'].eq_map.eqi
ok_ebc = vvs.has_ebc( vec )
ok_u = nm.all( vec[ii_u] == svec_u )
ok_phi = nm.all( vec[ii_phi] == svec_phi )
msg = '%s: %s'
self.report( msg % ('ebc', ok_ebc) )
self.report( msg % ('u', ok_u) )
self.report( msg % ('phi', ok_phi) )
ok = ok_ebc and ok_u and ok_phi
return ok
| [
"sfepy.discrete.Problem.from_conf"
] | [((256, 300), 'tests_basic.TestInput.from_conf', 'TestInput.from_conf', (['conf', 'options'], {'cls': 'Test'}), '(conf, options, cls=Test)\n', (275, 300), False, 'from tests_basic import TestInput\n'), ((458, 491), 'sfepy.discrete.Problem.from_conf', 'Problem.from_conf', (['self.test_conf'], {}), '(self.test_conf)\n', (475, 491), False, 'from sfepy.discrete import Problem\n'), ((641, 689), 'numpy.ones', 'nm.ones', (["(vvs.adi.n_dof['u'],)"], {'dtype': 'nm.float64'}), "((vvs.adi.n_dof['u'],), dtype=nm.float64)\n", (648, 689), True, 'import numpy as nm\n'), ((713, 764), 'numpy.empty', 'nm.empty', (["(vvs.adi.n_dof['phi'],)"], {'dtype': 'nm.float64'}), "((vvs.adi.n_dof['phi'],), dtype=nm.float64)\n", (721, 764), True, 'import numpy as nm\n'), ((1167, 1194), 'numpy.all', 'nm.all', (['(vec[ii_u] == svec_u)'], {}), '(vec[ii_u] == svec_u)\n', (1173, 1194), True, 'import numpy as nm\n'), ((1214, 1245), 'numpy.all', 'nm.all', (['(vec[ii_phi] == svec_phi)'], {}), '(vec[ii_phi] == svec_phi)\n', (1220, 1245), True, 'import numpy as nm\n')] |
"""
Finite element reference mappings.
"""
import numpy as nm
from sfepy import Config
from sfepy.base.base import get_default, output
from sfepy.base.mem_usage import raise_if_too_large
from sfepy.discrete.common.mappings import Mapping
from sfepy.discrete.common.extmods.mappings import CMapping
from sfepy.discrete import PolySpace
class FEMapping(Mapping):
"""
Base class for finite element mappings.
"""
def __init__(self, coors, conn, poly_space=None, gel=None, order=1):
self.coors = coors
self.conn = conn
try:
nm.take(self.coors, self.conn)
except IndexError:
output('coordinates shape: %s' % list(coors.shape))
output('connectivity: min: %d, max: %d' % (conn.min(), conn.max()))
msg = 'incompatible connectivity and coordinates (see above)'
raise IndexError(msg)
self.n_el, self.n_ep = conn.shape
self.dim = self.coors.shape[1]
if poly_space is None:
poly_space = PolySpace.any_from_args(None, gel, order,
base='lagrange',
force_bubble=False)
self.poly_space = poly_space
self.indices = slice(None)
def get_geometry(self):
"""
Return reference element geometry as a GeometryElement instance.
"""
return self.poly_space.geometry
def get_base(self, coors, diff=False):
"""
Get base functions or their gradient evaluated in given
coordinates.
"""
bf = self.poly_space.eval_base(coors, diff=diff)
return bf
def get_physical_qps(self, qp_coors):
"""
Get physical quadrature points corresponding to given reference
element quadrature points.
Returns
-------
qps : array
The physical quadrature points ordered element by element,
i.e. with shape (n_el, n_qp, dim).
"""
bf = self.get_base(qp_coors)
qps = nm.dot(nm.atleast_2d(bf.squeeze()), self.coors[self.conn])
# Reorder so that qps are really element by element.
qps = nm.ascontiguousarray(nm.swapaxes(qps, 0, 1))
return qps
class VolumeMapping(FEMapping):
"""
Mapping from reference domain to physical domain of the same space
dimension.
"""
def get_mapping(self, qp_coors, weights, poly_space=None, ori=None,
transform=None):
"""
Get the mapping for given quadrature points, weights, and
polynomial space.
Returns
-------
cmap : CMapping instance
The volume mapping.
"""
poly_space = get_default(poly_space, self.poly_space)
bf_g = self.get_base(qp_coors, diff=True)
ebf_g = poly_space.eval_base(qp_coors, diff=True, ori=ori,
force_axis=True, transform=transform)
size = ebf_g.nbytes * self.n_el
site_config = Config()
raise_if_too_large(size, site_config.refmap_memory_factor())
flag = (ori is not None) or (ebf_g.shape[0] > 1)
cmap = CMapping(self.n_el, qp_coors.shape[0], self.dim,
poly_space.n_nod, mode='volume', flag=flag)
cmap.describe(self.coors, self.conn, bf_g, ebf_g, weights)
return cmap
class SurfaceMapping(FEMapping):
"""
Mapping from reference domain to physical domain of the space
dimension higher by one.
"""
def set_basis_indices(self, indices):
"""
Set indices to cell-based basis that give the facet-based basis.
"""
self.indices = indices
def get_base(self, coors, diff=False):
"""
Get base functions or their gradient evaluated in given
coordinates.
"""
bf = self.poly_space.eval_base(coors, diff=diff)
ii = max(self.dim - 1, 1)
return nm.ascontiguousarray(bf[..., :ii:, self.indices])
def get_mapping(self, qp_coors, weights, poly_space=None, mode='surface'):
"""
Get the mapping for given quadrature points, weights, and
polynomial space.
Returns
-------
cmap : CMapping instance
The surface mapping.
"""
poly_space = get_default(poly_space, self.poly_space)
bf_g = self.get_base(qp_coors, diff=True)
if nm.allclose(bf_g, 0.0) and self.dim > 1:
raise ValueError('zero base function gradient!')
cmap = CMapping(self.n_el, qp_coors.shape[0], self.dim,
poly_space.n_nod, mode=mode)
cmap.describe(self.coors, self.conn, bf_g, None, weights)
if self.dim == 1:
# Fix normals.
ii = nm.where(self.conn == 0)[0]
cmap.normal[ii] *= -1.0
return cmap
| [
"sfepy.base.base.get_default",
"sfepy.discrete.common.extmods.mappings.CMapping",
"sfepy.discrete.PolySpace.any_from_args",
"sfepy.Config"
] | [((2744, 2784), 'sfepy.base.base.get_default', 'get_default', (['poly_space', 'self.poly_space'], {}), '(poly_space, self.poly_space)\n', (2755, 2784), False, 'from sfepy.base.base import get_default, output\n'), ((3041, 3049), 'sfepy.Config', 'Config', ([], {}), '()\n', (3047, 3049), False, 'from sfepy import Config\n'), ((3193, 3290), 'sfepy.discrete.common.extmods.mappings.CMapping', 'CMapping', (['self.n_el', 'qp_coors.shape[0]', 'self.dim', 'poly_space.n_nod'], {'mode': '"""volume"""', 'flag': 'flag'}), "(self.n_el, qp_coors.shape[0], self.dim, poly_space.n_nod, mode=\n 'volume', flag=flag)\n", (3201, 3290), False, 'from sfepy.discrete.common.extmods.mappings import CMapping\n'), ((3973, 4021), 'numpy.ascontiguousarray', 'nm.ascontiguousarray', (['bf[..., :ii, self.indices]'], {}), '(bf[..., :ii, self.indices])\n', (3993, 4021), True, 'import numpy as nm\n'), ((4339, 4379), 'sfepy.base.base.get_default', 'get_default', (['poly_space', 'self.poly_space'], {}), '(poly_space, self.poly_space)\n', (4350, 4379), False, 'from sfepy.base.base import get_default, output\n'), ((4560, 4637), 'sfepy.discrete.common.extmods.mappings.CMapping', 'CMapping', (['self.n_el', 'qp_coors.shape[0]', 'self.dim', 'poly_space.n_nod'], {'mode': 'mode'}), '(self.n_el, qp_coors.shape[0], self.dim, poly_space.n_nod, mode=mode)\n', (4568, 4637), False, 'from sfepy.discrete.common.extmods.mappings import CMapping\n'), ((575, 605), 'numpy.take', 'nm.take', (['self.coors', 'self.conn'], {}), '(self.coors, self.conn)\n', (582, 605), True, 'import numpy as nm\n'), ((1025, 1103), 'sfepy.discrete.PolySpace.any_from_args', 'PolySpace.any_from_args', (['None', 'gel', 'order'], {'base': '"""lagrange"""', 'force_bubble': '(False)'}), "(None, gel, order, base='lagrange', force_bubble=False)\n", (1048, 1103), False, 'from sfepy.discrete import PolySpace\n'), ((2220, 2242), 'numpy.swapaxes', 'nm.swapaxes', (['qps', '(0)', '(1)'], {}), '(qps, 0, 1)\n', (2231, 2242), True, 'import numpy as nm\n'), ((4442, 4464), 'numpy.allclose', 'nm.allclose', (['bf_g', '(0.0)'], {}), '(bf_g, 0.0)\n', (4453, 4464), True, 'import numpy as nm\n'), ((4798, 4822), 'numpy.where', 'nm.where', (['(self.conn == 0)'], {}), '(self.conn == 0)\n', (4806, 4822), True, 'import numpy as nm\n')] |
r"""
Incompressible Stokes flow with Navier (slip) boundary conditions, flow driven
by a moving wall and a small diffusion for stabilization.
This example demonstrates the use of `no-penetration` boundary conditions as
well as `edge direction` boundary conditions together with Navier or slip
boundary conditions.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}
- \int_{\Omega} p\ \nabla \cdot \ul{v}
+ \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d)
+ \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u}
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} \mu \nabla q \cdot \nabla p
+ \int_{\Omega} q\ \nabla \cdot \ul{u}
= 0
\;, \quad \forall q \;,
where :math:`\nu` is the fluid viscosity, :math:`\beta` is the slip
coefficient, :math:`\mu` is the (small) numerical diffusion coefficient,
:math:`\Gamma_1` is the top wall that moves with the given driving velocity
:math:`\ul{u}_d` and :math:`\Gamma_2` are the remaining walls. The Navier
conditions are in effect on both :math:`\Gamma_1`, :math:`\Gamma_2` and are
expressed by the corresponding integrals in the equations above.
The `no-penetration` boundary conditions are applied on :math:`\Gamma_1`,
:math:`\Gamma_2`, except the vertices of the block edges, where the `edge
direction` boundary conditions are applied. Optionally, Dirichlet boundary
conditions can be applied on the inlet, see the code below.
The mesh is created by ``gen_block_mesh()`` function - try different mesh
dimensions and resolutions below. For large meshes use the ``'ls_i'`` linear
solver - PETSc + petsc4py is needed in that case.
"""
import numpy as nm
from sfepy.discrete.fem.meshio import UserMeshIO
from sfepy.mesh.mesh_generators import gen_block_mesh
from sfepy.homogenization.utils import define_box_regions
# Mesh dimensions.
dims = nm.array([3, 1, 0.5])
# Mesh resolution: increase to improve accuracy.
shape = [11, 15, 15]
def mesh_hook(mesh, mode):
"""
Generate the block mesh.
"""
if mode == 'read':
mesh = gen_block_mesh(dims, shape, [0, 0, 0], name='user_block',
verbose=False)
return mesh
elif mode == 'write':
pass
filename_mesh = UserMeshIO(mesh_hook)
regions = define_box_regions(3, 0.5 * dims)
regions.update({
'Omega' : 'all',
'Edges_v' : ("""(r.Near *v r.Bottom) +v
(r.Bottom *v r.Far) +v
(r.Far *v r.Top) +v
(r.Top *v r.Near)""", 'edge'),
'Gamma1_f' : ('copy r.Top', 'face'),
'Gamma2_f' : ('r.Near +v r.Bottom +v r.Far', 'face'),
'Gamma_f' : ('r.Gamma1_f +v r.Gamma2_f', 'face'),
'Gamma_v' : ('r.Gamma_f -v r.Edges_v', 'face'),
'Inlet_f' : ('r.Left -v r.Gamma_f', 'face'),
})
fields = {
'velocity' : ('real', 3, 'Omega', 1),
'pressure' : ('real', 1, 'Omega', 1),
}
def get_u_d(ts, coors, region=None):
"""
Given stator velocity.
"""
out = nm.zeros_like(coors)
out[:] = [1.0, 1.0, 0.0]
return out
functions = {
'get_u_d' : (get_u_d,),
}
variables = {
'u' : ('unknown field', 'velocity', 0),
'v' : ('test field', 'velocity', 'u'),
'u_d' : ('parameter field', 'velocity',
{'setter' : 'get_u_d'}),
'p' : ('unknown field', 'pressure', 1),
'q' : ('test field', 'pressure', 'p'),
}
# Try setting the inlet velocity by un-commenting the ebcs.
ebcs = {
## 'inlet' : ('Inlet_f', {'u.0' : 1.0, 'u.[1, 2]' : 0.0}),
}
lcbcs = {
'walls' : ('Gamma_v', {'u.all' : 'no_penetration'},
'normals_Gamma.vtk'),
'edges' : ('Edges_v', {'u.all' : 'edge_direction'},
'edges_Edges.vtk'),
}
materials = {
'm' : ({
'nu' : 1e-3,
'beta' : 1e-2,
'mu' : 1e-10,
},),
}
equations = {
'balance' :
"""dw_div_grad.5.Omega(m.nu, v, u)
- dw_stokes.5.Omega(v, p)
+ dw_surface_dot.5.Gamma1_f(m.beta, v, u)
+ dw_surface_dot.5.Gamma2_f(m.beta, v, u)
=
+ dw_surface_dot.5.Gamma1_f(m.beta, v, u_d)""",
'incompressibility' :
"""dw_laplace.5.Omega(m.mu, q, p)
+ dw_stokes.5.Omega(u, q) = 0""",
}
solvers = {
'ls_d' : ('ls.scipy_direct', {}),
## 'ls_i' : ('ls.petsc', {
## 'method' : 'bcgsl', # ksp_type
## 'precond' : 'ilu', # pc_type
## 'eps_a' : 0.0, # abstol
## 'eps_r' : 1e-12, # rtol
## 'eps_d' : 1e10, # Divergence tolerance.
## 'i_max' : 2500, # maxits
## }),
'newton' : ('nls.newton', {
'i_max' : 1,
'eps_a' : 1e-10,
}),
}
options = {
'nls' : 'newton',
'ls' : 'ls_d',
}
| [
"sfepy.mesh.mesh_generators.gen_block_mesh",
"sfepy.discrete.fem.meshio.UserMeshIO",
"sfepy.homogenization.utils.define_box_regions"
] | [((1872, 1893), 'numpy.array', 'nm.array', (['[3, 1, 0.5]'], {}), '([3, 1, 0.5])\n', (1880, 1893), True, 'import numpy as nm\n'), ((2256, 2277), 'sfepy.discrete.fem.meshio.UserMeshIO', 'UserMeshIO', (['mesh_hook'], {}), '(mesh_hook)\n', (2266, 2277), False, 'from sfepy.discrete.fem.meshio import UserMeshIO\n'), ((2289, 2322), 'sfepy.homogenization.utils.define_box_regions', 'define_box_regions', (['(3)', '(0.5 * dims)'], {}), '(3, 0.5 * dims)\n', (2307, 2322), False, 'from sfepy.homogenization.utils import define_box_regions\n'), ((2985, 3005), 'numpy.zeros_like', 'nm.zeros_like', (['coors'], {}), '(coors)\n', (2998, 3005), True, 'import numpy as nm\n'), ((2076, 2148), 'sfepy.mesh.mesh_generators.gen_block_mesh', 'gen_block_mesh', (['dims', 'shape', '[0, 0, 0]'], {'name': '"""user_block"""', 'verbose': '(False)'}), "(dims, shape, [0, 0, 0], name='user_block', verbose=False)\n", (2090, 2148), False, 'from sfepy.mesh.mesh_generators import gen_block_mesh\n')] |
"""
Quadratic eigenvalue problem solvers.
"""
from __future__ import absolute_import
import time
import numpy as nm
import scipy.sparse as sps
from sfepy.base.base import output, get_default
from sfepy.linalg.utils import max_diff_csr
from sfepy.solvers.solvers import QuadraticEVPSolver
def standard_call(call):
"""
Decorator handling argument preparation and timing for quadratic
eigensolvers.
"""
def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None,
eigenvectors=None, status=None, conf=None, **kwargs):
timer = Timer(start=True)
conf = get_default(conf, self.conf)
mtx_m = get_default(mtx_m, self.mtx_m)
mtx_d = get_default(mtx_d, self.mtx_d)
mtx_k = get_default(mtx_k, self.mtx_k)
n_eigs = get_default(n_eigs, self.n_eigs)
eigenvectors = get_default(eigenvectors, self.eigenvectors)
status = get_default(status, self.status)
result = call(self, mtx_m, mtx_d, mtx_k,
n_eigs, eigenvectors, status, conf,
**kwargs)
elapsed = timer.stop()
if status is not None:
status['time'] = elapsed
return result
return _standard_call
class LQuadraticEVPSolver(QuadraticEVPSolver):
"""
Quadratic eigenvalue problem solver based on the problem linearization.
(w^2 M + w D + K) x = 0.
"""
name = 'eig.qevp'
_parameters = [
('method', "{'companion', 'cholesky'}", 'companion', False,
'The linearization method.'),
('solver', 'dict', {'kind': 'eig.scipy', 'method': 'eig'}, False,
"""The configuration of an eigenvalue solver for
the linearized problem (A - w B) x = 0."""),
('mode', "{'normal', 'inverted'}", 'normal', False,
'Solve either A - w B (normal), or B - 1/w A (inverted).'),
('debug', 'bool', False, False,
'If True, print debugging information.'),
]
@standard_call
def __call__(self, mtx_m, mtx_d, mtx_k, n_eigs=None,
eigenvectors=None, status=None, conf=None):
if conf.debug:
ssym = status['matrix_info'] = {}
ssym['|M - M^T|'] = max_diff_csr(mtx_m, mtx_m.T)
ssym['|D - D^T|'] = max_diff_csr(mtx_d, mtx_d.T)
ssym['|K - K^T|'] = max_diff_csr(mtx_k, mtx_k.T)
ssym['|M - M^H|'] = max_diff_csr(mtx_m, mtx_m.H)
ssym['|D - D^H|'] = max_diff_csr(mtx_d, mtx_d.H)
ssym['|K - K^H|'] = max_diff_csr(mtx_k, mtx_k.H)
if conf.method == 'companion':
mtx_eye = -sps.eye(mtx_m.shape[0], dtype=mtx_m.dtype)
mtx_a = sps.bmat([[mtx_d, mtx_k],
[mtx_eye, None]])
mtx_b = sps.bmat([[-mtx_m, None],
[None, mtx_eye]])
elif conf.method == 'cholesky':
from sksparse.cholmod import cholesky
factor = cholesky(mtx_m)
perm = factor.P()
ir = nm.arange(len(perm))
mtx_p = sps.coo_matrix((nm.ones_like(perm), (ir, perm)))
mtx_l = mtx_p.T * factor.L()
if conf.debug:
ssym['|S - LL^T|'] = max_diff_csr(mtx_m, mtx_l * mtx_l.T)
mtx_eye = sps.eye(mtx_l.shape[0], dtype=nm.float64)
mtx_a = sps.bmat([[-mtx_k, None],
[None, mtx_eye]])
mtx_b = sps.bmat([[mtx_d, mtx_l],
[mtx_l.T, None]])
else:
raise ValueError('unknown method! (%s)' % conf.method)
if conf.debug:
ssym['|A - A^T|'] = max_diff_csr(mtx_a, mtx_a.T)
ssym['|A - A^H|'] = max_diff_csr(mtx_a, mtx_a.H)
ssym['|B - B^T|'] = max_diff_csr(mtx_b, mtx_b.T)
ssym['|B - B^H|'] = max_diff_csr(mtx_b, mtx_b.H)
for key, val in sorted(ssym.items()):
output('{}: {}'.format(key, val))
if conf.mode == 'normal':
out = self.solver(mtx_a, mtx_b, n_eigs=n_eigs,
eigenvectors=eigenvectors, status=status)
if eigenvectors:
eigs, vecs = out
out = (eigs, vecs[:mtx_m.shape[0], :])
if conf.debug:
res = mtx_a.dot(vecs) - eigs * mtx_b.dot(vecs)
status['lin. error'] = nm.linalg.norm(res, nm.inf)
else:
out = self.solver(mtx_b, mtx_a, n_eigs=n_eigs,
eigenvectors=eigenvectors, status=status)
if eigenvectors:
eigs, vecs = out
out = (1.0 / eigs, vecs[:mtx_m.shape[0], :])
if conf.debug:
res = (1.0 / eigs) * mtx_b.dot(vecs) - mtx_a.dot(vecs)
status['lin. error'] = nm.linalg.norm(res, nm.inf)
else:
out = 1.0 / out
if conf.debug and eigenvectors:
eigs, vecs = out
res = ((eigs**2 * (mtx_m.dot(vecs)))
+ (eigs * (mtx_d.dot(vecs)))
+ (mtx_k.dot(vecs)))
status['error'] = nm.linalg.norm(res, nm.inf)
return out
| [
"sfepy.base.base.get_default",
"sfepy.linalg.utils.max_diff_csr"
] | [((609, 637), 'sfepy.base.base.get_default', 'get_default', (['conf', 'self.conf'], {}), '(conf, self.conf)\n', (620, 637), False, 'from sfepy.base.base import output, get_default\n'), ((654, 684), 'sfepy.base.base.get_default', 'get_default', (['mtx_m', 'self.mtx_m'], {}), '(mtx_m, self.mtx_m)\n', (665, 684), False, 'from sfepy.base.base import output, get_default\n'), ((701, 731), 'sfepy.base.base.get_default', 'get_default', (['mtx_d', 'self.mtx_d'], {}), '(mtx_d, self.mtx_d)\n', (712, 731), False, 'from sfepy.base.base import output, get_default\n'), ((748, 778), 'sfepy.base.base.get_default', 'get_default', (['mtx_k', 'self.mtx_k'], {}), '(mtx_k, self.mtx_k)\n', (759, 778), False, 'from sfepy.base.base import output, get_default\n'), ((796, 828), 'sfepy.base.base.get_default', 'get_default', (['n_eigs', 'self.n_eigs'], {}), '(n_eigs, self.n_eigs)\n', (807, 828), False, 'from sfepy.base.base import output, get_default\n'), ((852, 896), 'sfepy.base.base.get_default', 'get_default', (['eigenvectors', 'self.eigenvectors'], {}), '(eigenvectors, self.eigenvectors)\n', (863, 896), False, 'from sfepy.base.base import output, get_default\n'), ((914, 946), 'sfepy.base.base.get_default', 'get_default', (['status', 'self.status'], {}), '(status, self.status)\n', (925, 946), False, 'from sfepy.base.base import output, get_default\n'), ((2211, 2239), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx_m', 'mtx_m.T'], {}), '(mtx_m, mtx_m.T)\n', (2223, 2239), False, 'from sfepy.linalg.utils import max_diff_csr\n'), ((2272, 2300), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx_d', 'mtx_d.T'], {}), '(mtx_d, mtx_d.T)\n', (2284, 2300), False, 'from sfepy.linalg.utils import max_diff_csr\n'), ((2333, 2361), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx_k', 'mtx_k.T'], {}), '(mtx_k, mtx_k.T)\n', (2345, 2361), False, 'from sfepy.linalg.utils import max_diff_csr\n'), ((2394, 2422), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx_m', 'mtx_m.H'], {}), '(mtx_m, mtx_m.H)\n', (2406, 2422), False, 'from sfepy.linalg.utils import max_diff_csr\n'), ((2455, 2483), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx_d', 'mtx_d.H'], {}), '(mtx_d, mtx_d.H)\n', (2467, 2483), False, 'from sfepy.linalg.utils import max_diff_csr\n'), ((2516, 2544), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx_k', 'mtx_k.H'], {}), '(mtx_k, mtx_k.H)\n', (2528, 2544), False, 'from sfepy.linalg.utils import max_diff_csr\n'), ((2672, 2715), 'scipy.sparse.bmat', 'sps.bmat', (['[[mtx_d, mtx_k], [mtx_eye, None]]'], {}), '([[mtx_d, mtx_k], [mtx_eye, None]])\n', (2680, 2715), True, 'import scipy.sparse as sps\n'), ((2766, 2809), 'scipy.sparse.bmat', 'sps.bmat', (['[[-mtx_m, None], [None, mtx_eye]]'], {}), '([[-mtx_m, None], [None, mtx_eye]])\n', (2774, 2809), True, 'import scipy.sparse as sps\n'), ((3641, 3669), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx_a', 'mtx_a.T'], {}), '(mtx_a, mtx_a.T)\n', (3653, 3669), False, 'from sfepy.linalg.utils import max_diff_csr\n'), ((3702, 3730), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx_a', 'mtx_a.H'], {}), '(mtx_a, mtx_a.H)\n', (3714, 3730), False, 'from sfepy.linalg.utils import max_diff_csr\n'), ((3763, 3791), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx_b', 'mtx_b.T'], {}), '(mtx_b, mtx_b.T)\n', (3775, 3791), False, 'from sfepy.linalg.utils import max_diff_csr\n'), ((3824, 3852), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx_b', 'mtx_b.H'], {}), '(mtx_b, mtx_b.H)\n', (3836, 3852), False, 'from sfepy.linalg.utils import max_diff_csr\n'), ((5145, 5172), 'numpy.linalg.norm', 'nm.linalg.norm', (['res', 'nm.inf'], {}), '(res, nm.inf)\n', (5159, 5172), True, 'import numpy as nm\n'), ((2608, 2650), 'scipy.sparse.eye', 'sps.eye', (['mtx_m.shape[0]'], {'dtype': 'mtx_m.dtype'}), '(mtx_m.shape[0], dtype=mtx_m.dtype)\n', (2615, 2650), True, 'import scipy.sparse as sps\n'), ((2953, 2968), 'sksparse.cholmod.cholesky', 'cholesky', (['mtx_m'], {}), '(mtx_m)\n', (2961, 2968), False, 'from sksparse.cholmod import cholesky\n'), ((3272, 3313), 'scipy.sparse.eye', 'sps.eye', (['mtx_l.shape[0]'], {'dtype': 'nm.float64'}), '(mtx_l.shape[0], dtype=nm.float64)\n', (3279, 3313), True, 'import scipy.sparse as sps\n'), ((3335, 3378), 'scipy.sparse.bmat', 'sps.bmat', (['[[-mtx_k, None], [None, mtx_eye]]'], {}), '([[-mtx_k, None], [None, mtx_eye]])\n', (3343, 3378), True, 'import scipy.sparse as sps\n'), ((3429, 3472), 'scipy.sparse.bmat', 'sps.bmat', (['[[mtx_d, mtx_l], [mtx_l.T, None]]'], {}), '([[mtx_d, mtx_l], [mtx_l.T, None]])\n', (3437, 3472), True, 'import scipy.sparse as sps\n'), ((3212, 3248), 'sfepy.linalg.utils.max_diff_csr', 'max_diff_csr', (['mtx_m', '(mtx_l * mtx_l.T)'], {}), '(mtx_m, mtx_l * mtx_l.T)\n', (3224, 3248), False, 'from sfepy.linalg.utils import max_diff_csr\n'), ((4380, 4407), 'numpy.linalg.norm', 'nm.linalg.norm', (['res', 'nm.inf'], {}), '(res, nm.inf)\n', (4394, 4407), True, 'import numpy as nm\n'), ((4829, 4856), 'numpy.linalg.norm', 'nm.linalg.norm', (['res', 'nm.inf'], {}), '(res, nm.inf)\n', (4843, 4856), True, 'import numpy as nm\n'), ((3073, 3091), 'numpy.ones_like', 'nm.ones_like', (['perm'], {}), '(perm)\n', (3085, 3091), True, 'import numpy as nm\n')] |
from sfepy.terms.terms import *
from sfepy.linalg import dot_sequences
class NonPenetrationTerm(Term):
r"""
:Description:
Non-penetration condition in the weak sense.
:Definition:
.. math::
\int_{\Gamma} \lambda \ul{n} \cdot \ul{v} \mbox{ , }
\int_{\Gamma} \hat\lambda \ul{n} \cdot \ul{u}
:Arguments 1:
virtual : :math:`\ul{v}`,
state : :math:`\lambda`
:Arguments 2:
state : :math:`\ul{u}`,
virtual : :math:`\hat\lambda`
"""
name = 'dw_non_penetration'
arg_types = (('virtual', 'state'),
('state', 'virtual'))
modes = ('grad', 'div')
integration = 'surface'
use_caches = {'state_in_surface_qp' : [['state']]}
def __call__(self, diff_var=None, **kwargs):
if self.mode == 'grad':
virtual, state = self.get_args(**kwargs)
ap, sg = self.get_approximation(virtual)
cache = self.get_cache('state_in_surface_qp', 0)
else:
state, virtual = self.get_args(**kwargs)
ap, sg = self.get_approximation(state)
cache = self.get_cache('state_in_surface_qp', 0)
n_fa, n_qp, dim, n_fp = ap.get_s_data_shape(self.integral,
self.region.name)
rdim, cdim = virtual.n_components, state.n_components
if diff_var is None:
shape = (n_fa, 1, rdim * n_fp, 1)
elif diff_var == self.get_arg_name('state'):
shape = (n_fa, 1, rdim * n_fp, cdim * n_fp)
else:
raise StopIteration
sd = ap.surface_data[self.region.name]
# ap corresponds to \ul{u} field.
bf = ap.get_base(sd.face_type, 0, integral=self.integral)
ebf = nm.zeros((bf.shape[0], dim, n_fp * dim),
dtype=nm.float64)
for ir in xrange(dim):
ebf[:, ir, ir*n_fp:(ir+1)*n_fp] = bf[:,0,:]
normals = sg.variable(0)
out = nm.zeros(shape, dtype=nm.float64)
lchunk = nm.arange(n_fa, dtype=nm.int32)
if diff_var is None:
vec_qp = cache('state', self, 0,
state=state, get_vector=self.get_vector)
if self.mode == 'grad':
ebf_t = nm.tile(ebf.transpose((0, 2, 1)), (n_fa, 1, 1, 1))
nl = normals * vec_qp
eftnl = dot_sequences(ebf_t, nl, use_rows=True)
sg.integrate_chunk(out, eftnl, lchunk, 1)
else:
bf_t = nm.tile(bf.transpose((0, 2, 1)), (n_fa, 1, 1, 1))
ntu = (normals * vec_qp).sum(axis=-2)[...,None]
ftntu = (bf_t * ntu)
sg.integrate_chunk(out, ftntu, lchunk, 1)
else:
ebf_t = nm.tile(ebf.transpose((0, 2, 1)), (n_fa, 1, 1, 1))
bf_ = nm.tile(bf, (n_fa, 1, 1, 1))
eftn = dot_sequences(ebf_t, normals, use_rows=True)
eftnf = eftn * bf_
if self.mode == 'grad':
sg.integrate_chunk(out, eftnf, lchunk, 1)
else:
ftntef = nm.ascontiguousarray(eftnf.transpose((0, 1, 3, 2)))
sg.integrate_chunk(out, ftntef, lchunk, 1)
yield out, lchunk, 0
| [
"sfepy.linalg.dot_sequences"
] | [((2897, 2941), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['ebf_t', 'normals'], {'use_rows': '(True)'}), '(ebf_t, normals, use_rows=True)\n', (2910, 2941), False, 'from sfepy.linalg import dot_sequences\n'), ((2393, 2432), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['ebf_t', 'nl'], {'use_rows': '(True)'}), '(ebf_t, nl, use_rows=True)\n', (2406, 2432), False, 'from sfepy.linalg import dot_sequences\n')] |
r"""
Diametrically point loaded 2-D disk with postprocessing and probes. See
:ref:`sec-primer`.
Find :math:`\ul{u}` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
= 0
\;, \quad \forall \ul{v} \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
"""
from __future__ import absolute_import
from examples.linear_elasticity.its2D_1 import *
from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson
from sfepy.postprocess.probes_vtk import Probe
import os
from six.moves import range
def stress_strain(out, pb, state, extend=False):
"""
Calculate and output strain and stress for given displacements.
"""
from sfepy.base.base import Struct
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
ev = pb.evaluate
strain = ev('ev_cauchy_strain.2.Omega(u)', mode='el_avg')
stress = ev('ev_cauchy_stress.2.Omega(Asphalt.D, u)', mode='el_avg')
out['cauchy_strain'] = Struct(name='output_data', mode='cell',
data=strain, dofs=None)
out['cauchy_stress'] = Struct(name='output_data', mode='cell',
data=stress, dofs=None)
probe = Probe(out, pb.domain.mesh, probe_view=True)
ps0 = [[0.0, 0.0, 0.0], [ 0.0, 0.0, 0.0]]
ps1 = [[75.0, 0.0, 0.0], [ 0.0, 75.0, 0.0]]
n_point = 10
labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)]
probes = []
for ip in range(len(ps0)):
p0, p1 = ps0[ip], ps1[ip]
probes.append('line%d' % ip)
probe.add_line_probe('line%d' % ip, p0, p1, n_point)
for ip, label in zip(probes, labels):
fig = plt.figure()
plt.clf()
fig.subplots_adjust(hspace=0.4)
plt.subplot(311)
pars, vals = probe(ip, 'u')
for ic in range(vals.shape[1] - 1):
plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1),
lw=1, ls='-', marker='+', ms=3)
plt.ylabel('displacements')
plt.xlabel('probe %s' % label, fontsize=8)
plt.legend(loc='best', prop=fm.FontProperties(size=10))
sym_indices = [0, 4, 1]
sym_labels = ['11', '22', '12']
plt.subplot(312)
pars, vals = probe(ip, 'cauchy_strain')
for ii, ic in enumerate(sym_indices):
plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_labels[ii],
lw=1, ls='-', marker='+', ms=3)
plt.ylabel('Cauchy strain')
plt.xlabel('probe %s' % label, fontsize=8)
plt.legend(loc='best', prop=fm.FontProperties(size=8))
plt.subplot(313)
pars, vals = probe(ip, 'cauchy_stress')
for ii, ic in enumerate(sym_indices):
plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_labels[ii],
lw=1, ls='-', marker='+', ms=3)
plt.ylabel('Cauchy stress')
plt.xlabel('probe %s' % label, fontsize=8)
plt.legend(loc='best', prop=fm.FontProperties(size=8))
opts = pb.conf.options
filename_results = os.path.join(opts.get('output_dir'),
'its2D_probe_%s.png' % ip)
fig.savefig(filename_results)
return out
materials['Asphalt'][0].update({'D' : stiffness_from_youngpoisson(2, young, poisson)})
options.update({
'post_process_hook' : 'stress_strain',
})
| [
"sfepy.postprocess.probes_vtk.Probe",
"sfepy.mechanics.matcoefs.stiffness_from_youngpoisson",
"sfepy.base.base.Struct"
] | [((1052, 1115), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'strain', 'dofs': 'None'}), "(name='output_data', mode='cell', data=strain, dofs=None)\n", (1058, 1115), False, 'from sfepy.base.base import Struct\n'), ((1177, 1240), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'stress', 'dofs': 'None'}), "(name='output_data', mode='cell', data=stress, dofs=None)\n", (1183, 1240), False, 'from sfepy.base.base import Struct\n'), ((1288, 1331), 'sfepy.postprocess.probes_vtk.Probe', 'Probe', (['out', 'pb.domain.mesh'], {'probe_view': '(True)'}), '(out, pb.domain.mesh, probe_view=True)\n', (1293, 1331), False, 'from sfepy.postprocess.probes_vtk import Probe\n'), ((1748, 1760), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1758, 1760), True, 'import matplotlib.pyplot as plt\n'), ((1769, 1778), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1776, 1778), True, 'import matplotlib.pyplot as plt\n'), ((1827, 1843), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(311)'], {}), '(311)\n', (1838, 1843), True, 'import matplotlib.pyplot as plt\n'), ((1898, 1922), 'six.moves.range', 'range', (['(vals.shape[1] - 1)'], {}), '(vals.shape[1] - 1)\n', (1903, 1922), False, 'from six.moves import range\n'), ((2054, 2081), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""displacements"""'], {}), "('displacements')\n", (2064, 2081), True, 'import matplotlib.pyplot as plt\n'), ((2090, 2132), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (["('probe %s' % label)"], {'fontsize': '(8)'}), "('probe %s' % label, fontsize=8)\n", (2100, 2132), True, 'import matplotlib.pyplot as plt\n'), ((2279, 2295), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(312)'], {}), '(312)\n', (2290, 2295), True, 'import matplotlib.pyplot as plt\n'), ((2526, 2553), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cauchy strain"""'], {}), "('Cauchy strain')\n", (2536, 2553), True, 'import matplotlib.pyplot as plt\n'), ((2562, 2604), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (["('probe %s' % label)"], {'fontsize': '(8)'}), "('probe %s' % label, fontsize=8)\n", (2572, 2604), True, 'import matplotlib.pyplot as plt\n'), ((2677, 2693), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(313)'], {}), '(313)\n', (2688, 2693), True, 'import matplotlib.pyplot as plt\n'), ((2929, 2956), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cauchy stress"""'], {}), "('Cauchy stress')\n", (2939, 2956), True, 'import matplotlib.pyplot as plt\n'), ((2965, 3007), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (["('probe %s' % label)"], {'fontsize': '(8)'}), "('probe %s' % label, fontsize=8)\n", (2975, 3007), True, 'import matplotlib.pyplot as plt\n'), ((3328, 3374), 'sfepy.mechanics.matcoefs.stiffness_from_youngpoisson', 'stiffness_from_youngpoisson', (['(2)', 'young', 'poisson'], {}), '(2, young, poisson)\n', (3355, 3374), False, 'from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson\n'), ((1936, 2028), 'matplotlib.pyplot.plot', 'plt.plot', (['pars', 'vals[:, ic]'], {'label': "('$u_{%d}$' % (ic + 1))", 'lw': '(1)', 'ls': '"""-"""', 'marker': '"""+"""', 'ms': '(3)'}), "(pars, vals[:, ic], label='$u_{%d}$' % (ic + 1), lw=1, ls='-',\n marker='+', ms=3)\n", (1944, 2028), True, 'import matplotlib.pyplot as plt\n'), ((2402, 2500), 'matplotlib.pyplot.plot', 'plt.plot', (['pars', 'vals[:, ic]'], {'label': "('$e_{%s}$' % sym_labels[ii])", 'lw': '(1)', 'ls': '"""-"""', 'marker': '"""+"""', 'ms': '(3)'}), "(pars, vals[:, ic], label='$e_{%s}$' % sym_labels[ii], lw=1, ls='-',\n marker='+', ms=3)\n", (2410, 2500), True, 'import matplotlib.pyplot as plt\n'), ((2800, 2904), 'matplotlib.pyplot.plot', 'plt.plot', (['pars', 'vals[:, ic]'], {'label': "('$\\\\sigma_{%s}$' % sym_labels[ii])", 'lw': '(1)', 'ls': '"""-"""', 'marker': '"""+"""', 'ms': '(3)'}), "(pars, vals[:, ic], label='$\\\\sigma_{%s}$' % sym_labels[ii], lw=1,\n ls='-', marker='+', ms=3)\n", (2808, 2904), True, 'import matplotlib.pyplot as plt\n'), ((2169, 2195), 'matplotlib.font_manager.FontProperties', 'fm.FontProperties', ([], {'size': '(10)'}), '(size=10)\n', (2186, 2195), True, 'import matplotlib.font_manager as fm\n'), ((2641, 2666), 'matplotlib.font_manager.FontProperties', 'fm.FontProperties', ([], {'size': '(8)'}), '(size=8)\n', (2658, 2666), True, 'import matplotlib.font_manager as fm\n'), ((3044, 3069), 'matplotlib.font_manager.FontProperties', 'fm.FontProperties', ([], {'size': '(8)'}), '(size=8)\n', (3061, 3069), True, 'import matplotlib.font_manager as fm\n')] |
"""All Sfepy imports go in this module
"""
import numpy as np
from sfepy.base.goptions import goptions
from sfepy.discrete.fem import Field
from sfepy.discrete.fem import FEDomain as Domain
from sfepy.discrete import (
FieldVariable,
Material,
Integral,
Function,
Equation,
Equations,
Problem,
)
from sfepy.terms import Term, Terms
from sfepy.discrete.conditions import Conditions, EssentialBC
from sfepy.solvers.ls import ScipyDirect
from sfepy.solvers.nls import Newton
from sfepy.discrete import Functions
from sfepy.mesh.mesh_generators import gen_block_mesh
from sfepy.base.base import output
from toolz.curried import pipe, curry, do
goptions["verbose"] = False
output.set_output(quiet=True)
def check(ids):
"""Check that the fixed displacement nodes have been isolated
Args:
ids: the isolated IDs
Returns the unchanged IDs
>>> check([1, 2, 3, 4])
Traceback (most recent call last):
...
RuntimeError: length of ids is incorrect
"""
if len(ids) != 3:
raise RuntimeError("length of ids is incorrect")
return ids
@curry
def subdomain(i_x, domain_, eps, coords, **_):
"""Find the node IDs that will be fixed
Args:
i_x: the index (either 0 or 1) depends on direction of axes
domain_: the Sfepy domain
eps: a small value
coords: the coordinates of the nodes
Returns:
the isolated node IDs
"""
def i_y():
"""Switch the index from 0 -> 1 or from 1 -> 0
"""
return (i_x + 1) % 2
return pipe(
(coords[:, i_x] > -eps) & (coords[:, i_x] < eps),
lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x,
lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x,
lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x,
lambda x: np.where(x)[0],
check,
)
def get_bc(domain, delta_x, index, cond):
"""Make a displacement boundary condition
Args:
domain: the Sfepy domain
delta_x: the mesh spacing
index: the index (either 0 or 1) depends on direction of axes
cond: the BC dictionary
Returns:
the Sfepy boundary condition
"""
return pipe(
Function("fix_points", subdomain(index, domain, delta_x * 1e-3)),
lambda x: domain.create_region(
"region_fix_points",
"vertices by fix_points",
"vertex",
functions=Functions([x]),
),
lambda x: EssentialBC("fix_points_BC", x, cond),
)
def get_bcs(domain, delta_x):
"""Get the boundary conditions
Args:
domain: the Sfepy domain
delta_x: the mesh spacing
Returns:
the boundary conditions
"""
return Conditions(
[
get_bc(domain, delta_x, 1, {"u.0": 0.0}),
get_bc(domain, delta_x, 0, {"u.1": 0.0}),
]
)
def get_material(calc_stiffness, calc_prestress):
"""Get the material
Args:
calc_stiffness: the function for calculating the stiffness tensor
calc_prestress: the function for calculating the prestress
Returns:
the material
"""
def _material_func_(_, coors, mode=None, **__):
if mode == "qp":
return dict(D=calc_stiffness(coors), stress=calc_prestress(coors))
return None
return Material("m", function=Function("material_func", _material_func_))
def get_uv(shape, delta_x):
"""Get the fields for the displacement and test function
Args:
shape: the shape of the domain
delta_x: the mesh spacing
Returns:
tuple of field variables
"""
return pipe(
np.array(shape),
lambda x: gen_block_mesh(
x * delta_x, x + 1, np.zeros_like(shape), verbose=False
),
lambda x: Domain("domain", x),
lambda x: x.create_region("region_all", "all"),
lambda x: Field.from_args("fu", np.float64, "vector", x, approx_order=2),
lambda x: (
FieldVariable("u", "unknown", x),
FieldVariable("v", "test", x, primary_var_name="u"),
),
)
# field = Field.from_args('fu', np.float64, 'vector', region_all,
# pylint: disable=no-member
# approx_order=2)
def get_terms(u_field, v_field, calc_stiffness, calc_prestress):
"""Get the terms for the equation
Args:
u_field: the displacement field
v_field: the test function field
calc_stiffness: a function to calculate the stiffness tensor
calc_prestress: a function to calculate the prestress tensor
Returns:
a tuple of terms for the equation
"""
return (
Term.new(
"dw_lin_elastic(m.D, v, u)",
Integral("i", order=4),
v_field.field.region,
m=get_material(calc_stiffness, calc_prestress),
v=v_field,
u=u_field,
),
Term.new(
"dw_lin_prestress(m.stress, v)",
Integral("i", order=4),
v_field.field.region,
m=get_material(calc_stiffness, calc_prestress),
v=v_field,
),
)
def get_nls(evaluator):
"""Get the non-linear solver
Args:
evaluator: the problem evaluator
Returns:
the non-linear solver
"""
return Newton(
{},
lin_solver=ScipyDirect({}),
fun=evaluator.eval_residual,
fun_grad=evaluator.eval_tangent_matrix,
)
def get_problem(u_field, v_field, calc_stiffness, calc_prestress, delta_x):
"""Get the problem
Args:
u_field: the displacement field
v_field: the test function field
calc_stiffness: a functioin to calcuate the stiffness tensor
calc_prestress: a function to calculate the prestress tensor
delta_x: the mesh spacing
Returns:
the Sfepy problem
"""
return pipe(
get_terms(u_field, v_field, calc_stiffness, calc_prestress),
lambda x: Equation("balance_of_forces", Terms([x[0], x[1]])),
lambda x: Problem("elasticity", equations=Equations([x])),
do(lambda x: x.time_update(ebcs=get_bcs(v_field.field.region.domain, delta_x))),
do(lambda x: x.set_solver(get_nls(x.get_evaluator()))),
)
def get_displacement(vec, shape):
"""Extract reshaped displacement from output vector
Args:
vec: the output vector obtained from problem.solve()
shape: the shape of the mesh
Returns:
reshaped displacement field
"""
return pipe(
vec.create_output_dict()["u"].data,
lambda x: np.reshape(x, (tuple(y + 1 for y in shape) + x.shape[-1:])),
)
def get_strain(problem, shape):
"""Calculate the strain field
Args:
problem: the Sfepy problem
hape: the shape of the mesh
Returns:
the reshaped strain field
"""
return get_stress_strain(problem, shape, "ev_cauchy_strain.{dim}.region_all(u)")
def get_stress(problem, shape):
"""Calculate the strain field
Args:
problem: the Sfepy problem
shape: the shape of the mesh
Returns:
the reshaped stress field
"""
return get_stress_strain(
problem, shape, "ev_cauchy_stress.{dim}.region_all(m.D, u)"
)
def get_stress_strain(problem, shape, str_):
"""Get the stress or strain field depending on the str_ argument
Args:
problem: the Sfepy problem
shape: the shape of the domain
str_: string passed to problem.evaluate to extract the stress or
strain
Returns
the reshaped stress or strain field
"""
return pipe(
np.squeeze(
problem.evaluate(
str_.format(dim=len(shape)), mode="el_avg", copy_materials=False
)
),
lambda x: np.reshape(x, (shape + x.shape[-1:])),
)
def get_data(shape, problem, vec):
"""Extract the displacement, strain and stress fields
Args:
shape: the shape of the mesh
problem: the Sfepy problem
vec: the output vector from problem.solve
Returns:
a tuple of arrays for the strain, displacement and stress fields
"""
return (
get_strain(problem, shape),
get_displacement(vec, shape),
get_stress(problem, shape),
)
def solve(calc_stiffness, calc_prestress, shape, delta_x):
"""Solve the linear elasticity problem
Args:
calc_stiffness: the function to calculate the stiffness tensor
calc_prestress: the funtion to calculate the prestress tensor
shape: the shape of the mesh
delta_x: the mesh spacing
Returns:
a tuple of arrays for the displacement, strain and stress fields
"""
return pipe(
get_uv(shape, delta_x),
lambda x: get_problem(x[0], x[1], calc_stiffness, calc_prestress, delta_x),
lambda x: get_data(shape, x, x.solve()),
)
| [
"sfepy.discrete.Equations",
"sfepy.discrete.conditions.EssentialBC",
"sfepy.solvers.ls.ScipyDirect",
"sfepy.discrete.Functions",
"sfepy.terms.Terms",
"sfepy.base.base.output.set_output",
"sfepy.discrete.Integral",
"sfepy.discrete.fem.Field.from_args",
"sfepy.discrete.FieldVariable",
"sfepy.discret... | [((698, 727), 'sfepy.base.base.output.set_output', 'output.set_output', ([], {'quiet': '(True)'}), '(quiet=True)\n', (715, 727), False, 'from sfepy.base.base import output\n'), ((3702, 3717), 'numpy.array', 'np.array', (['shape'], {}), '(shape)\n', (3710, 3717), True, 'import numpy as np\n'), ((2537, 2574), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""fix_points_BC"""', 'x', 'cond'], {}), "('fix_points_BC', x, cond)\n", (2548, 2574), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((3409, 3451), 'sfepy.discrete.Function', 'Function', (['"""material_func"""', '_material_func_'], {}), "('material_func', _material_func_)\n", (3417, 3451), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((3850, 3869), 'sfepy.discrete.fem.FEDomain', 'Domain', (['"""domain"""', 'x'], {}), "('domain', x)\n", (3856, 3869), True, 'from sfepy.discrete.fem import FEDomain as Domain\n'), ((3945, 4007), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""fu"""', 'np.float64', '"""vector"""', 'x'], {'approx_order': '(2)'}), "('fu', np.float64, 'vector', x, approx_order=2)\n", (3960, 4007), False, 'from sfepy.discrete.fem import Field\n'), ((4778, 4800), 'sfepy.discrete.Integral', 'Integral', (['"""i"""'], {'order': '(4)'}), "('i', order=4)\n", (4786, 4800), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((5028, 5050), 'sfepy.discrete.Integral', 'Integral', (['"""i"""'], {'order': '(4)'}), "('i', order=4)\n", (5036, 5050), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((5395, 5410), 'sfepy.solvers.ls.ScipyDirect', 'ScipyDirect', (['{}'], {}), '({})\n', (5406, 5410), False, 'from sfepy.solvers.ls import ScipyDirect\n'), ((7812, 7847), 'numpy.reshape', 'np.reshape', (['x', '(shape + x.shape[-1:])'], {}), '(x, shape + x.shape[-1:])\n', (7822, 7847), True, 'import numpy as np\n'), ((1890, 1901), 'numpy.where', 'np.where', (['x'], {}), '(x)\n', (1898, 1901), True, 'import numpy as np\n'), ((3785, 3805), 'numpy.zeros_like', 'np.zeros_like', (['shape'], {}), '(shape)\n', (3798, 3805), True, 'import numpy as np\n'), ((4041, 4073), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""u"""', '"""unknown"""', 'x'], {}), "('u', 'unknown', x)\n", (4054, 4073), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((4087, 4138), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""v"""', '"""test"""', 'x'], {'primary_var_name': '"""u"""'}), "('v', 'test', x, primary_var_name='u')\n", (4100, 4138), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((6038, 6057), 'sfepy.terms.Terms', 'Terms', (['[x[0], x[1]]'], {}), '([x[0], x[1]])\n', (6043, 6057), False, 'from sfepy.terms import Term, Terms\n'), ((2492, 2506), 'sfepy.discrete.Functions', 'Functions', (['[x]'], {}), '([x])\n', (2501, 2506), False, 'from sfepy.discrete import Functions\n'), ((6110, 6124), 'sfepy.discrete.Equations', 'Equations', (['[x]'], {}), '([x])\n', (6119, 6124), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n')] |
from __future__ import absolute_import
import hashlib
import numpy as nm
import warnings
import scipy.sparse as sps
import six
from six.moves import range
warnings.simplefilter('ignore', sps.SparseEfficiencyWarning)
from sfepy.base.base import output, get_default, assert_, try_imports
from sfepy.base.timing import Timer
from sfepy.solvers.solvers import LinearSolver
def solve(mtx, rhs, solver_class=None, solver_conf=None):
"""
Solve the linear system with the matrix `mtx` and the right-hand side
`rhs`.
Convenience wrapper around the linear solver classes below.
"""
solver_class = get_default(solver_class, ScipyDirect)
solver_conf = get_default(solver_conf, {})
solver = solver_class(solver_conf, mtx=mtx)
solution = solver(rhs)
return solution
def _get_cs_matrix_hash(mtx, chunk_size=100000):
def _gen_array_chunks(arr):
ii = 0
while len(arr[ii:]):
yield arr[ii:ii+chunk_size].tobytes()
ii += chunk_size
sha1 = hashlib.sha1()
for chunk in _gen_array_chunks(mtx.indptr):
sha1.update(chunk)
for chunk in _gen_array_chunks(mtx.indices):
sha1.update(chunk)
for chunk in _gen_array_chunks(mtx.data):
sha1.update(chunk)
digest = sha1.hexdigest()
return digest
def _is_new_matrix(mtx, mtx_digest, force_reuse=False):
if not isinstance(mtx, sps.csr_matrix):
return True, mtx_digest
if force_reuse:
return False, mtx_digest
id0, digest0 = mtx_digest
id1 = id(mtx)
digest1 = _get_cs_matrix_hash(mtx)
if (id1 == id0) and (digest1 == digest0):
return False, (id1, digest1)
return True, (id1, digest1)
def standard_call(call):
"""
Decorator handling argument preparation and timing for linear solvers.
"""
def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None,
i_max=None, mtx=None, status=None, context=None,
**kwargs):
timer = Timer(start=True)
conf = get_default(conf, self.conf)
mtx = get_default(mtx, self.mtx)
status = get_default(status, self.status)
context = get_default(context, self.context)
assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0])
if x0 is not None:
assert_(x0.shape[0] == rhs.shape[0])
result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status,
context=context, **kwargs)
if isinstance(result, tuple):
result, n_iter = result
else:
n_iter = -1 # Number of iterations is undefined/unavailable.
elapsed = timer.stop()
if status is not None:
status['time'] = elapsed
status['n_iter'] = n_iter
return result
return _standard_call
def petsc_call(call):
"""
Decorator handling argument preparation and timing for PETSc-based linear
solvers.
"""
def _petsc_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None,
i_max=None, mtx=None, status=None, comm=None,
context=None, **kwargs):
timer = Timer(start=True)
conf = get_default(conf, self.conf)
mtx = get_default(mtx, self.mtx)
status = get_default(status, self.status)
context = get_default(context, self.context)
comm = get_default(comm, self.comm)
mshape = mtx.size if isinstance(mtx, self.petsc.Mat) else mtx.shape
rshape = [rhs.size] if isinstance(rhs, self.petsc.Vec) else rhs.shape
assert_(mshape[0] == mshape[1] == rshape[0])
if x0 is not None:
xshape = [x0.size] if isinstance(x0, self.petsc.Vec) else x0.shape
assert_(xshape[0] == rshape[0])
result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status,
comm, context=context, **kwargs)
elapsed = timer.stop()
if status is not None:
status['time'] = elapsed
status['n_iter'] = self.ksp.getIterationNumber()
return result
return _petsc_call
class ScipyDirect(LinearSolver):
"""
Direct sparse solver from SciPy.
"""
name = 'ls.scipy_direct'
_parameters = [
('method', "{'auto', 'umfpack', 'superlu'}", 'auto', False,
'The actual solver to use.'),
('use_presolve', 'bool', False, False,
'If True, pre-factorize the matrix.'),
]
def __init__(self, conf, method=None, **kwargs):
LinearSolver.__init__(self, conf, solve=None, **kwargs)
um = self.sls = None
if method is None:
method = self.conf.method
aux = try_imports(['import scipy.linsolve as sls',
'import scipy.splinalg.dsolve as sls',
'import scipy.sparse.linalg.dsolve as sls'],
'cannot import scipy sparse direct solvers!')
if 'sls' in aux:
self.sls = aux['sls']
else:
raise ValueError('SuperLU not available!')
if method in ['auto', 'umfpack']:
aux = try_imports([
'import scipy.linsolve.umfpack as um',
'import scipy.splinalg.dsolve.umfpack as um',
'import scipy.sparse.linalg.dsolve.umfpack as um',
'import scikits.umfpack as um'])
is_umfpack = True if 'um' in aux\
and hasattr(aux['um'], 'UMFPACK_OK') else False
if method == 'umfpack' and not is_umfpack:
raise ValueError('UMFPACK not available!')
elif method == 'superlu':
is_umfpack = False
else:
raise ValueError('uknown solution method! (%s)' % method)
if is_umfpack:
self.sls.use_solver(useUmfpack=True,
assumeSortedIndices=True)
else:
self.sls.use_solver(useUmfpack=False)
@standard_call
def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None,
i_max=None, mtx=None, status=None, **kwargs):
if conf.use_presolve:
self.presolve(mtx)
if self.solve is not None:
# Matrix is already prefactorized.
return self.solve(rhs)
else:
return self.sls.spsolve(mtx, rhs)
def presolve(self, mtx):
is_new, mtx_digest = _is_new_matrix(mtx, self.mtx_digest)
if is_new:
self.solve = self.sls.factorized(mtx)
self.mtx_digest = mtx_digest
class ScipySuperLU(ScipyDirect):
"""
SuperLU - direct sparse solver from SciPy.
"""
name = 'ls.scipy_superlu'
_parameters = [
('use_presolve', 'bool', False, False,
'If True, pre-factorize the matrix.'),
]
def __init__(self, conf, **kwargs):
ScipyDirect.__init__(self, conf, method='superlu', **kwargs)
class ScipyUmfpack(ScipyDirect):
"""
UMFPACK - direct sparse solver from SciPy.
"""
name = 'ls.scipy_umfpack'
_parameters = [
('use_presolve', 'bool', False, False,
'If True, pre-factorize the matrix.'),
]
def __init__(self, conf, **kwargs):
ScipyDirect.__init__(self, conf, method='umfpack', **kwargs)
class ScipyIterative(LinearSolver):
"""
Interface to SciPy iterative solvers.
The `eps_r` tolerance is both absolute and relative - the solvers
stop when either the relative or the absolute residual is below it.
"""
name = 'ls.scipy_iterative'
_parameters = [
('method', 'str', 'cg', False,
'The actual solver to use.'),
('setup_precond', 'callable', lambda mtx, context: None, False,
"""User-supplied function for the preconditioner initialization/setup.
It is called as setup_precond(mtx, context), where mtx is the
matrix, context is a user-supplied context, and should return one
of {sparse matrix, dense matrix, LinearOperator}.
"""),
('callback', 'callable', None, False,
"""User-supplied function to call after each iteration. It is called
as callback(xk), where xk is the current solution vector, except
the gmres method, where the argument is the residual.
"""),
('i_max', 'int', 100, False,
'The maximum number of iterations.'),
('eps_a', 'float', 1e-8, False,
'The absolute tolerance for the residual.'),
('eps_r', 'float', 1e-8, False,
'The relative tolerance for the residual.'),
('*', '*', None, False,
'Additional parameters supported by the method.'),
]
# All iterative solvers in scipy.sparse.linalg pass a solution vector into
# a callback except those below, that take a residual vector.
_callbacks_res = ['gmres']
def __init__(self, conf, context=None, **kwargs):
import scipy.sparse.linalg.isolve as la
LinearSolver.__init__(self, conf, context=context, **kwargs)
try:
solver = getattr(la, self.conf.method)
except AttributeError:
output('scipy solver %s does not exist!' % self.conf.method)
output('using cg instead')
solver = la.cg
self.solver = solver
self.converged_reasons = {
0 : 'successful exit',
1 : 'number of iterations',
-1 : 'illegal input or breakdown',
}
@standard_call
def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None,
i_max=None, mtx=None, status=None, context=None, **kwargs):
solver_kwargs = self.build_solver_kwargs(conf)
eps_a = get_default(eps_a, self.conf.eps_a)
eps_r = get_default(eps_r, self.conf.eps_r)
i_max = get_default(i_max, self.conf.i_max)
setup_precond = get_default(kwargs.get('setup_precond', None),
self.conf.setup_precond)
callback = get_default(kwargs.get('callback', lambda sol: None),
self.conf.callback)
self.iter = 0
def iter_callback(sol):
self.iter += 1
msg = '%s: iteration %d' % (self.conf.name, self.iter)
if conf.verbose > 2:
if conf.method not in self._callbacks_res:
res = mtx * sol - rhs
else:
res = sol
rnorm = nm.linalg.norm(res)
msg += ': |Ax-b| = %e' % rnorm
output(msg, verbose=conf.verbose > 1)
# Call an optional user-defined callback.
callback(sol)
precond = setup_precond(mtx, context)
if conf.method == 'qmr':
prec_args = {'M1' : precond, 'M2' : precond}
else:
prec_args = {'M' : precond}
solver_kwargs.update(prec_args)
try:
sol, info = self.solver(mtx, rhs, x0=x0, atol=eps_a, tol=eps_r,
maxiter=i_max, callback=iter_callback,
**solver_kwargs)
except TypeError:
sol, info = self.solver(mtx, rhs, x0=x0, tol=eps_r,
maxiter=i_max, callback=iter_callback,
**solver_kwargs)
output('%s: %s convergence: %s (%s, %d iterations)'
% (self.conf.name, self.conf.method,
info, self.converged_reasons[nm.sign(info)], self.iter),
verbose=conf.verbose)
return sol, self.iter
class PyAMGSolver(LinearSolver):
"""
Interface to PyAMG solvers.
The `method` parameter can be one of: 'smoothed_aggregation_solver',
'ruge_stuben_solver'. The `accel` parameter specifies the Krylov
solver name, that is used as an accelerator for the multigrid solver.
"""
name = 'ls.pyamg'
_parameters = [
('method', 'str', 'smoothed_aggregation_solver', False,
'The actual solver to use.'),
('accel', 'str', None, False,
'The accelerator.'),
('callback', 'callable', None, False,
"""User-supplied function to call after each iteration. It is called
as callback(xk), where xk is the current solution vector, except
the gmres accelerator, where the argument is the residual norm.
"""),
('i_max', 'int', 100, False,
'The maximum number of iterations.'),
('eps_r', 'float', 1e-8, False,
'The relative tolerance for the residual.'),
('force_reuse', 'bool', False, False,
"""If True, skip the check whether the MG solver object corresponds
to the `mtx` argument: it is always reused."""),
('*', '*', None, False,
"""Additional parameters supported by the method. Use the 'method:'
prefix for arguments of the method construction function
(e.g. 'method:max_levels' : 5), and the 'solve:' prefix for
the subsequent solver call."""),
]
# All iterative solvers in pyamg.krylov pass a solution vector into
# a callback except those below, that take a residual vector norm.
_callbacks_res = ['gmres']
def __init__(self, conf, **kwargs):
try:
import pyamg
except ImportError:
msg = 'cannot import pyamg!'
raise ImportError(msg)
LinearSolver.__init__(self, conf, mg=None, **kwargs)
try:
solver = getattr(pyamg, self.conf.method)
except AttributeError:
output('pyamg.%s does not exist!' % self.conf.method)
output('using pyamg.smoothed_aggregation_solver instead')
solver = pyamg.smoothed_aggregation_solver
self.solver = solver
@standard_call
def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None,
i_max=None, mtx=None, status=None, **kwargs):
solver_kwargs = self.build_solver_kwargs(conf)
eps_r = get_default(eps_r, self.conf.eps_r)
i_max = get_default(i_max, self.conf.i_max)
callback = get_default(kwargs.get('callback', lambda sol: None),
self.conf.callback)
self.iter = 0
def iter_callback(sol):
self.iter += 1
msg = '%s: iteration %d' % (self.conf.name, self.iter)
if conf.verbose > 2:
if conf.accel not in self._callbacks_res:
res = mtx * sol - rhs
else:
res = sol
rnorm = nm.linalg.norm(res)
msg += ': |Ax-b| = %e' % rnorm
output(msg, verbose=conf.verbose > 1)
# Call an optional user-defined callback.
callback(sol)
is_new, mtx_digest = _is_new_matrix(mtx, self.mtx_digest,
force_reuse=conf.force_reuse)
if is_new or (self.mg is None):
_kwargs = {key[7:] : val
for key, val in six.iteritems(solver_kwargs)
if key.startswith('method:')}
self.mg = self.solver(mtx, **_kwargs)
self.mtx_digest = mtx_digest
_kwargs = {key[6:] : val
for key, val in six.iteritems(solver_kwargs)
if key.startswith('solve:')}
sol = self.mg.solve(rhs, x0=x0, accel=conf.accel, tol=eps_r,
maxiter=i_max, callback=iter_callback,
**_kwargs)
return sol, self.iter
class PyAMGKrylovSolver(LinearSolver):
"""
Interface to PyAMG Krylov solvers.
"""
name = 'ls.pyamg_krylov'
_parameters = [
('method', 'str', 'cg', False,
'The actual solver to use.'),
('setup_precond', 'callable', lambda mtx, context: None, False,
"""User-supplied function for the preconditioner initialization/setup.
It is called as setup_precond(mtx, context), where mtx is the
matrix, context is a user-supplied context, and should return one
of {sparse matrix, dense matrix, LinearOperator}.
"""),
('callback', 'callable', None, False,
"""User-supplied function to call after each iteration. It is called
as callback(xk), where xk is the current solution vector, except
the gmres method, where the argument is the residual norm.
"""),
('i_max', 'int', 100, False,
'The maximum number of iterations.'),
('eps_r', 'float', 1e-8, False,
'The relative tolerance for the residual.'),
('*', '*', None, False,
'Additional parameters supported by the method.'),
]
# All iterative solvers in pyamg.krylov pass a solution vector into
# a callback except those below, that take a residual vector norm.
_callbacks_res = ['gmres']
def __init__(self, conf, context=None, **kwargs):
try:
import pyamg.krylov as krylov
except ImportError:
msg = 'cannot import pyamg.krylov!'
raise ImportError(msg)
LinearSolver.__init__(self, conf, mg=None,
context=context, **kwargs)
try:
solver = getattr(krylov, self.conf.method)
except AttributeError:
output('pyamg.krylov.%s does not exist!' % self.conf.method)
raise
self.solver = solver
self.converged_reasons = {
0 : 'successful exit',
1 : 'number of iterations',
-1 : 'illegal input or breakdown',
}
@standard_call
def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None,
i_max=None, mtx=None, status=None, context=None, **kwargs):
solver_kwargs = self.build_solver_kwargs(conf)
eps_r = get_default(eps_r, self.conf.eps_r)
i_max = get_default(i_max, self.conf.i_max)
setup_precond = get_default(kwargs.get('setup_precond', None),
self.conf.setup_precond)
callback = get_default(kwargs.get('callback', lambda sol: None),
self.conf.callback)
self.iter = 0
def iter_callback(sol):
self.iter += 1
msg = '%s: iteration %d' % (self.conf.name, self.iter)
if conf.verbose > 2:
if conf.method not in self._callbacks_res:
res = mtx * sol - rhs
else:
res = sol
rnorm = nm.linalg.norm(res)
msg += ': |Ax-b| = %e' % rnorm
output(msg, verbose=conf.verbose > 1)
# Call an optional user-defined callback.
callback(sol)
precond = setup_precond(mtx, context)
sol, info = self.solver(mtx, rhs, x0=x0, tol=eps_r, maxiter=i_max,
M=precond, callback=iter_callback,
**solver_kwargs)
output('%s: %s convergence: %s (%s, %d iterations)'
% (self.conf.name, self.conf.method,
info, self.converged_reasons[nm.sign(info)], self.iter),
verbose=conf.verbose)
return sol, self.iter
class PETScKrylovSolver(LinearSolver):
"""
PETSc Krylov subspace solver.
The solver supports parallel use with a given MPI communicator (see `comm`
argument of :func:`PETScKrylovSolver.__init__()`) and allows passing in
PETSc matrices and vectors. Returns a (global) PETSc solution vector
instead of a (local) numpy array, when given a PETSc right-hand side
vector.
The solver and preconditioner types are set upon the solver object
creation. Tolerances can be overridden when called by passing a `conf`
object.
Convergence is reached when `rnorm < max(eps_r * rnorm_0, eps_a)`,
where, in PETSc, `rnorm` is by default the norm of *preconditioned*
residual.
"""
name = 'ls.petsc'
_parameters = [
('method', 'str', 'cg', False,
'The actual solver to use.'),
('setup_precond', 'callable', None, False,
"""User-supplied function for the preconditioner initialization/setup.
It is called as setup_precond(mtx, context), where mtx is the
matrix, context is a user-supplied context, and should return an
object with `setUp(self, pc)` and `apply(self, pc, x, y)` methods.
Has precedence over the `precond`/`sub_precond` parameters.
"""),
('precond', 'str', 'icc', False,
'The preconditioner.'),
('sub_precond', 'str', 'none', False,
'The preconditioner for matrix blocks (in parallel runs).'),
('precond_side', "{'left', 'right', 'symmetric', None}", None, False,
'The preconditioner side.'),
('i_max', 'int', 100, False,
'The maximum number of iterations.'),
('eps_a', 'float', 1e-8, False,
'The absolute tolerance for the residual.'),
('eps_r', 'float', 1e-8, False,
'The relative tolerance for the residual.'),
('eps_d', 'float', 1e5, False,
'The divergence tolerance for the residual.'),
('force_reuse', 'bool', False, False,
"""If True, skip the check whether the KSP solver object corresponds
to the `mtx` argument: it is always reused."""),
('*', '*', None, False,
"""Additional parameters supported by the method. Can be used to pass
all PETSc options supported by :func:`petsc.Options()`."""),
]
_precond_sides = {None : None, 'left' : 0, 'right' : 1, 'symmetric' : 2}
def __init__(self, conf, comm=None, context=None, **kwargs):
if comm is None:
from sfepy.parallel.parallel import init_petsc_args; init_petsc_args
from petsc4py import PETSc as petsc
converged_reasons = {}
for key, val in six.iteritems(petsc.KSP.ConvergedReason.__dict__):
if isinstance(val, int):
converged_reasons[val] = key
LinearSolver.__init__(self, conf, petsc=petsc, comm=comm,
converged_reasons=converged_reasons,
fields=None, ksp=None, pmtx=None,
context=context, **kwargs)
def set_field_split(self, field_ranges, comm=None):
"""
Setup local PETSc ranges for fields to be used with 'fieldsplit'
preconditioner.
This function must be called before solving the linear system.
"""
comm = get_default(comm, self.comm)
self.fields = []
for key, rng in six.iteritems(field_ranges):
if isinstance(rng, slice):
rng = rng.start, rng.stop
size = rng[1] - rng[0]
field_is = self.petsc.IS().createStride(size, first=rng[0], step=1,
comm=comm)
self.fields.append((key, field_is))
def create_ksp(self, options=None, comm=None):
optDB = self.petsc.Options()
optDB['sub_pc_type'] = self.conf.sub_precond
if options is not None:
for key, val in six.iteritems(options):
optDB[key] = val
ksp = self.petsc.KSP()
ksp.create(comm)
ksp.setType(self.conf.method)
pc = ksp.getPC()
if self.conf.setup_precond is None:
pc.setType(self.conf.precond)
else:
pc.setType(pc.Type.PYTHON)
ksp.setFromOptions()
if (pc.type == 'fieldsplit'):
if self.fields is not None:
pc.setFieldSplitIS(*self.fields)
else:
msg = 'PETScKrylovSolver.set_field_split() has to be called!'
raise ValueError(msg)
side = self._precond_sides[self.conf.precond_side]
if side is not None:
ksp.setPCSide(side)
return ksp
def create_petsc_matrix(self, mtx, comm=None):
if isinstance(mtx, self.petsc.Mat):
pmtx = mtx
else:
mtx = sps.csr_matrix(mtx)
pmtx = self.petsc.Mat()
pmtx.createAIJ(mtx.shape, csr=(mtx.indptr, mtx.indices, mtx.data),
comm=comm)
return pmtx
@petsc_call
def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None,
i_max=None, mtx=None, status=None, comm=None, context=None,
**kwargs):
solver_kwargs = self.build_solver_kwargs(conf)
eps_a = get_default(eps_a, self.conf.eps_a)
eps_r = get_default(eps_r, self.conf.eps_r)
i_max = get_default(i_max, self.conf.i_max)
eps_d = self.conf.eps_d
is_new, mtx_digest = _is_new_matrix(mtx, self.mtx_digest,
force_reuse=conf.force_reuse)
if (not is_new) and self.ksp is not None:
ksp = self.ksp
pmtx = self.pmtx
else:
pmtx = self.create_petsc_matrix(mtx, comm=comm)
ksp = self.create_ksp(options=solver_kwargs, comm=comm)
ksp.setOperators(pmtx)
ksp.setTolerances(atol=eps_a, rtol=eps_r, divtol=eps_d,
max_it=i_max)
setup_precond = self.conf.setup_precond
if setup_precond is not None:
ksp.pc.setPythonContext(setup_precond(mtx, context))
ksp.setFromOptions()
self.mtx_digest = mtx_digest
self.ksp = ksp
self.pmtx = pmtx
if isinstance(rhs, self.petsc.Vec):
prhs = rhs
else:
prhs = pmtx.getVecLeft()
prhs[...] = rhs
if x0 is not None:
if isinstance(x0, self.petsc.Vec):
psol = x0
else:
psol = pmtx.getVecRight()
psol[...] = x0
ksp.setInitialGuessNonzero(True)
else:
psol = pmtx.getVecRight()
ksp.setInitialGuessNonzero(False)
ksp.solve(prhs, psol)
output('%s(%s, %s/proc) convergence: %s (%s, %d iterations)'
% (ksp.getType(), ksp.getPC().getType(), self.conf.sub_precond,
ksp.reason, self.converged_reasons[ksp.reason],
ksp.getIterationNumber()),
verbose=conf.verbose)
if isinstance(rhs, self.petsc.Vec):
sol = psol
else:
sol = psol[...].copy()
return sol
class MUMPSSolver(LinearSolver):
"""
Interface to MUMPS solver.
"""
name = 'ls.mumps'
_parameters = [
('use_presolve', 'bool', False, False,
'If True, pre-factorize the matrix.'),
('memory_relaxation', 'int', 20, False,
'The percentage increase in the estimated working space.'),
]
def __init__(self, conf, **kwargs):
import sfepy.solvers.ls_mumps as mumps
self.mumps_ls = None
if not mumps.use_mpi:
raise AttributeError('No mpi4py found! Required by MUMPS solver.')
mumps.load_mumps_libraries() # try to load MUMPS libraries
LinearSolver.__init__(self, conf, mumps=mumps, mumps_ls=None,
mumps_presolved=False, **kwargs)
@standard_call
def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None,
i_max=None, mtx=None, status=None, **kwargs):
if not self.mumps_presolved:
self.presolve(mtx, presolve_flag=conf.use_presolve)
out = rhs.copy()
self.mumps_ls.set_rhs(out)
self.mumps_ls(3) # solve
return out
def presolve(self, mtx, presolve_flag=False):
is_new, mtx_digest = _is_new_matrix(mtx, self.mtx_digest)
if not isinstance(mtx, sps.coo_matrix):
mtx = mtx.tocoo()
if self.mumps_ls is None:
system = 'complex' if mtx.dtype.name.startswith('complex')\
else 'real'
is_sym = self.mumps.coo_is_symmetric(mtx)
mem_relax = self.conf.memory_relaxation
self.mumps_ls = self.mumps.MumpsSolver(system=system,
is_sym=is_sym,
mem_relax=mem_relax)
if is_new:
if self.conf.verbose:
self.mumps_ls.set_verbose()
self.mumps_ls.set_mtx_centralized(mtx)
self.mumps_ls(4) # analyze + factorize
if presolve_flag:
self.mumps_presolved = True
self.mtx_digest = mtx_digest
def __del__(self):
if self.mumps_ls is not None:
del(self.mumps_ls)
class MUMPSParallelSolver(LinearSolver):
"""
Interface to MUMPS parallel solver.
"""
name = 'ls.mumps_par'
_parameters = [
('memory_relaxation', 'int', 20, False,
'The percentage increase in the estimated working space.'),
]
def __init__(self, conf, **kwargs):
import multiprocessing
import sfepy.solvers.ls_mumps as mumps
mumps.load_mumps_libraries() # try to load MUMPS libraries
LinearSolver.__init__(self, conf, mumps=mumps, mumps_ls=None,
number_of_cpu=multiprocessing.cpu_count(),
mumps_presolved=False, **kwargs)
@standard_call
def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None,
i_max=None, mtx=None, status=None, **kwargs):
from mpi4py import MPI
import sys
from sfepy import data_dir
import os.path as op
from tempfile import gettempdir
def tmpfile(fname):
return op.join(gettempdir(), fname)
if not isinstance(mtx, sps.coo_matrix):
mtx = mtx.tocoo()
is_sym = self.mumps.coo_is_symmetric(mtx)
rr, cc, data = mtx.row + 1, mtx.col + 1, mtx.data
if is_sym:
idxs = nm.where(cc >= rr)[0] # upper triangular matrix
rr, cc, data = rr[idxs], cc[idxs], data[idxs]
n = mtx.shape[0]
nz = rr.shape[0]
flags = nm.memmap(tmpfile('vals_flags.array'), dtype='int32',
mode='w+', shape=(4,))
flags[0] = n
flags[1] = 1 if data.dtype.name.startswith('complex') else 0
flags[2] = int(is_sym)
flags[3] = int(self.conf.verbose)
idxs = nm.memmap(tmpfile('idxs.array'), dtype='int32',
mode='w+', shape=(2, nz))
idxs[0, :] = rr
idxs[1, :] = cc
dtype = {0: 'float64', 1: 'complex128'}[flags[1]]
vals_mtx = nm.memmap(tmpfile('vals_mtx.array'), dtype=dtype,
mode='w+', shape=(nz,))
vals_rhs = nm.memmap(tmpfile('vals_rhs.array'), dtype=dtype,
mode='w+', shape=(n,))
vals_mtx[:] = data
vals_rhs[:] = rhs
mumps_call = op.join(data_dir, 'sfepy', 'solvers',
'ls_mumps_parallel.py')
comm = MPI.COMM_SELF.Spawn(sys.executable, args=[mumps_call],
maxprocs=self.number_of_cpu)
comm.Disconnect()
out = nm.memmap(tmpfile('vals_x.array'), dtype=dtype, mode='r')
return out
class SchurMumps(MUMPSSolver):
r"""
Mumps Schur complement solver.
"""
name = 'ls.schur_mumps'
_parameters = MUMPSSolver._parameters + [
('schur_variables', 'list', None, True,
'The list of Schur variables.'),
]
@standard_call
def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None,
i_max=None, mtx=None, status=None, **kwargs):
import scipy.linalg as sla
if not isinstance(mtx, sps.coo_matrix):
mtx = mtx.tocoo()
system = 'complex' if mtx.dtype.name.startswith('complex') else 'real'
self.mumps_ls = self.mumps.MumpsSolver(system=system)
if self.conf.verbose:
self.mumps_ls.set_verbose()
schur_list = []
for schur_var in conf.schur_variables:
slc = self.context.equations.variables.adi.indx[schur_var]
schur_list.append(nm.arange(slc.start, slc.stop, slc.step, dtype='i'))
self.mumps_ls.set_mtx_centralized(mtx)
out = rhs.copy()
self.mumps_ls.set_rhs(out)
S, y2 = self.mumps_ls.get_schur(nm.hstack(schur_list))
x2 = sla.solve(S.T, y2) # solve the dense Schur system using scipy.linalg
return self.mumps_ls.expand_schur(x2)
class MultiProblem(ScipyDirect):
r"""
Conjugate multiple problems.
Allows to define conjugate multiple problems.
"""
name = 'ls.cm_pb'
_parameters = ScipyDirect._parameters + [
('others', 'list', None, True,
'The list of auxiliary problem definition files.'),
('coupling_variables', 'list', None, True,
'The list of coupling variables.'),
]
def __init__(self, conf, context=None, **kwargs):
ScipyDirect.__init__(self, conf, context=context, **kwargs)
def init_subproblems(self, conf, **kwargs):
from sfepy.discrete.state import State
from sfepy.discrete import Problem
from sfepy.base.conf import ProblemConf, get_standard_keywords
from scipy.spatial import cKDTree as KDTree
# init subproblems
problem = self.context
pb_vars = problem.get_variables()
# get "master" DofInfo and last index
pb_adi_indx = problem.equations.variables.adi.indx
self.adi_indx = pb_adi_indx.copy()
last_indx = -1
for ii in six.itervalues(self.adi_indx):
last_indx = nm.max([last_indx, ii.stop])
# coupling variables
self.cvars_to_pb = {}
for jj in conf.coupling_variables:
self.cvars_to_pb[jj] = [None, None]
if jj in pb_vars.names:
if pb_vars[jj].dual_var_name is not None:
self.cvars_to_pb[jj][0] = -1
else:
self.cvars_to_pb[jj][1] = -1
# init subproblems
self.subpb = []
required, other = get_standard_keywords()
master_prefix = output.get_output_prefix()
for ii, ifname in enumerate(conf.others):
sub_prefix = master_prefix[:-1] + '-sub%d:' % (ii + 1)
output.set_output_prefix(sub_prefix)
kwargs['master_problem'] = problem
confi = ProblemConf.from_file(ifname, required, other,
define_args=kwargs)
pbi = Problem.from_conf(confi, init_equations=True)
sti = State(pbi.equations.variables)
pbi.equations.set_data(None, ignore_unknown=True)
pbi.time_update()
pbi.update_materials()
sti.apply_ebc()
pbi_vars = pbi.get_variables()
output.set_output_prefix(master_prefix)
self.subpb.append([pbi, sti, None])
# append "slave" DofInfo
for jj in pbi_vars.names:
if not(pbi_vars[jj].is_state()):
continue
didx = pbi.equations.variables.adi.indx[jj]
ndof = didx.stop - didx.start
if jj in self.adi_indx:
if ndof != \
(self.adi_indx[jj].stop - self.adi_indx[jj].start):
raise ValueError('DOFs do not match!')
else:
self.adi_indx.update({
jj: slice(last_indx, last_indx + ndof, None)})
last_indx += ndof
for jj in conf.coupling_variables:
if jj in pbi_vars.names:
if pbi_vars[jj].dual_var_name is not None:
self.cvars_to_pb[jj][0] = ii
else:
self.cvars_to_pb[jj][1] = ii
self.subpb.append([problem, None, None])
self.cvars_to_pb_map = {}
for varname, pbs in six.iteritems(self.cvars_to_pb):
# match field nodes
coors = []
for ii in pbs:
pbi = self.subpb[ii][0]
pbi_vars = pbi.get_variables()
fcoors = pbi_vars[varname].field.coors
dc = nm.abs(nm.max(fcoors, axis=0)\
- nm.min(fcoors, axis=0))
ax = nm.where(dc > 1e-9)[0]
coors.append(fcoors[:,ax])
if len(coors[0]) != len(coors[1]):
raise ValueError('number of nodes does not match!')
kdtree = KDTree(coors[0])
map_12 = kdtree.query(coors[1])[1]
pbi1 = self.subpb[pbs[0]][0]
pbi1_vars = pbi1.get_variables()
eq_map_1 = pbi1_vars[varname].eq_map
pbi2 = self.subpb[pbs[1]][0]
pbi2_vars = pbi2.get_variables()
eq_map_2 = pbi2_vars[varname].eq_map
dpn = eq_map_2.dpn
nnd = map_12.shape[0]
map_12_nd = nm.zeros((nnd * dpn,), dtype=nm.int32)
if dpn > 1:
for ii in range(dpn):
map_12_nd[ii::dpn] = map_12 * dpn + ii
else:
map_12_nd = map_12
idx = nm.where(eq_map_2.eq >= 0)[0]
self.cvars_to_pb_map[varname] = eq_map_1.eq[map_12[idx]]
def sparse_submat(self, Ad, Ar, Ac, gr, gc, S):
"""
A[gr,gc] = S
"""
if type(gr) is slice:
gr = nm.arange(gr.start, gr.stop)
if type(gc) is slice:
gc = nm.arange(gc.start, gc.stop)
for ii, lrow in enumerate(S):
m = lrow.indices.shape[0]
idxrow = nm.ones((m,), dtype=nm.int32) * gr[ii]
Ar = nm.hstack([Ar, idxrow])
Ac = nm.hstack([Ac, gc[lrow.indices]])
Ad = nm.hstack([Ad, lrow.data])
return Ad, Ar, Ac
@standard_call
def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None,
i_max=None, mtx=None, status=None, **kwargs):
self.init_subproblems(self.conf, **kwargs)
max_indx = 0
hst = nm.hstack
for ii in six.itervalues(self.adi_indx):
max_indx = nm.max([max_indx, ii.stop])
new_rhs = nm.zeros((max_indx,), dtype=rhs.dtype)
new_rhs[:rhs.shape[0]] = rhs
# copy "master" matrices
pbi = self.subpb[-1][0]
adi_indxi = pbi.equations.variables.adi.indx
mtxc = mtx.tocsc()
aux_data = nm.array([], dtype=mtxc.dtype)
aux_rows = nm.array([], dtype=nm.int32)
aux_cols = nm.array([], dtype=nm.int32)
for jk, jv in six.iteritems(adi_indxi):
if jk in self.cvars_to_pb:
if not(self.cvars_to_pb[jk][0] == -1):
continue
gjv = self.adi_indx[jk]
ii = gjv.start
for jj in nm.arange(jv.start, jv.stop):
ptr = mtxc.indptr[jj]
nn = mtxc.indptr[jj + 1] - ptr
sl = slice(ptr, ptr + nn, None)
aux_data = hst([aux_data, mtxc.data[sl]])
aux_rows = hst([aux_rows, mtxc.indices[sl]])
aux_cols = hst([aux_cols, nm.ones((nn,), dtype=nm.int32) * ii])
ii += 1
# copy "slave" (sub)matricies
mtxs = []
for kk, (pbi, sti0, _) in enumerate(self.subpb[:-1]):
x0i = sti0.get_reduced()
evi = pbi.get_evaluator()
mtxi = evi.eval_tangent_matrix(x0i, mtx=pbi.mtx_a)
rhsi = evi.eval_residual(x0i)
mtxs.append(mtxi)
adi_indxi = pbi.equations.variables.adi.indx
for ik, iv in six.iteritems(adi_indxi):
if ik in self.cvars_to_pb:
if not(self.cvars_to_pb[ik][0] == kk):
continue
giv = self.adi_indx[ik]
for jk, jv in six.iteritems(adi_indxi):
gjv = self.adi_indx[jk]
if jk in self.cvars_to_pb:
if not(self.cvars_to_pb[jk][0] == kk):
continue
aux_data, aux_rows, aux_cols =\
self.sparse_submat(aux_data, aux_rows, aux_cols,
giv, gjv, mtxi[iv, jv])
new_rhs[giv] = rhsi[iv]
mtxs.append(mtx)
# copy "coupling" (sub)matricies
for varname, pbs in six.iteritems(self.cvars_to_pb):
idx = pbs[1]
pbi = self.subpb[idx][0]
mtxi = mtxs[idx]
gjv = self.adi_indx[varname]
jv = pbi.equations.variables.adi.indx[varname]
adi_indxi = pbi.equations.variables.adi.indx
for ik, iv in six.iteritems(adi_indxi):
if ik == varname:
continue
giv = self.adi_indx[ik]
aux_mtx = mtxi[iv,:].tocsc()
for ll, jj in enumerate(nm.arange(jv.start, jv.stop)):
ptr = aux_mtx.indptr[jj]
nn = aux_mtx.indptr[jj + 1] - ptr
if nn < 1:
continue
sl = slice(ptr, ptr + nn, None)
aux_data = hst([aux_data, aux_mtx.data[sl]])
aux_rows = hst([aux_rows, aux_mtx.indices[sl] + giv.start])
jjr = gjv.start + self.cvars_to_pb_map[varname][ll]
aux_cols = hst([aux_cols,
nm.ones((nn,), dtype=nm.int32) * jjr])
# create new matrix
new_mtx = sps.coo_matrix((aux_data, (aux_rows, aux_cols))).tocsr()
res0 = ScipyDirect.__call__(self, new_rhs, mtx=new_mtx)
res = []
for kk, (pbi, sti0, _) in enumerate(self.subpb):
adi_indxi = pbi.equations.variables.adi.indx
max_indx = 0
for ii in six.itervalues(adi_indxi):
max_indx = nm.max([max_indx, ii.stop])
resi = nm.zeros((max_indx,), dtype=res0.dtype)
for ik, iv in six.iteritems(adi_indxi):
giv = self.adi_indx[ik]
if ik in self.cvars_to_pb:
if pbi is self.subpb[self.cvars_to_pb[ik][1]][0]:
giv = self.cvars_to_pb_map[ik] + giv.start
resi[iv] = res0[giv]
if sti0 is not None:
sti = sti0.copy()
sti.set_reduced(-resi)
pbi.setup_default_output()
pbi.save_state(pbi.get_output_name(), sti)
self.subpb[kk][-1] = sti
res.append(resi)
return res[-1]
| [
"sfepy.solvers.solvers.LinearSolver.__init__",
"sfepy.solvers.ls_mumps.load_mumps_libraries",
"sfepy.base.conf.get_standard_keywords",
"sfepy.base.base.output",
"sfepy.base.base.assert_",
"sfepy.discrete.Problem.from_conf",
"sfepy.base.base.get_default",
"sfepy.base.base.output.set_output_prefix",
"... | [((158, 218), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'sps.SparseEfficiencyWarning'], {}), "('ignore', sps.SparseEfficiencyWarning)\n", (179, 218), False, 'import warnings\n'), ((617, 655), 'sfepy.base.base.get_default', 'get_default', (['solver_class', 'ScipyDirect'], {}), '(solver_class, ScipyDirect)\n', (628, 655), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((674, 702), 'sfepy.base.base.get_default', 'get_default', (['solver_conf', '{}'], {}), '(solver_conf, {})\n', (685, 702), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((1017, 1031), 'hashlib.sha1', 'hashlib.sha1', ([], {}), '()\n', (1029, 1031), False, 'import hashlib\n'), ((2013, 2030), 'sfepy.base.timing.Timer', 'Timer', ([], {'start': '(True)'}), '(start=True)\n', (2018, 2030), False, 'from sfepy.base.timing import Timer\n'), ((2047, 2075), 'sfepy.base.base.get_default', 'get_default', (['conf', 'self.conf'], {}), '(conf, self.conf)\n', (2058, 2075), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((2090, 2116), 'sfepy.base.base.get_default', 'get_default', (['mtx', 'self.mtx'], {}), '(mtx, self.mtx)\n', (2101, 2116), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((2134, 2166), 'sfepy.base.base.get_default', 'get_default', (['status', 'self.status'], {}), '(status, self.status)\n', (2145, 2166), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((2185, 2219), 'sfepy.base.base.get_default', 'get_default', (['context', 'self.context'], {}), '(context, self.context)\n', (2196, 2219), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((2229, 2282), 'sfepy.base.base.assert_', 'assert_', (['(mtx.shape[0] == mtx.shape[1] == rhs.shape[0])'], {}), '(mtx.shape[0] == mtx.shape[1] == rhs.shape[0])\n', (2236, 2282), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((3168, 3185), 'sfepy.base.timing.Timer', 'Timer', ([], {'start': '(True)'}), '(start=True)\n', (3173, 3185), False, 'from sfepy.base.timing import Timer\n'), ((3202, 3230), 'sfepy.base.base.get_default', 'get_default', (['conf', 'self.conf'], {}), '(conf, self.conf)\n', (3213, 3230), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((3245, 3271), 'sfepy.base.base.get_default', 'get_default', (['mtx', 'self.mtx'], {}), '(mtx, self.mtx)\n', (3256, 3271), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((3289, 3321), 'sfepy.base.base.get_default', 'get_default', (['status', 'self.status'], {}), '(status, self.status)\n', (3300, 3321), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((3340, 3374), 'sfepy.base.base.get_default', 'get_default', (['context', 'self.context'], {}), '(context, self.context)\n', (3351, 3374), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((3390, 3418), 'sfepy.base.base.get_default', 'get_default', (['comm', 'self.comm'], {}), '(comm, self.comm)\n', (3401, 3418), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((3583, 3627), 'sfepy.base.base.assert_', 'assert_', (['(mshape[0] == mshape[1] == rshape[0])'], {}), '(mshape[0] == mshape[1] == rshape[0])\n', (3590, 3627), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((4527, 4582), 'sfepy.solvers.solvers.LinearSolver.__init__', 'LinearSolver.__init__', (['self', 'conf'], {'solve': 'None'}), '(self, conf, solve=None, **kwargs)\n', (4548, 4582), False, 'from sfepy.solvers.solvers import LinearSolver\n'), ((4692, 4878), 'sfepy.base.base.try_imports', 'try_imports', (["['import scipy.linsolve as sls', 'import scipy.splinalg.dsolve as sls',\n 'import scipy.sparse.linalg.dsolve as sls']", '"""cannot import scipy sparse direct solvers!"""'], {}), "(['import scipy.linsolve as sls',\n 'import scipy.splinalg.dsolve as sls',\n 'import scipy.sparse.linalg.dsolve as sls'],\n 'cannot import scipy sparse direct solvers!')\n", (4703, 4878), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((8965, 9025), 'sfepy.solvers.solvers.LinearSolver.__init__', 'LinearSolver.__init__', (['self', 'conf'], {'context': 'context'}), '(self, conf, context=context, **kwargs)\n', (8986, 9025), False, 'from sfepy.solvers.solvers import LinearSolver\n'), ((9698, 9733), 'sfepy.base.base.get_default', 'get_default', (['eps_a', 'self.conf.eps_a'], {}), '(eps_a, self.conf.eps_a)\n', (9709, 9733), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((9750, 9785), 'sfepy.base.base.get_default', 'get_default', (['eps_r', 'self.conf.eps_r'], {}), '(eps_r, self.conf.eps_r)\n', (9761, 9785), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((9802, 9837), 'sfepy.base.base.get_default', 'get_default', (['i_max', 'self.conf.i_max'], {}), '(i_max, self.conf.i_max)\n', (9813, 9837), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((13416, 13468), 'sfepy.solvers.solvers.LinearSolver.__init__', 'LinearSolver.__init__', (['self', 'conf'], {'mg': 'None'}), '(self, conf, mg=None, **kwargs)\n', (13437, 13468), False, 'from sfepy.solvers.solvers import LinearSolver\n'), ((14015, 14050), 'sfepy.base.base.get_default', 'get_default', (['eps_r', 'self.conf.eps_r'], {}), '(eps_r, self.conf.eps_r)\n', (14026, 14050), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((14067, 14102), 'sfepy.base.base.get_default', 'get_default', (['i_max', 'self.conf.i_max'], {}), '(i_max, self.conf.i_max)\n', (14078, 14102), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((17141, 17210), 'sfepy.solvers.solvers.LinearSolver.__init__', 'LinearSolver.__init__', (['self', 'conf'], {'mg': 'None', 'context': 'context'}), '(self, conf, mg=None, context=context, **kwargs)\n', (17162, 17210), False, 'from sfepy.solvers.solvers import LinearSolver\n'), ((17870, 17905), 'sfepy.base.base.get_default', 'get_default', (['eps_r', 'self.conf.eps_r'], {}), '(eps_r, self.conf.eps_r)\n', (17881, 17905), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((17922, 17957), 'sfepy.base.base.get_default', 'get_default', (['i_max', 'self.conf.i_max'], {}), '(i_max, self.conf.i_max)\n', (17933, 17957), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((21959, 22008), 'six.iteritems', 'six.iteritems', (['petsc.KSP.ConvergedReason.__dict__'], {}), '(petsc.KSP.ConvergedReason.__dict__)\n', (21972, 22008), False, 'import six\n'), ((22101, 22265), 'sfepy.solvers.solvers.LinearSolver.__init__', 'LinearSolver.__init__', (['self', 'conf'], {'petsc': 'petsc', 'comm': 'comm', 'converged_reasons': 'converged_reasons', 'fields': 'None', 'ksp': 'None', 'pmtx': 'None', 'context': 'context'}), '(self, conf, petsc=petsc, comm=comm, converged_reasons\n =converged_reasons, fields=None, ksp=None, pmtx=None, context=context,\n **kwargs)\n', (22122, 22265), False, 'from sfepy.solvers.solvers import LinearSolver\n'), ((22612, 22640), 'sfepy.base.base.get_default', 'get_default', (['comm', 'self.comm'], {}), '(comm, self.comm)\n', (22623, 22640), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((22691, 22718), 'six.iteritems', 'six.iteritems', (['field_ranges'], {}), '(field_ranges)\n', (22704, 22718), False, 'import six\n'), ((24595, 24630), 'sfepy.base.base.get_default', 'get_default', (['eps_a', 'self.conf.eps_a'], {}), '(eps_a, self.conf.eps_a)\n', (24606, 24630), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((24647, 24682), 'sfepy.base.base.get_default', 'get_default', (['eps_r', 'self.conf.eps_r'], {}), '(eps_r, self.conf.eps_r)\n', (24658, 24682), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((24699, 24734), 'sfepy.base.base.get_default', 'get_default', (['i_max', 'self.conf.i_max'], {}), '(i_max, self.conf.i_max)\n', (24710, 24734), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((27131, 27159), 'sfepy.solvers.ls_mumps.load_mumps_libraries', 'mumps.load_mumps_libraries', ([], {}), '()\n', (27157, 27159), True, 'import sfepy.solvers.ls_mumps as mumps\n'), ((27200, 27298), 'sfepy.solvers.solvers.LinearSolver.__init__', 'LinearSolver.__init__', (['self', 'conf'], {'mumps': 'mumps', 'mumps_ls': 'None', 'mumps_presolved': '(False)'}), '(self, conf, mumps=mumps, mumps_ls=None,\n mumps_presolved=False, **kwargs)\n', (27221, 27298), False, 'from sfepy.solvers.solvers import LinearSolver\n'), ((29142, 29170), 'sfepy.solvers.ls_mumps.load_mumps_libraries', 'mumps.load_mumps_libraries', ([], {}), '()\n', (29168, 29170), True, 'import sfepy.solvers.ls_mumps as mumps\n'), ((31001, 31062), 'os.path.join', 'op.join', (['data_dir', '"""sfepy"""', '"""solvers"""', '"""ls_mumps_parallel.py"""'], {}), "(data_dir, 'sfepy', 'solvers', 'ls_mumps_parallel.py')\n", (31008, 31062), True, 'import os.path as op\n'), ((31107, 31195), 'mpi4py.MPI.COMM_SELF.Spawn', 'MPI.COMM_SELF.Spawn', (['sys.executable'], {'args': '[mumps_call]', 'maxprocs': 'self.number_of_cpu'}), '(sys.executable, args=[mumps_call], maxprocs=self.\n number_of_cpu)\n', (31126, 31195), False, 'from mpi4py import MPI\n'), ((32494, 32512), 'scipy.linalg.solve', 'sla.solve', (['S.T', 'y2'], {}), '(S.T, y2)\n', (32503, 32512), True, 'import scipy.linalg as sla\n'), ((33693, 33722), 'six.itervalues', 'six.itervalues', (['self.adi_indx'], {}), '(self.adi_indx)\n', (33707, 33722), False, 'import six\n'), ((34221, 34244), 'sfepy.base.conf.get_standard_keywords', 'get_standard_keywords', ([], {}), '()\n', (34242, 34244), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((34269, 34295), 'sfepy.base.base.output.get_output_prefix', 'output.get_output_prefix', ([], {}), '()\n', (34293, 34295), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((36093, 36124), 'six.iteritems', 'six.iteritems', (['self.cvars_to_pb'], {}), '(self.cvars_to_pb)\n', (36106, 36124), False, 'import six\n'), ((38261, 38290), 'six.itervalues', 'six.itervalues', (['self.adi_indx'], {}), '(self.adi_indx)\n', (38275, 38290), False, 'import six\n'), ((38362, 38400), 'numpy.zeros', 'nm.zeros', (['(max_indx,)'], {'dtype': 'rhs.dtype'}), '((max_indx,), dtype=rhs.dtype)\n', (38370, 38400), True, 'import numpy as nm\n'), ((38603, 38633), 'numpy.array', 'nm.array', (['[]'], {'dtype': 'mtxc.dtype'}), '([], dtype=mtxc.dtype)\n', (38611, 38633), True, 'import numpy as nm\n'), ((38653, 38681), 'numpy.array', 'nm.array', (['[]'], {'dtype': 'nm.int32'}), '([], dtype=nm.int32)\n', (38661, 38681), True, 'import numpy as nm\n'), ((38701, 38729), 'numpy.array', 'nm.array', (['[]'], {'dtype': 'nm.int32'}), '([], dtype=nm.int32)\n', (38709, 38729), True, 'import numpy as nm\n'), ((38753, 38777), 'six.iteritems', 'six.iteritems', (['adi_indxi'], {}), '(adi_indxi)\n', (38766, 38777), False, 'import six\n'), ((40565, 40596), 'six.iteritems', 'six.iteritems', (['self.cvars_to_pb'], {}), '(self.cvars_to_pb)\n', (40578, 40596), False, 'import six\n'), ((2322, 2358), 'sfepy.base.base.assert_', 'assert_', (['(x0.shape[0] == rhs.shape[0])'], {}), '(x0.shape[0] == rhs.shape[0])\n', (2329, 2358), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((3746, 3777), 'sfepy.base.base.assert_', 'assert_', (['(xshape[0] == rshape[0])'], {}), '(xshape[0] == rshape[0])\n', (3753, 3777), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((5136, 5329), 'sfepy.base.base.try_imports', 'try_imports', (["['import scipy.linsolve.umfpack as um',\n 'import scipy.splinalg.dsolve.umfpack as um',\n 'import scipy.sparse.linalg.dsolve.umfpack as um',\n 'import scikits.umfpack as um']"], {}), "(['import scipy.linsolve.umfpack as um',\n 'import scipy.splinalg.dsolve.umfpack as um',\n 'import scipy.sparse.linalg.dsolve.umfpack as um',\n 'import scikits.umfpack as um'])\n", (5147, 5329), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((10535, 10572), 'sfepy.base.base.output', 'output', (['msg'], {'verbose': '(conf.verbose > 1)'}), '(msg, verbose=conf.verbose > 1)\n', (10541, 10572), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((14667, 14704), 'sfepy.base.base.output', 'output', (['msg'], {'verbose': '(conf.verbose > 1)'}), '(msg, verbose=conf.verbose > 1)\n', (14673, 14704), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((18655, 18692), 'sfepy.base.base.output', 'output', (['msg'], {'verbose': '(conf.verbose > 1)'}), '(msg, verbose=conf.verbose > 1)\n', (18661, 18692), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((23231, 23253), 'six.iteritems', 'six.iteritems', (['options'], {}), '(options)\n', (23244, 23253), False, 'import six\n'), ((24134, 24153), 'scipy.sparse.csr_matrix', 'sps.csr_matrix', (['mtx'], {}), '(mtx)\n', (24148, 24153), True, 'import scipy.sparse as sps\n'), ((32458, 32479), 'numpy.hstack', 'nm.hstack', (['schur_list'], {}), '(schur_list)\n', (32467, 32479), True, 'import numpy as nm\n'), ((33748, 33776), 'numpy.max', 'nm.max', (['[last_indx, ii.stop]'], {}), '([last_indx, ii.stop])\n', (33754, 33776), True, 'import numpy as nm\n'), ((34425, 34461), 'sfepy.base.base.output.set_output_prefix', 'output.set_output_prefix', (['sub_prefix'], {}), '(sub_prefix)\n', (34449, 34461), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((34529, 34595), 'sfepy.base.conf.ProblemConf.from_file', 'ProblemConf.from_file', (['ifname', 'required', 'other'], {'define_args': 'kwargs'}), '(ifname, required, other, define_args=kwargs)\n', (34550, 34595), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((34656, 34701), 'sfepy.discrete.Problem.from_conf', 'Problem.from_conf', (['confi'], {'init_equations': '(True)'}), '(confi, init_equations=True)\n', (34673, 34701), False, 'from sfepy.discrete import Problem\n'), ((34720, 34750), 'sfepy.discrete.state.State', 'State', (['pbi.equations.variables'], {}), '(pbi.equations.variables)\n', (34725, 34750), False, 'from sfepy.discrete.state import State\n'), ((34961, 35000), 'sfepy.base.base.output.set_output_prefix', 'output.set_output_prefix', (['master_prefix'], {}), '(master_prefix)\n', (34985, 35000), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((36681, 36697), 'scipy.spatial.cKDTree', 'KDTree', (['coors[0]'], {}), '(coors[0])\n', (36687, 36697), True, 'from scipy.spatial import cKDTree as KDTree\n'), ((37108, 37146), 'numpy.zeros', 'nm.zeros', (['(nnd * dpn,)'], {'dtype': 'nm.int32'}), '((nnd * dpn,), dtype=nm.int32)\n', (37116, 37146), True, 'import numpy as nm\n'), ((37585, 37613), 'numpy.arange', 'nm.arange', (['gr.start', 'gr.stop'], {}), '(gr.start, gr.stop)\n', (37594, 37613), True, 'import numpy as nm\n'), ((37662, 37690), 'numpy.arange', 'nm.arange', (['gc.start', 'gc.stop'], {}), '(gc.start, gc.stop)\n', (37671, 37690), True, 'import numpy as nm\n'), ((37845, 37868), 'numpy.hstack', 'nm.hstack', (['[Ar, idxrow]'], {}), '([Ar, idxrow])\n', (37854, 37868), True, 'import numpy as nm\n'), ((37886, 37919), 'numpy.hstack', 'nm.hstack', (['[Ac, gc[lrow.indices]]'], {}), '([Ac, gc[lrow.indices]])\n', (37895, 37919), True, 'import numpy as nm\n'), ((37937, 37963), 'numpy.hstack', 'nm.hstack', (['[Ad, lrow.data]'], {}), '([Ad, lrow.data])\n', (37946, 37963), True, 'import numpy as nm\n'), ((38315, 38342), 'numpy.max', 'nm.max', (['[max_indx, ii.stop]'], {}), '([max_indx, ii.stop])\n', (38321, 38342), True, 'import numpy as nm\n'), ((38988, 39016), 'numpy.arange', 'nm.arange', (['jv.start', 'jv.stop'], {}), '(jv.start, jv.stop)\n', (38997, 39016), True, 'import numpy as nm\n'), ((39787, 39811), 'six.iteritems', 'six.iteritems', (['adi_indxi'], {}), '(adi_indxi)\n', (39800, 39811), False, 'import six\n'), ((40872, 40896), 'six.iteritems', 'six.iteritems', (['adi_indxi'], {}), '(adi_indxi)\n', (40885, 40896), False, 'import six\n'), ((42019, 42044), 'six.itervalues', 'six.itervalues', (['adi_indxi'], {}), '(adi_indxi)\n', (42033, 42044), False, 'import six\n'), ((42121, 42160), 'numpy.zeros', 'nm.zeros', (['(max_indx,)'], {'dtype': 'res0.dtype'}), '((max_indx,), dtype=res0.dtype)\n', (42129, 42160), True, 'import numpy as nm\n'), ((42187, 42211), 'six.iteritems', 'six.iteritems', (['adi_indxi'], {}), '(adi_indxi)\n', (42200, 42211), False, 'import six\n'), ((9134, 9194), 'sfepy.base.base.output', 'output', (["('scipy solver %s does not exist!' % self.conf.method)"], {}), "('scipy solver %s does not exist!' % self.conf.method)\n", (9140, 9194), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((9207, 9233), 'sfepy.base.base.output', 'output', (['"""using cg instead"""'], {}), "('using cg instead')\n", (9213, 9233), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((10456, 10475), 'numpy.linalg.norm', 'nm.linalg.norm', (['res'], {}), '(res)\n', (10470, 10475), True, 'import numpy as nm\n'), ((13580, 13633), 'sfepy.base.base.output', 'output', (["('pyamg.%s does not exist!' % self.conf.method)"], {}), "('pyamg.%s does not exist!' % self.conf.method)\n", (13586, 13633), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((13646, 13703), 'sfepy.base.base.output', 'output', (['"""using pyamg.smoothed_aggregation_solver instead"""'], {}), "('using pyamg.smoothed_aggregation_solver instead')\n", (13652, 13703), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((14588, 14607), 'numpy.linalg.norm', 'nm.linalg.norm', (['res'], {}), '(res)\n', (14602, 14607), True, 'import numpy as nm\n'), ((15285, 15313), 'six.iteritems', 'six.iteritems', (['solver_kwargs'], {}), '(solver_kwargs)\n', (15298, 15313), False, 'import six\n'), ((17353, 17413), 'sfepy.base.base.output', 'output', (["('pyamg.krylov.%s does not exist!' % self.conf.method)"], {}), "('pyamg.krylov.%s does not exist!' % self.conf.method)\n", (17359, 17413), False, 'from sfepy.base.base import output, get_default, assert_, try_imports\n'), ((18576, 18595), 'numpy.linalg.norm', 'nm.linalg.norm', (['res'], {}), '(res)\n', (18590, 18595), True, 'import numpy as nm\n'), ((29317, 29344), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (29342, 29344), False, 'import multiprocessing\n'), ((29774, 29786), 'tempfile.gettempdir', 'gettempdir', ([], {}), '()\n', (29784, 29786), False, 'from tempfile import gettempdir\n'), ((30021, 30039), 'numpy.where', 'nm.where', (['(cc >= rr)'], {}), '(cc >= rr)\n', (30029, 30039), True, 'import numpy as nm\n'), ((32256, 32307), 'numpy.arange', 'nm.arange', (['slc.start', 'slc.stop', 'slc.step'], {'dtype': '"""i"""'}), "(slc.start, slc.stop, slc.step, dtype='i')\n", (32265, 32307), True, 'import numpy as nm\n'), ((37197, 37207), 'six.moves.range', 'range', (['dpn'], {}), '(dpn)\n', (37202, 37207), False, 'from six.moves import range\n'), ((37340, 37366), 'numpy.where', 'nm.where', (['(eq_map_2.eq >= 0)'], {}), '(eq_map_2.eq >= 0)\n', (37348, 37366), True, 'import numpy as nm\n'), ((37789, 37818), 'numpy.ones', 'nm.ones', (['(m,)'], {'dtype': 'nm.int32'}), '((m,), dtype=nm.int32)\n', (37796, 37818), True, 'import numpy as nm\n'), ((40019, 40043), 'six.iteritems', 'six.iteritems', (['adi_indxi'], {}), '(adi_indxi)\n', (40032, 40043), False, 'import six\n'), ((41718, 41766), 'scipy.sparse.coo_matrix', 'sps.coo_matrix', (['(aux_data, (aux_rows, aux_cols))'], {}), '((aux_data, (aux_rows, aux_cols)))\n', (41732, 41766), True, 'import scipy.sparse as sps\n'), ((42073, 42100), 'numpy.max', 'nm.max', (['[max_indx, ii.stop]'], {}), '([max_indx, ii.stop])\n', (42079, 42100), True, 'import numpy as nm\n'), ((15043, 15071), 'six.iteritems', 'six.iteritems', (['solver_kwargs'], {}), '(solver_kwargs)\n', (15056, 15071), False, 'import six\n'), ((36477, 36497), 'numpy.where', 'nm.where', (['(dc > 1e-09)'], {}), '(dc > 1e-09)\n', (36485, 36497), True, 'import numpy as nm\n'), ((41087, 41115), 'numpy.arange', 'nm.arange', (['jv.start', 'jv.stop'], {}), '(jv.start, jv.stop)\n', (41096, 41115), True, 'import numpy as nm\n'), ((11484, 11497), 'numpy.sign', 'nm.sign', (['info'], {}), '(info)\n', (11491, 11497), True, 'import numpy as nm\n'), ((19173, 19186), 'numpy.sign', 'nm.sign', (['info'], {}), '(info)\n', (19180, 19186), True, 'import numpy as nm\n'), ((36378, 36400), 'numpy.max', 'nm.max', (['fcoors'], {'axis': '(0)'}), '(fcoors, axis=0)\n', (36384, 36400), True, 'import numpy as nm\n'), ((36432, 36454), 'numpy.min', 'nm.min', (['fcoors'], {'axis': '(0)'}), '(fcoors, axis=0)\n', (36438, 36454), True, 'import numpy as nm\n'), ((39312, 39342), 'numpy.ones', 'nm.ones', (['(nn,)'], {'dtype': 'nm.int32'}), '((nn,), dtype=nm.int32)\n', (39319, 39342), True, 'import numpy as nm\n'), ((41632, 41662), 'numpy.ones', 'nm.ones', (['(nn,)'], {'dtype': 'nm.int32'}), '((nn,), dtype=nm.int32)\n', (41639, 41662), True, 'import numpy as nm\n')] |
# coding=utf8
from __future__ import absolute_import
import os
from sfepy import data_dir
import six
filename_meshes = ['/meshes/3d/cylinder.mesh',
'/meshes/3d/cylinder.vtk',
'/meshes/various_formats/small2d.mesh',
'/meshes/various_formats/small2d.vtk',
'/meshes/various_formats/octahedron.node',
'/meshes/various_formats/comsol_tri.txt',
'/meshes/various_formats/abaqus_hex.inp',
'/meshes/various_formats/abaqus_tet.inp',
'/meshes/various_formats/abaqus_quad.inp',
'/meshes/various_formats/abaqus_tri.inp',
'/meshes/various_formats/abaqus_quad_tri.inp',
'/meshes/various_formats/hex4.mesh3d',
'/meshes/various_formats/tetra8.mesh3d',
'/meshes/various_formats/cube.bdf',
'/meshes/various_formats/med_2d_tri_quad.med',
'/meshes/various_formats/med_3d_tet_hex.med',
'/meshes/various_formats/msh_tri.msh',
'/meshes/various_formats/msh_tetra.msh',
'/meshes/various_formats/xyz_quad.xyz',
'/meshes/various_formats/xyz_tet.xyz']
filename_meshes = [data_dir + name for name in filename_meshes]
def mesh_hook(mesh, mode):
"""
Define a mesh programmatically.
"""
if mode == 'read':
nodes = [[0, 0], [1, 0], [1, 1], [0, 1]]
nod_ids = [0, 0, 1, 1]
conns = [[[0, 1, 2], [0, 2, 3]]]
mat_ids = [[0, 1]]
descs = ['2_3']
mesh._set_io_data(nodes, nod_ids, conns, mat_ids, descs)
elif mode == 'write':
pass
from sfepy.discrete.fem.meshio import UserMeshIO
filename_meshes.extend([mesh_hook, UserMeshIO(mesh_hook)])
same = [(0, 1), (2, 3)]
import os.path as op
from sfepy.base.base import assert_
from sfepy.base.testing import TestCommon
class Test(TestCommon):
"""Write test names explicitely to impose a given order of evaluation."""
tests = ['test_read_meshes', 'test_compare_same_meshes',
'test_read_dimension', 'test_write_read_meshes',
'test_hdf5_meshio']
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_read_meshes(self):
"""Try to read all listed meshes."""
from sfepy.discrete.fem import Mesh
conf_dir = op.dirname(__file__)
meshes = {}
for ii, filename in enumerate(filename_meshes):
self.report('%d. mesh: %s' % (ii + 1, filename))
mesh = Mesh.from_file(filename, prefix_dir=conf_dir)
assert_(mesh.dim == (mesh.coors.shape[1]))
assert_(mesh.n_nod == (mesh.coors.shape[0]))
assert_(mesh.n_nod == (mesh.cmesh.vertex_groups.shape[0]))
assert_(mesh.n_el == mesh.cmesh.num[mesh.cmesh.tdim])
self.report('read ok')
meshes[filename] = mesh
self.meshes = meshes
return True
def _compare_meshes(self, mesh0, mesh1):
import numpy as nm
oks = []
ok0 = (mesh0.dim == mesh1.dim)
if not ok0:
self.report('dimension failed!')
oks.append(ok0)
ok0 = mesh0.n_nod == mesh1.n_nod
if not ok0:
self.report('number of nodes failed!')
oks.append(ok0)
ok0 = mesh0.n_el == mesh1.n_el
if not ok0:
self.report('number of elements failed!')
oks.append(ok0)
ok0 = mesh0.descs == mesh1.descs
if not ok0:
self.report('element types failed!')
oks.append(ok0)
ok0 = nm.allclose(mesh0.coors, mesh1.coors)
if not ok0:
self.report('nodes failed!')
oks.append(ok0)
ok0 = nm.all(mesh0.cmesh.vertex_groups == mesh1.cmesh.vertex_groups)
if not ok0:
self.report('node groups failed!')
oks.append(ok0)
ok0 = nm.all(mesh0.cmesh.cell_groups == mesh1.cmesh.cell_groups)
if not ok0:
self.report('material ids failed!')
oks.append(ok0)
ok0 = (nm.all(mesh0.cmesh.get_cell_conn().indices ==
mesh1.cmesh.get_cell_conn().indices) and
nm.all(mesh0.cmesh.get_cell_conn().offsets ==
mesh1.cmesh.get_cell_conn().offsets))
if not ok0:
self.report('connectivities failed!')
oks.append(ok0)
return oks
def test_compare_same_meshes(self):
"""
Compare same meshes in various formats.
"""
oks = []
for i0, i1 in same:
name0 = filename_meshes[i0]
name1 = filename_meshes[i1]
self.report('comparing meshes from "%s" and "%s"' % (name0, name1))
mesh0 = self.meshes[name0]
mesh1 = self.meshes[name1]
oks = self._compare_meshes(mesh0, mesh1)
return sum(oks) == len(oks)
def test_read_dimension(self):
from sfepy.discrete.fem import MeshIO
meshes = {data_dir + '/meshes/various_formats/small2d.mesh' : 2,
data_dir + '/meshes/various_formats/small2d.vtk' : 2,
data_dir + '/meshes/various_formats/small3d.mesh' : 3}
ok = True
conf_dir = op.dirname(__file__)
for filename, adim in six.iteritems(meshes):
self.report('mesh: %s, dimension %d' % (filename, adim))
io = MeshIO.any_from_filename(filename, prefix_dir=conf_dir)
dim = io.read_dimension()
if dim != adim:
self.report('read dimension %d -> failed' % dim)
ok = False
else:
self.report('read dimension %d -> ok' % dim)
return ok
def test_write_read_meshes(self):
"""
Try to write and then read all supported formats.
"""
from sfepy.discrete.fem import Mesh
from sfepy.discrete.fem.meshio import (supported_formats,
supported_capabilities)
conf_dir = op.dirname(__file__)
mesh0 = Mesh.from_file(data_dir
+ '/meshes/various_formats/small3d.mesh',
prefix_dir=conf_dir)
oks = []
for suffix, format_ in six.iteritems(supported_formats):
if isinstance(format_, tuple) or (format_ == 'xyz'):
continue
if 'w' not in supported_capabilities[format_]: continue
filename = op.join(self.options.out_dir, 'test_mesh_wr' + suffix)
self.report('%s format: %s' % (suffix, filename))
mesh0.write(filename, io='auto')
mesh1 = Mesh.from_file(filename)
oks.extend(self._compare_meshes(mesh0, mesh1))
return sum(oks) == len(oks)
def test_hdf5_meshio(self):
try:
from igakit import igalib
except ImportError:
self.report('hdf5_meshio not-tested (missing igalib module)!')
return True
import tempfile
import numpy as nm
import scipy.sparse as sps
from sfepy.discrete.fem.meshio import HDF5MeshIO
from sfepy.base.base import Struct
from sfepy.base.ioutils import Cached, Uncached, SoftLink, \
DataSoftLink
from sfepy.discrete.iga.domain import IGDomain
from sfepy.discrete.iga.domain_generators import gen_patch_block_domain
from sfepy.solvers.ts import TimeStepper
from sfepy.discrete.fem import Mesh
conf_dir = op.dirname(__file__)
mesh0 = Mesh.from_file(data_dir +
'/meshes/various_formats/small3d.mesh',
prefix_dir=conf_dir)
shape = [4, 4, 4]
dims = [5, 5, 5]
centre = [0, 0, 0]
degrees = [2, 2, 2]
nurbs, bmesh, regions = gen_patch_block_domain(dims, shape, centre,
degrees,
cp_mode='greville',
name='iga')
ig_domain = IGDomain('iga', nurbs, bmesh, regions=regions)
int_ar = nm.arange(4)
data = {
'list': range(4),
'mesh1': mesh0,
'mesh2': mesh0,
'mesh3': Uncached(mesh0),
'mesh4': SoftLink('/step0/__cdata/data/data/mesh2'),
'mesh5': DataSoftLink('Mesh','/step0/__cdata/data/data/mesh1/data'),
'mesh6': DataSoftLink('Mesh','/step0/__cdata/data/data/mesh2/data',
mesh0),
'mesh7': DataSoftLink('Mesh','/step0/__cdata/data/data/mesh1/data',
True),
'iga' : ig_domain,
'cached1': Cached(1),
'cached2': Cached(int_ar),
'cached3': Cached(int_ar),
'types': ( True, False, None ),
'tuple': ('first string', 'druhý UTF8 řetězec'),
'struct': Struct(
double=nm.arange(4, dtype=float),
int=nm.array([2,3,4,7]),
sparse=sps.csr_matrix(nm.array([1,0,0,5]).
reshape((2,2)))
)
}
with tempfile.NamedTemporaryFile(suffix='.h5', delete=False) as fil:
io = HDF5MeshIO(fil.name)
ts = TimeStepper(0,1.,0.1, 10)
io.write(fil.name, mesh0, {
'cdata' : Struct(
mode='custom',
data=data,
unpack_markers=False
)
}, ts=ts)
ts.advance()
mesh = io.read()
data['problem_mesh'] = DataSoftLink('Mesh', '/mesh', mesh)
io.write(fil.name, mesh0, {
'cdata' : Struct(
mode='custom',
data=data,
unpack_markers=True
)
}, ts=ts)
cache = {'/mesh': mesh }
fout = io.read_data(0, cache=cache)
fout2 = io.read_data(1, cache=cache )
out = fout['cdata']
out2 = fout2['cdata']
assert_(out['mesh7'] is out2['mesh7'],
'These two meshes should be in fact the same object')
assert_(out['mesh6'] is out2['mesh6'],
'These two meshes should be in fact the same object')
assert_(out['mesh5'] is not out2['mesh5'],
'These two meshes shouldn''t be in fact the same object')
assert_(out['mesh1'] is out['mesh2'],
'These two meshes should be in fact the same object')
assert_(out['mesh1'] is out['mesh2'],
'These two meshes should be in fact the same object')
assert_(out['mesh4'] is out['mesh2'],
'These two meshes should be in fact the same object')
assert_(out['mesh5'] is not out['mesh2'],
'These two meshes shouldn''t be in fact the same object')
assert_(out['mesh6'] is out['mesh2'],
'These two meshes should be in fact the same object')
assert_(out['mesh7'] is not out['mesh2'],
'These two meshes shouldn''t be in fact the same object')
assert_(out['mesh3'] is not out['mesh2'],
'These two meshes should be different objects')
assert_(out['cached2'] is out['cached3'],
'These two array should be the same object')
assert_(out2['problem_mesh'] is mesh,
'These two meshes should be the same objects')
assert_(self._compare_meshes(out['mesh1'], mesh0),
'Failed to restore mesh')
assert_(self._compare_meshes(out['mesh3'], mesh0),
'Failed to restore mesh')
assert_((out['struct'].sparse == data['struct'].sparse).todense()
.all(), 'Sparse matrix restore failed')
ts.advance()
io.write(fil.name, mesh0, {
'cdata' : Struct(
mode='custom',
data=[
DataSoftLink('Mesh',
'/step0/__cdata/data/data/mesh1/data',
mesh0),
mesh0
]
)
}, ts=ts)
out3 = io.read_data(2)['cdata']
assert_(out3[0] is out3[1])
os.remove(fil.name)
#this property is not restored
del data['iga'].nurbs.nurbs
#not supporting comparison
del data['iga']._bnf
del out2['iga']._bnf
#restoration of this property fails
del data['iga'].vertex_set_bcs
del out2['iga'].vertex_set_bcs
#these soflink has no information how to unpack, so it must be
#done manually
data['mesh4'] = mesh0
data['mesh5'] = mesh0
data['mesh7'] = mesh0
for key, val in six.iteritems(out2):
self.report('comparing:', key)
self.assert_equal(val, data[key])
return True
| [
"sfepy.discrete.fem.meshio.HDF5MeshIO",
"sfepy.base.ioutils.Uncached",
"sfepy.solvers.ts.TimeStepper",
"sfepy.base.ioutils.Cached",
"sfepy.discrete.fem.Mesh.from_file",
"sfepy.discrete.iga.domain_generators.gen_patch_block_domain",
"sfepy.base.base.Struct",
"sfepy.base.base.assert_",
"sfepy.base.iou... | [((1816, 1837), 'sfepy.discrete.fem.meshio.UserMeshIO', 'UserMeshIO', (['mesh_hook'], {}), '(mesh_hook)\n', (1826, 1837), False, 'from sfepy.discrete.fem.meshio import UserMeshIO\n'), ((2467, 2487), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (2477, 2487), True, 'import os.path as op\n'), ((3708, 3745), 'numpy.allclose', 'nm.allclose', (['mesh0.coors', 'mesh1.coors'], {}), '(mesh0.coors, mesh1.coors)\n', (3719, 3745), True, 'import numpy as nm\n'), ((3846, 3908), 'numpy.all', 'nm.all', (['(mesh0.cmesh.vertex_groups == mesh1.cmesh.vertex_groups)'], {}), '(mesh0.cmesh.vertex_groups == mesh1.cmesh.vertex_groups)\n', (3852, 3908), True, 'import numpy as nm\n'), ((4015, 4073), 'numpy.all', 'nm.all', (['(mesh0.cmesh.cell_groups == mesh1.cmesh.cell_groups)'], {}), '(mesh0.cmesh.cell_groups == mesh1.cmesh.cell_groups)\n', (4021, 4073), True, 'import numpy as nm\n'), ((5352, 5372), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (5362, 5372), True, 'import os.path as op\n'), ((5403, 5424), 'six.iteritems', 'six.iteritems', (['meshes'], {}), '(meshes)\n', (5416, 5424), False, 'import six\n'), ((6146, 6166), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (6156, 6166), True, 'import os.path as op\n'), ((6183, 6273), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (["(data_dir + '/meshes/various_formats/small3d.mesh')"], {'prefix_dir': 'conf_dir'}), "(data_dir + '/meshes/various_formats/small3d.mesh',\n prefix_dir=conf_dir)\n", (6197, 6273), False, 'from sfepy.discrete.fem import Mesh\n'), ((6381, 6413), 'six.iteritems', 'six.iteritems', (['supported_formats'], {}), '(supported_formats)\n', (6394, 6413), False, 'import six\n'), ((7669, 7689), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (7679, 7689), True, 'import os.path as op\n'), ((7706, 7796), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (["(data_dir + '/meshes/various_formats/small3d.mesh')"], {'prefix_dir': 'conf_dir'}), "(data_dir + '/meshes/various_formats/small3d.mesh',\n prefix_dir=conf_dir)\n", (7720, 7796), False, 'from sfepy.discrete.fem import Mesh\n'), ((7995, 8083), 'sfepy.discrete.iga.domain_generators.gen_patch_block_domain', 'gen_patch_block_domain', (['dims', 'shape', 'centre', 'degrees'], {'cp_mode': '"""greville"""', 'name': '"""iga"""'}), "(dims, shape, centre, degrees, cp_mode='greville',\n name='iga')\n", (8017, 8083), False, 'from sfepy.discrete.iga.domain_generators import gen_patch_block_domain\n'), ((8265, 8311), 'sfepy.discrete.iga.domain.IGDomain', 'IGDomain', (['"""iga"""', 'nurbs', 'bmesh'], {'regions': 'regions'}), "('iga', nurbs, bmesh, regions=regions)\n", (8273, 8311), False, 'from sfepy.discrete.iga.domain import IGDomain\n'), ((8330, 8342), 'numpy.arange', 'nm.arange', (['(4)'], {}), '(4)\n', (8339, 8342), True, 'import numpy as nm\n'), ((12640, 12659), 'os.remove', 'os.remove', (['fil.name'], {}), '(fil.name)\n', (12649, 12659), False, 'import os\n'), ((13163, 13182), 'six.iteritems', 'six.iteritems', (['out2'], {}), '(out2)\n', (13176, 13182), False, 'import six\n'), ((2644, 2689), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['filename'], {'prefix_dir': 'conf_dir'}), '(filename, prefix_dir=conf_dir)\n', (2658, 2689), False, 'from sfepy.discrete.fem import Mesh\n'), ((2703, 2743), 'sfepy.base.base.assert_', 'assert_', (['(mesh.dim == mesh.coors.shape[1])'], {}), '(mesh.dim == mesh.coors.shape[1])\n', (2710, 2743), False, 'from sfepy.base.base import assert_\n'), ((2758, 2800), 'sfepy.base.base.assert_', 'assert_', (['(mesh.n_nod == mesh.coors.shape[0])'], {}), '(mesh.n_nod == mesh.coors.shape[0])\n', (2765, 2800), False, 'from sfepy.base.base import assert_\n'), ((2815, 2871), 'sfepy.base.base.assert_', 'assert_', (['(mesh.n_nod == mesh.cmesh.vertex_groups.shape[0])'], {}), '(mesh.n_nod == mesh.cmesh.vertex_groups.shape[0])\n', (2822, 2871), False, 'from sfepy.base.base import assert_\n'), ((2886, 2939), 'sfepy.base.base.assert_', 'assert_', (['(mesh.n_el == mesh.cmesh.num[mesh.cmesh.tdim])'], {}), '(mesh.n_el == mesh.cmesh.num[mesh.cmesh.tdim])\n', (2893, 2939), False, 'from sfepy.base.base import assert_\n'), ((5512, 5567), 'sfepy.discrete.fem.MeshIO.any_from_filename', 'MeshIO.any_from_filename', (['filename'], {'prefix_dir': 'conf_dir'}), '(filename, prefix_dir=conf_dir)\n', (5536, 5567), False, 'from sfepy.discrete.fem import MeshIO\n'), ((6597, 6651), 'os.path.join', 'op.join', (['self.options.out_dir', "('test_mesh_wr' + suffix)"], {}), "(self.options.out_dir, 'test_mesh_wr' + suffix)\n", (6604, 6651), True, 'import os.path as op\n'), ((6780, 6804), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['filename'], {}), '(filename)\n', (6794, 6804), False, 'from sfepy.discrete.fem import Mesh\n'), ((8468, 8483), 'sfepy.base.ioutils.Uncached', 'Uncached', (['mesh0'], {}), '(mesh0)\n', (8476, 8483), False, 'from sfepy.base.ioutils import Cached, Uncached, SoftLink, DataSoftLink\n'), ((8506, 8548), 'sfepy.base.ioutils.SoftLink', 'SoftLink', (['"""/step0/__cdata/data/data/mesh2"""'], {}), "('/step0/__cdata/data/data/mesh2')\n", (8514, 8548), False, 'from sfepy.base.ioutils import Cached, Uncached, SoftLink, DataSoftLink\n'), ((8571, 8630), 'sfepy.base.ioutils.DataSoftLink', 'DataSoftLink', (['"""Mesh"""', '"""/step0/__cdata/data/data/mesh1/data"""'], {}), "('Mesh', '/step0/__cdata/data/data/mesh1/data')\n", (8583, 8630), False, 'from sfepy.base.ioutils import Cached, Uncached, SoftLink, DataSoftLink\n'), ((8652, 8718), 'sfepy.base.ioutils.DataSoftLink', 'DataSoftLink', (['"""Mesh"""', '"""/step0/__cdata/data/data/mesh2/data"""', 'mesh0'], {}), "('Mesh', '/step0/__cdata/data/data/mesh2/data', mesh0)\n", (8664, 8718), False, 'from sfepy.base.ioutils import Cached, Uncached, SoftLink, DataSoftLink\n'), ((8756, 8821), 'sfepy.base.ioutils.DataSoftLink', 'DataSoftLink', (['"""Mesh"""', '"""/step0/__cdata/data/data/mesh1/data"""', '(True)'], {}), "('Mesh', '/step0/__cdata/data/data/mesh1/data', True)\n", (8768, 8821), False, 'from sfepy.base.ioutils import Cached, Uncached, SoftLink, DataSoftLink\n'), ((8892, 8901), 'sfepy.base.ioutils.Cached', 'Cached', (['(1)'], {}), '(1)\n', (8898, 8901), False, 'from sfepy.base.ioutils import Cached, Uncached, SoftLink, DataSoftLink\n'), ((8926, 8940), 'sfepy.base.ioutils.Cached', 'Cached', (['int_ar'], {}), '(int_ar)\n', (8932, 8940), False, 'from sfepy.base.ioutils import Cached, Uncached, SoftLink, DataSoftLink\n'), ((8965, 8979), 'sfepy.base.ioutils.Cached', 'Cached', (['int_ar'], {}), '(int_ar)\n', (8971, 8979), False, 'from sfepy.base.ioutils import Cached, Uncached, SoftLink, DataSoftLink\n'), ((9359, 9414), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'suffix': '""".h5"""', 'delete': '(False)'}), "(suffix='.h5', delete=False)\n", (9386, 9414), False, 'import tempfile\n'), ((9440, 9460), 'sfepy.discrete.fem.meshio.HDF5MeshIO', 'HDF5MeshIO', (['fil.name'], {}), '(fil.name)\n', (9450, 9460), False, 'from sfepy.discrete.fem.meshio import HDF5MeshIO\n'), ((9478, 9506), 'sfepy.solvers.ts.TimeStepper', 'TimeStepper', (['(0)', '(1.0)', '(0.1)', '(10)'], {}), '(0, 1.0, 0.1, 10)\n', (9489, 9506), False, 'from sfepy.solvers.ts import TimeStepper\n'), ((9816, 9851), 'sfepy.base.ioutils.DataSoftLink', 'DataSoftLink', (['"""Mesh"""', '"""/mesh"""', 'mesh'], {}), "('Mesh', '/mesh', mesh)\n", (9828, 9851), False, 'from sfepy.base.ioutils import Cached, Uncached, SoftLink, DataSoftLink\n'), ((10288, 10384), 'sfepy.base.base.assert_', 'assert_', (["(out['mesh7'] is out2['mesh7'])", '"""These two meshes should be in fact the same object"""'], {}), "(out['mesh7'] is out2['mesh7'],\n 'These two meshes should be in fact the same object')\n", (10295, 10384), False, 'from sfepy.base.base import assert_\n'), ((10410, 10506), 'sfepy.base.base.assert_', 'assert_', (["(out['mesh6'] is out2['mesh6'])", '"""These two meshes should be in fact the same object"""'], {}), "(out['mesh6'] is out2['mesh6'],\n 'These two meshes should be in fact the same object')\n", (10417, 10506), False, 'from sfepy.base.base import assert_\n'), ((10532, 10634), 'sfepy.base.base.assert_', 'assert_', (["(out['mesh5'] is not out2['mesh5'])", '"""These two meshes shouldnt be in fact the same object"""'], {}), "(out['mesh5'] is not out2['mesh5'],\n 'These two meshes shouldnt be in fact the same object')\n", (10539, 10634), False, 'from sfepy.base.base import assert_\n'), ((10662, 10757), 'sfepy.base.base.assert_', 'assert_', (["(out['mesh1'] is out['mesh2'])", '"""These two meshes should be in fact the same object"""'], {}), "(out['mesh1'] is out['mesh2'],\n 'These two meshes should be in fact the same object')\n", (10669, 10757), False, 'from sfepy.base.base import assert_\n'), ((10783, 10878), 'sfepy.base.base.assert_', 'assert_', (["(out['mesh1'] is out['mesh2'])", '"""These two meshes should be in fact the same object"""'], {}), "(out['mesh1'] is out['mesh2'],\n 'These two meshes should be in fact the same object')\n", (10790, 10878), False, 'from sfepy.base.base import assert_\n'), ((10904, 10999), 'sfepy.base.base.assert_', 'assert_', (["(out['mesh4'] is out['mesh2'])", '"""These two meshes should be in fact the same object"""'], {}), "(out['mesh4'] is out['mesh2'],\n 'These two meshes should be in fact the same object')\n", (10911, 10999), False, 'from sfepy.base.base import assert_\n'), ((11025, 11126), 'sfepy.base.base.assert_', 'assert_', (["(out['mesh5'] is not out['mesh2'])", '"""These two meshes shouldnt be in fact the same object"""'], {}), "(out['mesh5'] is not out['mesh2'],\n 'These two meshes shouldnt be in fact the same object')\n", (11032, 11126), False, 'from sfepy.base.base import assert_\n'), ((11154, 11249), 'sfepy.base.base.assert_', 'assert_', (["(out['mesh6'] is out['mesh2'])", '"""These two meshes should be in fact the same object"""'], {}), "(out['mesh6'] is out['mesh2'],\n 'These two meshes should be in fact the same object')\n", (11161, 11249), False, 'from sfepy.base.base import assert_\n'), ((11275, 11376), 'sfepy.base.base.assert_', 'assert_', (["(out['mesh7'] is not out['mesh2'])", '"""These two meshes shouldnt be in fact the same object"""'], {}), "(out['mesh7'] is not out['mesh2'],\n 'These two meshes shouldnt be in fact the same object')\n", (11282, 11376), False, 'from sfepy.base.base import assert_\n'), ((11404, 11497), 'sfepy.base.base.assert_', 'assert_', (["(out['mesh3'] is not out['mesh2'])", '"""These two meshes should be different objects"""'], {}), "(out['mesh3'] is not out['mesh2'],\n 'These two meshes should be different objects')\n", (11411, 11497), False, 'from sfepy.base.base import assert_\n'), ((11523, 11613), 'sfepy.base.base.assert_', 'assert_', (["(out['cached2'] is out['cached3'])", '"""These two array should be the same object"""'], {}), "(out['cached2'] is out['cached3'],\n 'These two array should be the same object')\n", (11530, 11613), False, 'from sfepy.base.base import assert_\n'), ((11639, 11727), 'sfepy.base.base.assert_', 'assert_', (["(out2['problem_mesh'] is mesh)", '"""These two meshes should be the same objects"""'], {}), "(out2['problem_mesh'] is mesh,\n 'These two meshes should be the same objects')\n", (11646, 11727), False, 'from sfepy.base.base import assert_\n'), ((12603, 12630), 'sfepy.base.base.assert_', 'assert_', (['(out3[0] is out3[1])'], {}), '(out3[0] is out3[1])\n', (12610, 12630), False, 'from sfepy.base.base import assert_\n'), ((9139, 9164), 'numpy.arange', 'nm.arange', (['(4)'], {'dtype': 'float'}), '(4, dtype=float)\n', (9148, 9164), True, 'import numpy as nm\n'), ((9186, 9208), 'numpy.array', 'nm.array', (['[2, 3, 4, 7]'], {}), '([2, 3, 4, 7])\n', (9194, 9208), True, 'import numpy as nm\n'), ((9571, 9625), 'sfepy.base.base.Struct', 'Struct', ([], {'mode': '"""custom"""', 'data': 'data', 'unpack_markers': '(False)'}), "(mode='custom', data=data, unpack_markers=False)\n", (9577, 9625), False, 'from sfepy.base.base import Struct\n'), ((9919, 9972), 'sfepy.base.base.Struct', 'Struct', ([], {'mode': '"""custom"""', 'data': 'data', 'unpack_markers': '(True)'}), "(mode='custom', data=data, unpack_markers=True)\n", (9925, 9972), False, 'from sfepy.base.base import Struct\n'), ((9245, 9267), 'numpy.array', 'nm.array', (['[1, 0, 0, 5]'], {}), '([1, 0, 0, 5])\n', (9253, 9267), True, 'import numpy as nm\n'), ((12293, 12359), 'sfepy.base.ioutils.DataSoftLink', 'DataSoftLink', (['"""Mesh"""', '"""/step0/__cdata/data/data/mesh1/data"""', 'mesh0'], {}), "('Mesh', '/step0/__cdata/data/data/mesh1/data', mesh0)\n", (12305, 12359), False, 'from sfepy.base.ioutils import Cached, Uncached, SoftLink, DataSoftLink\n')] |
"""
Time stepping solvers.
"""
import numpy as nm
from sfepy.base.base import output, Struct, IndexedStruct, basestr
from sfepy.solvers.solvers import make_get_conf, TimeSteppingSolver
from sfepy.discrete.mass_operator import MassOperator
from sfepy.solvers.ts import TimeStepper, VariableTimeStepper
class StationarySolver(TimeSteppingSolver):
"""
Solver for stationary problems without time stepping.
This class is provided to have a unified interface of the time stepping
solvers also for stationary problems.
"""
name = 'ts.stationary'
def __init__(self, conf, **kwargs):
TimeSteppingSolver.__init__(self, conf, ts=None, **kwargs)
def __call__(self, state0=None, save_results=True, step_hook=None,
post_process_hook=None, nls_status=None):
problem = self.problem
problem.time_update()
state = problem.solve(state0=state0, nls_status=nls_status)
if step_hook is not None:
step_hook(problem, None, state)
if save_results:
problem.save_state(problem.get_output_name(), state,
post_process_hook=post_process_hook,
file_per_var=None)
return state
def replace_virtuals(deps, pairs):
out = {}
for key, val in deps.iteritems():
out[pairs[key]] = val
return out
class EquationSequenceSolver(TimeSteppingSolver):
"""
Solver for stationary problems with an equation sequence.
"""
name = 'ts.equation_sequence'
def __init__(self, conf, **kwargs):
TimeSteppingSolver.__init__(self, conf, ts=None, **kwargs)
def __call__(self, state0=None, save_results=True, step_hook=None,
post_process_hook=None, nls_status=None):
from sfepy.base.base import invert_dict, get_subdict
from sfepy.base.resolve_deps import resolve
problem = self.problem
if state0 is None:
state0 = problem.create_state()
variables = problem.get_variables()
vtos = variables.get_dual_names()
vdeps = problem.equations.get_variable_dependencies()
sdeps = replace_virtuals(vdeps, vtos)
sorder = resolve(sdeps)
stov = invert_dict(vtos)
vorder = [[stov[ii] for ii in block] for block in sorder]
parts0 = state0.get_parts()
state = state0.copy()
solved = []
for ib, block in enumerate(vorder):
output('solving for %s...' % sorder[ib])
subpb = problem.create_subproblem(block, solved)
subpb.equations.print_terms()
subpb.time_update()
substate0 = subpb.create_state()
vals = get_subdict(parts0, block)
substate0.set_parts(vals)
substate = subpb.solve(state0=substate0, nls_status=nls_status)
state.set_parts(substate.get_parts())
solved.extend(sorder[ib])
output('...done')
if step_hook is not None:
step_hook(problem, None, state)
if save_results:
problem.save_state(problem.get_output_name(), state,
post_process_hook=post_process_hook,
file_per_var=None)
return state
def get_initial_state(problem):
"""
Create a zero state vector and apply initial conditions.
"""
state = problem.create_state()
problem.setup_ic()
state.apply_ic()
return state
def prepare_save_data(ts, conf):
"""
Given a time stepper configuration, return a list of time steps when the
state should be saved.
"""
try:
save_steps = conf.options.save_steps
except:
save_steps = -1
if save_steps == -1:
save_steps = ts.n_step
is_save = nm.linspace(0, ts.n_step - 1, save_steps).astype(nm.int32)
is_save = nm.unique(is_save)
return ts.suffix, is_save
def prepare_matrix(problem, state):
"""
Pre-assemble tangent system matrix.
"""
problem.update_materials()
ev = problem.get_evaluator()
try:
mtx = ev.eval_tangent_matrix(state(), is_full=True)
except ValueError:
output('matrix evaluation failed, giving up...')
raise
return mtx
def make_implicit_step(ts, state0, problem, nls_status=None):
"""
Make a step of an implicit time stepping solver.
"""
problem.time_update(ts)
if ts.step == 0:
state0.apply_ebc()
state = state0.copy(deep=True)
if not ts.is_quasistatic:
problem.init_time(ts)
ev = problem.get_evaluator()
try:
vec_r = ev.eval_residual(state(), is_full=True)
except ValueError:
output('initial residual evaluation failed, giving up...')
raise
else:
err = nm.linalg.norm(vec_r)
output('initial residual: %e' % err)
if problem.is_linear():
mtx = prepare_matrix(problem, state)
else:
mtx = None
# Initialize solvers (and possibly presolve the matrix).
presolve = mtx is not None
problem.init_solvers(nls_status=nls_status, mtx=mtx, presolve=presolve)
# Initialize variables with history.
state0.init_history()
if ts.is_quasistatic:
# Ordinary solve.
state = problem.solve(state0=state0, nls_status=nls_status)
else:
if (ts.step == 1) and ts.is_quasistatic and problem.is_linear():
mtx = prepare_matrix(problem, state0)
problem.init_solvers(nls_status=nls_status, mtx=mtx)
state = problem.solve(state0=state0, nls_status=nls_status)
return state
def make_explicit_step(ts, state0, problem, mass, nls_status=None):
"""
Make a step of an explicit time stepping solver.
"""
problem.time_update(ts)
if ts.step == 0:
state0.apply_ebc()
state = state0.copy(deep=True)
problem.init_time(ts)
# Initialize variables with history.
state0.init_history()
ev = problem.get_evaluator()
try:
vec_r = ev.eval_residual(state0(), is_full=True)
except ValueError:
output('residual evaluation failed, giving up...')
raise
else:
err = nm.linalg.norm(vec_r)
output('residual: %e' % err)
if ts.step > 0:
variables = problem.get_variables()
vec_rf = variables.make_full_vec(vec_r, force_value=0.0)
rhs = -ts.dt * vec_rf + mass.action(state0())
vec = mass.inverse_action(rhs)
state = state0.copy(preserve_caches=True)
state.set_full(vec)
state.apply_ebc()
return state
def get_min_dt(adt):
red = adt.red
while red >= adt.red_max:
red *= adt.red_factor
dt = adt.dt0 * red
return dt
def adapt_time_step(ts, status, adt, problem=None):
"""
Adapt the time step of `ts` according to the exit status of the
nonlinear solver.
The time step dt is reduced, if the nonlinear solver did not converge. If it
converged in less then a specified number of iterations for several time
steps, the time step is increased. This is governed by the following
parameters:
- red_factor : time step reduction factor
- red_max : maximum time step reduction factor
- inc_factor : time step increase factor
- inc_on_iter : increase time step if the nonlinear solver converged in
less than this amount of iterations...
- inc_wait : ...for this number of consecutive time steps
Parameters
----------
ts : VariableTimeStepper instance
The time stepper.
status : IndexedStruct instance
The nonlinear solver exit status.
adt : Struct instance
The adaptivity parameters of the time solver:
problem : Problem instance, optional
This canbe used in user-defined adaptivity functions. Not used here.
Returns
-------
is_break : bool
If True, the adaptivity loop should stop.
"""
is_break = False
if status.condition == 0:
if status.n_iter <= adt.inc_on_iter:
adt.wait += 1
if adt.wait > adt.inc_wait:
if adt.red < 1.0:
adt.red = adt.red * adt.inc_factor
ts.set_time_step(adt.dt0 * adt.red)
output('+++++ new time step: %e +++++' % ts.dt)
adt.wait = 0
else:
adt.wait = 0
is_break = True
else:
adt.red = adt.red * adt.red_factor
if adt.red < adt.red_max:
is_break = True
else:
ts.set_time_step(adt.dt0 * adt.red, update_time=True)
output('----- new time step: %e -----' % ts.dt)
adt.wait = 0
return is_break
class SimpleTimeSteppingSolver(TimeSteppingSolver):
"""
Implicit time stepping solver with a fixed time step.
"""
name = 'ts.simple'
@staticmethod
def process_conf(conf, kwargs):
"""
Process configuration options.
"""
get = make_get_conf(conf, kwargs)
common = TimeSteppingSolver.process_conf(conf)
return Struct(t0=get('t0', 0.0),
t1=get('t1', 1.0),
dt=get('dt', None),
n_step=get('n_step', 10),
quasistatic=get('quasistatic', False)) + common
def __init__(self, conf, **kwargs):
TimeSteppingSolver.__init__(self, conf, **kwargs)
self.ts = TimeStepper.from_conf(self.conf)
nd = self.ts.n_digit
format = '====== time %%e (step %%%dd of %%%dd) =====' % (nd, nd)
self.format = format
def __call__(self, state0=None, save_results=True, step_hook=None,
post_process_hook=None, nls_status=None):
"""
Solve the time-dependent problem.
"""
problem = self.problem
ts = self.ts
suffix, is_save = prepare_save_data(ts, problem.conf)
if state0 is None:
state0 = get_initial_state(problem)
ii = 0
for step, time in ts:
output(self.format % (time, step + 1, ts.n_step))
state = self.solve_step(ts, state0, nls_status=nls_status)
state0 = state.copy(deep=True)
if step_hook is not None:
step_hook(problem, ts, state)
if save_results and (is_save[ii] == ts.step):
filename = problem.get_output_name(suffix=suffix % ts.step)
problem.save_state(filename, state,
post_process_hook=post_process_hook,
file_per_var=None,
ts=ts)
ii += 1
problem.advance(ts)
return state
def solve_step(self, ts, state0, nls_status=None):
"""
Solve a single time step.
"""
state = make_implicit_step(ts, state0, self.problem,
nls_status=nls_status)
return state
class ExplicitTimeSteppingSolver(SimpleTimeSteppingSolver):
"""
Explicit time stepping solver with a fixed time step.
"""
name = 'ts.explicit'
@staticmethod
def process_conf(conf, kwargs):
"""
Process configuration options.
"""
get = make_get_conf(conf, kwargs)
common = SimpleTimeSteppingSolver.process_conf(conf, kwargs)
return Struct(mass=get('mass', None,
'missing "mass" in options!'),
lumped=get('lumped', False)) + common
def __init__(self, conf, **kwargs):
SimpleTimeSteppingSolver.__init__(self, conf, **kwargs)
self.mass = MassOperator(self.problem, self.conf)
def solve_step(self, ts, state0, nls_status=None):
"""
Solve a single time step.
"""
state = make_explicit_step(ts, state0, self.problem, self.mass,
nls_status=nls_status)
return state
class AdaptiveTimeSteppingSolver(SimpleTimeSteppingSolver):
"""
Implicit time stepping solver with an adaptive time step.
Either the built-in or user supplied function can be used to adapt the time
step.
"""
name = 'ts.adaptive'
@staticmethod
def process_conf(conf, kwargs):
"""
Process configuration options.
"""
get = make_get_conf(conf, kwargs)
common = SimpleTimeSteppingSolver.process_conf(conf, kwargs)
adt = Struct(red_factor=get('dt_red_factor', 0.2),
red_max=get('dt_red_max', 1e-3),
inc_factor=get('dt_inc_factor', 1.25),
inc_on_iter=get('dt_inc_on_iter', 4),
inc_wait=get('dt_inc_wait', 5),
red=1.0, wait=0, dt0=0.0)
return Struct(adapt_fun=get('adapt_fun', adapt_time_step),
adt=adt) + common
def __init__(self, conf, **kwargs):
TimeSteppingSolver.__init__(self, conf, **kwargs)
self.ts = VariableTimeStepper.from_conf(self.conf)
self.adt = adt = self.conf.adt
adt.dt0 = self.ts.get_default_time_step()
self.ts.set_n_digit_from_min_dt(get_min_dt(adt))
self.format = '====== time %e (dt %e, wait %d, step %d of %d) ====='
if isinstance(self.conf.adapt_fun, basestr):
self.adapt_time_step = self.problem.functions[self.conf.adapt_fun]
else:
self.adapt_time_step = self.conf.adapt_fun
def __call__(self, state0=None, save_results=True, step_hook=None,
post_process_hook=None, nls_status=None):
"""
Solve the time-dependent problem.
"""
problem = self.problem
ts = self.ts
if state0 is None:
state0 = get_initial_state(problem)
ii = 0
for step, time in ts:
output(self.format % (time, ts.dt, self.adt.wait,
step + 1, ts.n_step))
state = self.solve_step(ts, state0, nls_status=nls_status)
state0 = state.copy(deep=True)
if step_hook is not None:
step_hook(problem, ts, state)
if save_results:
filename = problem.get_output_name(suffix=ts.suffix % ts.step)
problem.save_state(filename, state,
post_process_hook=post_process_hook,
file_per_var=None,
ts=ts)
ii += 1
problem.advance(ts)
return state
def solve_step(self, ts, state0, nls_status=None):
"""
Solve a single time step.
"""
status = IndexedStruct(n_iter=0, condition=0)
while 1:
state = make_implicit_step(ts, state0, self.problem,
nls_status=status)
is_break = self.adapt_time_step(ts, status, self.adt, self.problem)
if is_break:
break
if nls_status is not None:
nls_status.update(status)
return state
| [
"sfepy.base.base.invert_dict",
"sfepy.base.base.output",
"sfepy.solvers.solvers.TimeSteppingSolver.__init__",
"sfepy.solvers.solvers.TimeSteppingSolver.process_conf",
"sfepy.discrete.mass_operator.MassOperator",
"sfepy.solvers.ts.VariableTimeStepper.from_conf",
"sfepy.base.base.IndexedStruct",
"sfepy.... | [((3883, 3901), 'numpy.unique', 'nm.unique', (['is_save'], {}), '(is_save)\n', (3892, 3901), True, 'import numpy as nm\n'), ((616, 674), 'sfepy.solvers.solvers.TimeSteppingSolver.__init__', 'TimeSteppingSolver.__init__', (['self', 'conf'], {'ts': 'None'}), '(self, conf, ts=None, **kwargs)\n', (643, 674), False, 'from sfepy.solvers.solvers import make_get_conf, TimeSteppingSolver\n'), ((1592, 1650), 'sfepy.solvers.solvers.TimeSteppingSolver.__init__', 'TimeSteppingSolver.__init__', (['self', 'conf'], {'ts': 'None'}), '(self, conf, ts=None, **kwargs)\n', (1619, 1650), False, 'from sfepy.solvers.solvers import make_get_conf, TimeSteppingSolver\n'), ((2212, 2226), 'sfepy.base.resolve_deps.resolve', 'resolve', (['sdeps'], {}), '(sdeps)\n', (2219, 2226), False, 'from sfepy.base.resolve_deps import resolve\n'), ((2243, 2260), 'sfepy.base.base.invert_dict', 'invert_dict', (['vtos'], {}), '(vtos)\n', (2254, 2260), False, 'from sfepy.base.base import invert_dict, get_subdict\n'), ((6330, 6351), 'numpy.linalg.norm', 'nm.linalg.norm', (['vec_r'], {}), '(vec_r)\n', (6344, 6351), True, 'import numpy as nm\n'), ((6360, 6388), 'sfepy.base.base.output', 'output', (["('residual: %e' % err)"], {}), "('residual: %e' % err)\n", (6366, 6388), False, 'from sfepy.base.base import output, Struct, IndexedStruct, basestr\n'), ((9131, 9158), 'sfepy.solvers.solvers.make_get_conf', 'make_get_conf', (['conf', 'kwargs'], {}), '(conf, kwargs)\n', (9144, 9158), False, 'from sfepy.solvers.solvers import make_get_conf, TimeSteppingSolver\n'), ((9176, 9213), 'sfepy.solvers.solvers.TimeSteppingSolver.process_conf', 'TimeSteppingSolver.process_conf', (['conf'], {}), '(conf)\n', (9207, 9213), False, 'from sfepy.solvers.solvers import make_get_conf, TimeSteppingSolver\n'), ((9506, 9555), 'sfepy.solvers.solvers.TimeSteppingSolver.__init__', 'TimeSteppingSolver.__init__', (['self', 'conf'], {}), '(self, conf, **kwargs)\n', (9533, 9555), False, 'from sfepy.solvers.solvers import make_get_conf, TimeSteppingSolver\n'), ((9575, 9607), 'sfepy.solvers.ts.TimeStepper.from_conf', 'TimeStepper.from_conf', (['self.conf'], {}), '(self.conf)\n', (9596, 9607), False, 'from sfepy.solvers.ts import TimeStepper, VariableTimeStepper\n'), ((11419, 11446), 'sfepy.solvers.solvers.make_get_conf', 'make_get_conf', (['conf', 'kwargs'], {}), '(conf, kwargs)\n', (11432, 11446), False, 'from sfepy.solvers.solvers import make_get_conf, TimeSteppingSolver\n'), ((11810, 11847), 'sfepy.discrete.mass_operator.MassOperator', 'MassOperator', (['self.problem', 'self.conf'], {}), '(self.problem, self.conf)\n', (11822, 11847), False, 'from sfepy.discrete.mass_operator import MassOperator\n'), ((12501, 12528), 'sfepy.solvers.solvers.make_get_conf', 'make_get_conf', (['conf', 'kwargs'], {}), '(conf, kwargs)\n', (12514, 12528), False, 'from sfepy.solvers.solvers import make_get_conf, TimeSteppingSolver\n'), ((13088, 13137), 'sfepy.solvers.solvers.TimeSteppingSolver.__init__', 'TimeSteppingSolver.__init__', (['self', 'conf'], {}), '(self, conf, **kwargs)\n', (13115, 13137), False, 'from sfepy.solvers.solvers import make_get_conf, TimeSteppingSolver\n'), ((13157, 13197), 'sfepy.solvers.ts.VariableTimeStepper.from_conf', 'VariableTimeStepper.from_conf', (['self.conf'], {}), '(self.conf)\n', (13186, 13197), False, 'from sfepy.solvers.ts import TimeStepper, VariableTimeStepper\n'), ((14854, 14890), 'sfepy.base.base.IndexedStruct', 'IndexedStruct', ([], {'n_iter': '(0)', 'condition': '(0)'}), '(n_iter=0, condition=0)\n', (14867, 14890), False, 'from sfepy.base.base import output, Struct, IndexedStruct, basestr\n'), ((2470, 2510), 'sfepy.base.base.output', 'output', (["('solving for %s...' % sorder[ib])"], {}), "('solving for %s...' % sorder[ib])\n", (2476, 2510), False, 'from sfepy.base.base import output, Struct, IndexedStruct, basestr\n'), ((2714, 2740), 'sfepy.base.base.get_subdict', 'get_subdict', (['parts0', 'block'], {}), '(parts0, block)\n', (2725, 2740), False, 'from sfepy.base.base import invert_dict, get_subdict\n'), ((2958, 2975), 'sfepy.base.base.output', 'output', (['"""...done"""'], {}), "('...done')\n", (2964, 2975), False, 'from sfepy.base.base import output, Struct, IndexedStruct, basestr\n'), ((3810, 3851), 'numpy.linspace', 'nm.linspace', (['(0)', '(ts.n_step - 1)', 'save_steps'], {}), '(0, ts.n_step - 1, save_steps)\n', (3821, 3851), True, 'import numpy as nm\n'), ((4192, 4240), 'sfepy.base.base.output', 'output', (['"""matrix evaluation failed, giving up..."""'], {}), "('matrix evaluation failed, giving up...')\n", (4198, 4240), False, 'from sfepy.base.base import output, Struct, IndexedStruct, basestr\n'), ((6241, 6291), 'sfepy.base.base.output', 'output', (['"""residual evaluation failed, giving up..."""'], {}), "('residual evaluation failed, giving up...')\n", (6247, 6291), False, 'from sfepy.base.base import output, Struct, IndexedStruct, basestr\n'), ((8755, 8802), 'sfepy.base.base.output', 'output', (["('----- new time step: %e -----' % ts.dt)"], {}), "('----- new time step: %e -----' % ts.dt)\n", (8761, 8802), False, 'from sfepy.base.base import output, Struct, IndexedStruct, basestr\n'), ((10188, 10237), 'sfepy.base.base.output', 'output', (['(self.format % (time, step + 1, ts.n_step))'], {}), '(self.format % (time, step + 1, ts.n_step))\n', (10194, 10237), False, 'from sfepy.base.base import output, Struct, IndexedStruct, basestr\n'), ((14009, 14080), 'sfepy.base.base.output', 'output', (['(self.format % (time, ts.dt, self.adt.wait, step + 1, ts.n_step))'], {}), '(self.format % (time, ts.dt, self.adt.wait, step + 1, ts.n_step))\n', (14015, 14080), False, 'from sfepy.base.base import output, Struct, IndexedStruct, basestr\n'), ((4879, 4900), 'numpy.linalg.norm', 'nm.linalg.norm', (['vec_r'], {}), '(vec_r)\n', (4893, 4900), True, 'import numpy as nm\n'), ((4917, 4953), 'sfepy.base.base.output', 'output', (["('initial residual: %e' % err)"], {}), "('initial residual: %e' % err)\n", (4923, 4953), False, 'from sfepy.base.base import output, Struct, IndexedStruct, basestr\n'), ((4758, 4816), 'sfepy.base.base.output', 'output', (['"""initial residual evaluation failed, giving up..."""'], {}), "('initial residual evaluation failed, giving up...')\n", (4764, 4816), False, 'from sfepy.base.base import output, Struct, IndexedStruct, basestr\n'), ((8404, 8451), 'sfepy.base.base.output', 'output', (["('+++++ new time step: %e +++++' % ts.dt)"], {}), "('+++++ new time step: %e +++++' % ts.dt)\n", (8410, 8451), False, 'from sfepy.base.base import output, Struct, IndexedStruct, basestr\n')] |
import numpy as nm
from sfepy.base.conf import transform_functions
from sfepy.base.testing import TestCommon
def get_vertices(coors, domain=None):
x, z = coors[:,0], coors[:,2]
return nm.where((z < 0.1) & (x < 0.1))[0]
def get_cells(coors, domain=None):
return nm.where(coors[:, 0] < 0)[0]
class Test(TestCommon):
@staticmethod
def from_conf( conf, options ):
from sfepy import data_dir
from sfepy.discrete.fem import Mesh, FEDomain
from sfepy.discrete import Functions
mesh = Mesh('test mesh',
data_dir + '/meshes/various_formats/abaqus_tet.inp')
mesh.nodal_bcs['set0'] = [0, 7]
domain = FEDomain('test domain', mesh)
conf_functions = {
'get_vertices' : (get_vertices,),
'get_cells' : (get_cells,),
}
functions = Functions.from_conf(transform_functions(conf_functions))
test = Test(conf=conf, options=options,
domain=domain, functions=functions)
return test
def test_selectors(self):
"""
Test basic region selectors.
"""
selectors = [
['all', 'cell'],
['vertices of surface', 'facet'],
['vertices of group 0', 'facet'],
['vertices of set set0', 'vertex'],
['vertices in (z < 0.1) & (x < 0.1)', 'facet'],
['vertices by get_vertices', 'cell'],
['vertex 0, 1, 2', 'vertex'],
['vertex in r.r6', 'vertex'],
['cells of group 0', 'cell'],
# ['cells of set 0', 'cell'], not implemented...
['cells by get_cells', 'cell'],
['cell 1, 4, 5', 'cell'],
['cell (0, 1), (0, 4), (0, 5)', 'cell'],
['copy r.r5', 'cell'],
['r.r5', 'cell'],
]
vertices = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[0, 1, 3, 7],
[0, 7],
[1, 2, 3, 4, 5, 9, 11],
[1, 2, 3, 4, 5, 9, 11],
[0, 1, 2],
[0],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
[0, 1, 2, 3, 4, 5, 6, 9, 10, 11],
[0, 1, 2, 3, 4, 5, 6, 8],
[0, 1, 2, 3, 4, 5, 6, 8],
[1, 2, 3, 4, 5, 9, 11],
[1, 2, 3, 4, 5, 9, 11],
]
ok = True
for ii, sel in enumerate(selectors):
self.report('select:', sel)
reg = self.domain.create_region('r%d' % ii, sel[0], kind=sel[1],
functions=self.functions)
_ok = ((len(reg.vertices) == len(vertices[ii]))
and (reg.vertices == vertices[ii]).all())
self.report(' vertices:', _ok)
ok = ok and _ok
return ok
def test_operators(self):
"""
Test operators in region selectors.
"""
ok = True
r1 = self.domain.create_region('r1', 'all')
sel = 'r.r1 -v vertices of group 0'
self.report('select:', sel)
reg = self.domain.create_region('reg', sel, kind='vertex')
av = [2, 4, 5, 6, 8, 9, 10, 11, 12]
_ok = (reg.vertices == nm.array(av)).all()
self.report(' vertices:', _ok)
ok = ok and _ok
sel = 'vertex 0, 1, 2 +v vertices of group 0'
self.report('select:', sel)
reg = self.domain.create_region('reg', sel, kind='vertex')
av = [0, 1, 2, 3, 7]
_ok = (reg.vertices == nm.array(av)).all()
self.report(' vertices:', _ok)
ok = ok and _ok
sel = 'vertex 0, 1, 2 *v vertices of group 0'
self.report('select:', sel)
reg = self.domain.create_region('reg', sel, kind='vertex')
av = [0, 1]
_ok = (reg.vertices == nm.array(av)).all()
self.report(' vertices:', _ok)
ok = ok and _ok
sel = 'r.r1 -c cell 1, 4, 5'
self.report('select:', sel)
reg = self.domain.create_region('reg', sel)
_ok = (nm.setdiff1d(r1.cells[0], [1, 4, 5]) == reg.cells[0]).all()
self.report(' cells:', _ok)
ok = ok and _ok
sel = 'cell 8, 3 +c cell 1, 4, 5'
self.report('select:', sel)
reg = self.domain.create_region('reg', sel)
cells = [1, 3, 4, 5, 8]
_ok = (reg.cells == nm.array(cells)).all()
self.report(' cells:', _ok)
ok = ok and _ok
sel = 'cell 8, 3, 2 *c cell 8, 4, 2, 7'
self.report('select:', sel)
reg = self.domain.create_region('reg', sel)
cells = [2, 8]
_ok = (reg.cells == nm.array(cells)).all()
self.report(' cells:', _ok)
ok = ok and _ok
return ok
| [
"sfepy.base.conf.transform_functions",
"sfepy.discrete.fem.Mesh",
"sfepy.discrete.fem.FEDomain"
] | [((195, 226), 'numpy.where', 'nm.where', (['((z < 0.1) & (x < 0.1))'], {}), '((z < 0.1) & (x < 0.1))\n', (203, 226), True, 'import numpy as nm\n'), ((277, 302), 'numpy.where', 'nm.where', (['(coors[:, 0] < 0)'], {}), '(coors[:, 0] < 0)\n', (285, 302), True, 'import numpy as nm\n'), ((536, 606), 'sfepy.discrete.fem.Mesh', 'Mesh', (['"""test mesh"""', "(data_dir + '/meshes/various_formats/abaqus_tet.inp')"], {}), "('test mesh', data_dir + '/meshes/various_formats/abaqus_tet.inp')\n", (540, 606), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((684, 713), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""test domain"""', 'mesh'], {}), "('test domain', mesh)\n", (692, 713), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((878, 913), 'sfepy.base.conf.transform_functions', 'transform_functions', (['conf_functions'], {}), '(conf_functions)\n', (897, 913), False, 'from sfepy.base.conf import transform_functions\n'), ((3318, 3330), 'numpy.array', 'nm.array', (['av'], {}), '(av)\n', (3326, 3330), True, 'import numpy as nm\n'), ((3624, 3636), 'numpy.array', 'nm.array', (['av'], {}), '(av)\n', (3632, 3636), True, 'import numpy as nm\n'), ((3918, 3930), 'numpy.array', 'nm.array', (['av'], {}), '(av)\n', (3926, 3930), True, 'import numpy as nm\n'), ((4143, 4179), 'numpy.setdiff1d', 'nm.setdiff1d', (['r1.cells[0]', '[1, 4, 5]'], {}), '(r1.cells[0], [1, 4, 5])\n', (4155, 4179), True, 'import numpy as nm\n'), ((4459, 4474), 'numpy.array', 'nm.array', (['cells'], {}), '(cells)\n', (4467, 4474), True, 'import numpy as nm\n'), ((4732, 4747), 'numpy.array', 'nm.array', (['cells'], {}), '(cells)\n', (4740, 4747), True, 'import numpy as nm\n')] |
# Vibroacoustics
#
# E.Rohan, V.Lukeš
# Homogenization of the vibro–acoustic transmission on periodically
# perforated elastic plates with arrays of resonators.
# https://arxiv.org/abs/2104.01367 (arXiv:2104.01367v1)
import os.path as op
import numpy as nm
from acoustics_macro_utils import get_homogmat
from sfepy.homogenization.utils import define_box_regions
from sfepy.discrete.fem import Mesh
from sfepy.discrete.fem.periodic import match_y_plane, match_x_plane
wdir = op.dirname(__file__)
def get_regions(filename_mesh):
mesh = Mesh.from_file(filename_mesh)
bbox = nm.array(mesh.get_bounding_box())
region_lb, region_rt = bbox
return define_box_regions(2, region_lb, region_rt)
def get_homogmat_plate(coors, mode, pb):
if mode != 'qp':
return
mconf = pb.conf.mconf
c = mconf.sound_speed
wave_num = mconf.wave_num
rho0 = mconf.rho0
c2 = c**2
w = wave_num * c
w2 = w**2
pb.ofn_trunk = mconf.ofn_trunk + '_plate'
out_ac = get_homogmat(coors, mode, pb, mconf.coefs_filename, omega=w)
nqp = coors.shape[0]
out = {}
out['A'] = out_ac['A']
out['w2F'] = out_ac['F'] * w2
out['wB'] = out_ac['B'] * w
vol_Imp = 0.5 * (out_ac['Vol_Imp']['volume_Im'] +
out_ac['Vol_Imp']['volume_Ip'])
zeta = out_ac['volumes']['volume_Y'] / vol_Imp
out['w2Kr'] = nm.tile(zeta / c2, (nqp, 1, 1)) * w2
out['w'] = nm.ones((nqp, 1, 1), dtype=nm.float64) * w
out_vc = get_homogmat(coors, mode, pb, mconf.coefs_filename_plate)
bar_h = out_ac['h']
h = mconf.eps0 * bar_h
out['E'] = bar_h / rho0 * out_vc['Cm']
out['h2E'] = h**2 / 12. * out['E']
out['wH'] = bar_h * out_vc['Hm'] * w
out['w2K'] = out['w2Kr'] + rho0 * out_vc['Km'] * bar_h * w2
out['S'] = bar_h / rho0 * out_vc['Gm']
sfdim = out_vc['Gm'].shape[2]
out['w2C3'] = out_ac['C'][:, sfdim:, :] * w2
out['wD'] = nm.ascontiguousarray(out_ac['D'][:, :sfdim, :sfdim]) * w
out['w2M'] = (out_ac['tM'] + out_ac['M'][:, :sfdim, :sfdim]) * w2
out['w2N'] = out_ac['M'][:, sfdim:, sfdim:] * w2
out['w2h2L'] = h**2 / 12. * out_ac['tM'] * w2
print('### material-plate: wave number = ', wave_num)
return out
def define(**kwargs):
mconf = kwargs['master_problem'].conf
filename_mesh = mconf.filename_mesh_plate
regions = {
'Gamma0_1': 'all',
}
regions.update(get_regions(filename_mesh))
functions = {
'get_homogmat':
(lambda ts, coors, mode=None, problem=None, **kwargs:
get_homogmat_plate(coors, mode, problem),),
'match_y_plane': (match_y_plane,),
}
materials = {
'ac': 'get_homogmat',
}
fields = {
'tvelocity0': ('complex', 'scalar', 'Gamma0_1', 1),
'pressure0': ('complex', 'scalar', 'Gamma0_1', 1),
'deflection': ('complex', 'scalar', 'Gamma0_1', 2),
'displacement': ('complex', 'vector', 'Gamma0_1', 1),
'rotation': ('complex', 'vector', 'Gamma0_1', 1),
}
integrals = {
'i': 4,
}
variables = {
'sp0': ('unknown field', 'pressure0', 0),
'sq0': ('test field', 'pressure0', 'sp0'),
'dp0': ('unknown field', 'pressure0', 1),
'dq0': ('test field', 'pressure0', 'dp0'),
'g01': ('unknown field', 'tvelocity0', 2),
'f01': ('test field', 'tvelocity0', 'g01'),
'g02': ('unknown field', 'tvelocity0', 3),
'f02': ('test field', 'tvelocity0', 'g02'),
'u': ('unknown field', 'displacement', 4),
'v': ('test field', 'displacement', 'u'),
'w': ('unknown field', 'deflection', 5),
'z': ('test field', 'deflection', 'w'),
'theta': ('unknown field', 'rotation', 6),
'nu': ('test field', 'rotation', 'theta'),
}
ebcs = {
'fixed_l': ('Left', {'w.0': 0.0, 'u.all': 0.0, 'theta.all': 0.0}),
'fixed_r': ('Right', {'w.0': 0.0, 'u.all': 0.0, 'theta.all': 0.0}),
}
epbcs = {
# 'per_g01': (['Bottom', 'Top'], {'g01.0': 'g01.0'},
# 'match_y_plane'),
# 'per_g02': (['Bottom', 'Top'], {'g02.0': 'g02.0'},
# 'match_y_plane'),
# 'per_dp0': (['Bottom', 'Top'], {'dp0.0': 'dp0.0'},
# 'match_y_plane'),
# 'per_sp0': (['Bottom', 'Top'], {'sp0.0': 'sp0.0'},
# 'match_y_plane'),
'per_w': (['Bottom', 'Top'], {'w.0': 'w.0'},
'match_y_plane'),
'per_u': (['Bottom', 'Top'], {'u.all': 'u.all'},
'match_y_plane'),
'per_theta': (['Bottom', 'Top'], {'theta.all': 'theta.all'},
'match_y_plane'),
}
equations = {
# p^0 = 0.5 * (P^+ + P^-)
# eq. (79)_1
'eq_g01': """
0.5 * dw_diffusion.i.Gamma0_1(ac.A, f01, sp0)
- 0.5 * dw_volume_dot.i.Gamma0_1(ac.w2K, f01, sp0)
+ %s * dw_v_dot_grad_s.i.Gamma0_1(ac.wD, u, f01)
+ %s * dw_biot.i.Gamma0_1(ac.wH, u, f01)
+ %s * dw_volume_dot.i.Gamma0_1(ac.w, f01, g01)
- %s * dw_volume_dot.i.Gamma0_1(ac.w, f01, g02)
= 0""" % (1j, 1j, 1j / mconf.eps0, 1j / mconf.eps0),
# eq. (80)_1
'eq_g02': """
+ 0.5 * dw_volume_dot.i.Gamma0_1(ac.w2F, f02, g01)
+ 0.5 * dw_volume_dot.i.Gamma0_1(ac.w2F, f02, g02)
- dw_volume_dot.i.Gamma0_1(ac.w2C3, f02, w)
- %s * dw_volume_dot.i.Gamma0_1(ac.w, f02, dp0)
= 0""" % (1j / mconf.eps0,),
# p^0 = 0.5 * (P^+ + P^-)
# eq. (79)_2
'eq_v': """
- %s * dw_v_dot_grad_s.i.Gamma0_1(ac.wD, v, sp0)
- %s * dw_biot.i.Gamma0_1(ac.wH, v, sp0)
+ dw_lin_elastic.i.Gamma0_1(ac.E, v, u)
- dw_volume_dot.i.Gamma0_1(ac.w2M, v, u)
= 0""" % (1j * 0.5, 1j * 0.5),
# eq. (80)_2
'eq_z': """
- dw_volume_dot.i.Gamma0_1(ac.w2N, z, w)
+ dw_diffusion.i.Gamma0_1(ac.S, z, w)
- dw_v_dot_grad_s.i.Gamma0_1(ac.S, theta, z)
+ 0.5 * dw_volume_dot.i.Gamma0_1(ac.w2C3, z, g01)
+ 0.5 * dw_volume_dot.i.Gamma0_1(ac.w2C3, z, g02)
= 0""",
# eq. (80)_2
'eq_nu': """
- dw_volume_dot.i.Gamma0_1(ac.w2h2L, nu, theta)
+ dw_lin_elastic.i.Gamma0_1(ac.h2E, nu, theta)
+ dw_volume_dot.i.Gamma0_1(ac.S, nu, theta)
- dw_v_dot_grad_s.i.Gamma0_1(ac.S, nu, w)
= 0""",
}
options = {
'output_dir': op.join(wdir, 'results'),
'output_format': 'h5',
}
solvers = {
'ls': ('ls.scipy_direct', {}),
'newton': ('nls.newton', {'i_max': 1,
'eps_a': 1e-6,
'eps_r': 1e-6,
'problem': 'nonlinear', })
}
return locals()
| [
"sfepy.discrete.fem.Mesh.from_file",
"sfepy.homogenization.utils.define_box_regions"
] | [((476, 496), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (486, 496), True, 'import os.path as op\n'), ((542, 571), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['filename_mesh'], {}), '(filename_mesh)\n', (556, 571), False, 'from sfepy.discrete.fem import Mesh\n'), ((661, 704), 'sfepy.homogenization.utils.define_box_regions', 'define_box_regions', (['(2)', 'region_lb', 'region_rt'], {}), '(2, region_lb, region_rt)\n', (679, 704), False, 'from sfepy.homogenization.utils import define_box_regions\n'), ((1000, 1060), 'acoustics_macro_utils.get_homogmat', 'get_homogmat', (['coors', 'mode', 'pb', 'mconf.coefs_filename'], {'omega': 'w'}), '(coors, mode, pb, mconf.coefs_filename, omega=w)\n', (1012, 1060), False, 'from acoustics_macro_utils import get_homogmat\n'), ((1481, 1538), 'acoustics_macro_utils.get_homogmat', 'get_homogmat', (['coors', 'mode', 'pb', 'mconf.coefs_filename_plate'], {}), '(coors, mode, pb, mconf.coefs_filename_plate)\n', (1493, 1538), False, 'from acoustics_macro_utils import get_homogmat\n'), ((1372, 1403), 'numpy.tile', 'nm.tile', (['(zeta / c2)', '(nqp, 1, 1)'], {}), '(zeta / c2, (nqp, 1, 1))\n', (1379, 1403), True, 'import numpy as nm\n'), ((1424, 1462), 'numpy.ones', 'nm.ones', (['(nqp, 1, 1)'], {'dtype': 'nm.float64'}), '((nqp, 1, 1), dtype=nm.float64)\n', (1431, 1462), True, 'import numpy as nm\n'), ((1922, 1974), 'numpy.ascontiguousarray', 'nm.ascontiguousarray', (["out_ac['D'][:, :sfdim, :sfdim]"], {}), "(out_ac['D'][:, :sfdim, :sfdim])\n", (1942, 1974), True, 'import numpy as nm\n'), ((6668, 6692), 'os.path.join', 'op.join', (['wdir', '"""results"""'], {}), "(wdir, 'results')\n", (6675, 6692), True, 'import os.path as op\n')] |
from __future__ import absolute_import
import os
import sfepy
from sfepy.base.base import load_classes, insert_static_method
from .solvers import *
from .eigen import eig
solver_files = sfepy.get_paths('sfepy/solvers/*.py')
remove = ['setup.py', 'solvers.py', 'petsc_worker.py']
solver_files = [name for name in solver_files
if os.path.basename(name) not in remove]
solver_table = load_classes(solver_files,
[LinearSolver, NonlinearSolver,
TimeSteppingSolver, EigenvalueSolver,
OptimizationSolver], package_name='sfepy.solvers')
def register_solver(cls):
"""
Register a custom solver.
"""
solver_table[cls.name] = cls
def any_from_conf(conf, **kwargs):
"""Create an instance of a solver class according to the configuration."""
return solver_table[conf.kind](conf, **kwargs)
insert_static_method(Solver, any_from_conf)
del any_from_conf
del sfepy
| [
"sfepy.get_paths",
"sfepy.base.base.insert_static_method",
"sfepy.base.base.load_classes"
] | [((187, 224), 'sfepy.get_paths', 'sfepy.get_paths', (['"""sfepy/solvers/*.py"""'], {}), "('sfepy/solvers/*.py')\n", (202, 224), False, 'import sfepy\n'), ((398, 554), 'sfepy.base.base.load_classes', 'load_classes', (['solver_files', '[LinearSolver, NonlinearSolver, TimeSteppingSolver, EigenvalueSolver,\n OptimizationSolver]'], {'package_name': '"""sfepy.solvers"""'}), "(solver_files, [LinearSolver, NonlinearSolver,\n TimeSteppingSolver, EigenvalueSolver, OptimizationSolver], package_name\n ='sfepy.solvers')\n", (410, 554), False, 'from sfepy.base.base import load_classes, insert_static_method\n'), ((904, 947), 'sfepy.base.base.insert_static_method', 'insert_static_method', (['Solver', 'any_from_conf'], {}), '(Solver, any_from_conf)\n', (924, 947), False, 'from sfepy.base.base import load_classes, insert_static_method\n'), ((345, 367), 'os.path.basename', 'os.path.basename', (['name'], {}), '(name)\n', (361, 367), False, 'import os\n')] |
from __future__ import absolute_import
import os.path as op
import numpy as nm
import sfepy
from sfepy.discrete import FieldVariable
from sfepy.discrete.fem import Mesh, FEDomain, Field
from sfepy.base.base import assert_
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
mesh = Mesh.from_file('meshes/2d/square_unit_tri.mesh',
prefix_dir=sfepy.data_dir)
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field = Field.from_args('linear', nm.float64, 'scalar', omega,
approx_order=1)
test = Test(conf=conf, options=options, omega=omega, field=field)
return test
def test_mass_matrix(self):
from sfepy.discrete.projections import create_mass_matrix
field = self.field
mtx = create_mass_matrix(field)
assert_(mtx.shape == (field.n_nod, field.n_nod))
assert_(abs(mtx.sum() - 1.0) < 1e-14)
return True
def test_projection_tri_quad(self):
from sfepy.discrete.projections import make_l2_projection
source = FieldVariable('us', 'unknown', self.field)
coors = self.field.get_coor()
vals = nm.sin(2.0 * nm.pi * coors[:,0] * coors[:,1])
source.set_data(vals)
name = op.join(self.options.out_dir,
'test_projection_tri_quad_source.vtk')
source.save_as_mesh(name)
mesh = Mesh.from_file('meshes/2d/square_quad.mesh',
prefix_dir=sfepy.data_dir)
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field = Field.from_args('bilinear', nm.float64, 'scalar', omega,
approx_order=1)
target = FieldVariable('ut', 'unknown', field)
make_l2_projection(target, source)
name = op.join(self.options.out_dir,
'test_projection_tri_quad_target.vtk')
target.save_as_mesh(name)
bbox = self.field.domain.get_mesh_bounding_box()
x = nm.linspace(bbox[0, 0] + 0.001, bbox[1, 0] - 0.001, 20)
y = nm.linspace(bbox[0, 1] + 0.001, bbox[1, 1] - 0.001, 20)
xx, yy = nm.meshgrid(x, y)
test_coors = nm.c_[xx.ravel(), yy.ravel()].copy()
vec1 = source.evaluate_at(test_coors)
vec2 = target.evaluate_at(test_coors)
ok = (nm.abs(vec1 - vec2) < 0.01).all()
return ok
def test_projection_iga_fem(self):
from sfepy.discrete import FieldVariable
from sfepy.discrete.fem import FEDomain, Field
from sfepy.discrete.iga.domain import IGDomain
from sfepy.mesh.mesh_generators import gen_block_mesh
from sfepy.discrete.iga.domain_generators import gen_patch_block_domain
from sfepy.discrete.projections import (make_l2_projection,
make_l2_projection_data)
shape = [10, 12, 12]
dims = [5, 6, 6]
centre = [0, 0, 0]
degrees = [2, 2, 2]
nurbs, bmesh, regions = gen_patch_block_domain(dims, shape, centre,
degrees,
cp_mode='greville',
name='iga')
ig_domain = IGDomain('iga', nurbs, bmesh, regions=regions)
ig_omega = ig_domain.create_region('Omega', 'all')
ig_field = Field.from_args('iga', nm.float64, 1, ig_omega,
approx_order='iga', poly_space_base='iga')
ig_u = FieldVariable('ig_u', 'parameter', ig_field,
primary_var_name='(set-to-None)')
mesh = gen_block_mesh(dims, shape, centre, name='fem')
fe_domain = FEDomain('fem', mesh)
fe_omega = fe_domain.create_region('Omega', 'all')
fe_field = Field.from_args('fem', nm.float64, 1, fe_omega,
approx_order=2)
fe_u = FieldVariable('fe_u', 'parameter', fe_field,
primary_var_name='(set-to-None)')
def _eval_data(ts, coors, mode, **kwargs):
return nm.prod(coors**2, axis=1)[:, None, None]
make_l2_projection_data(ig_u, _eval_data)
make_l2_projection(fe_u, ig_u) # This calls ig_u.evaluate_at().
coors = 0.5 * nm.random.rand(20, 3) * dims
ig_vals = ig_u.evaluate_at(coors)
fe_vals = fe_u.evaluate_at(coors)
ok = nm.allclose(ig_vals, fe_vals, rtol=0.0, atol=1e-12)
if not ok:
self.report('iga-fem projection failed!')
self.report('coors:')
self.report(coors)
self.report('iga fem diff:')
self.report(nm.c_[ig_vals, fe_vals, nm.abs(ig_vals - fe_vals)])
return ok
def test_project_tensors(self):
from sfepy.discrete import FieldVariable
from sfepy.discrete.projections import project_by_component
ok = True
u = FieldVariable('u', 'parameter', self.field,
primary_var_name='(set-to-None)')
u.set_constant(1.0)
component = FieldVariable('component', 'parameter', self.field,
primary_var_name='(set-to-None)')
nls_options = {'eps_a' : 1e-16, 'i_max' : 1}
u_qp = u.evaluate()
u2 = FieldVariable('u2', 'parameter', self.field,
primary_var_name='(set-to-None)')
project_by_component(u2, u_qp, component, self.field.approx_order,
nls_options=nls_options)
_ok = self.compare_vectors(u(), u2())
ok = ok and _ok
gu_qp = u.evaluate(mode='grad')
gfield = Field.from_args('gu', nm.float64, 2, self.field.region,
approx_order=self.field.approx_order)
gu = FieldVariable('gu', 'parameter', gfield,
primary_var_name='(set-to-None)')
project_by_component(gu, gu_qp, component, gfield.approx_order,
nls_options=nls_options)
_ok = self.compare_vectors(gu(), nm.zeros_like(gu()))
ok = ok and _ok
return ok
| [
"sfepy.mesh.mesh_generators.gen_block_mesh",
"sfepy.discrete.projections.make_l2_projection_data",
"sfepy.discrete.fem.Mesh.from_file",
"sfepy.discrete.iga.domain_generators.gen_patch_block_domain",
"sfepy.discrete.fem.Field.from_args",
"sfepy.discrete.fem.FEDomain",
"sfepy.base.base.assert_",
"sfepy.... | [((359, 434), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['"""meshes/2d/square_unit_tri.mesh"""'], {'prefix_dir': 'sfepy.data_dir'}), "('meshes/2d/square_unit_tri.mesh', prefix_dir=sfepy.data_dir)\n", (373, 434), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((482, 506), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""domain"""', 'mesh'], {}), "('domain', mesh)\n", (490, 506), False, 'from sfepy.discrete.fem import FEDomain, Field\n'), ((578, 648), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""linear"""', 'nm.float64', '"""scalar"""', 'omega'], {'approx_order': '(1)'}), "('linear', nm.float64, 'scalar', omega, approx_order=1)\n", (593, 648), False, 'from sfepy.discrete.fem import FEDomain, Field\n'), ((918, 943), 'sfepy.discrete.projections.create_mass_matrix', 'create_mass_matrix', (['field'], {}), '(field)\n', (936, 943), False, 'from sfepy.discrete.projections import create_mass_matrix\n'), ((953, 1001), 'sfepy.base.base.assert_', 'assert_', (['(mtx.shape == (field.n_nod, field.n_nod))'], {}), '(mtx.shape == (field.n_nod, field.n_nod))\n', (960, 1001), False, 'from sfepy.base.base import assert_\n'), ((1194, 1236), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""us"""', '"""unknown"""', 'self.field'], {}), "('us', 'unknown', self.field)\n", (1207, 1236), False, 'from sfepy.discrete import FieldVariable\n'), ((1291, 1338), 'numpy.sin', 'nm.sin', (['(2.0 * nm.pi * coors[:, 0] * coors[:, 1])'], {}), '(2.0 * nm.pi * coors[:, 0] * coors[:, 1])\n', (1297, 1338), True, 'import numpy as nm\n'), ((1383, 1451), 'os.path.join', 'op.join', (['self.options.out_dir', '"""test_projection_tri_quad_source.vtk"""'], {}), "(self.options.out_dir, 'test_projection_tri_quad_source.vtk')\n", (1390, 1451), True, 'import os.path as op\n'), ((1525, 1596), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['"""meshes/2d/square_quad.mesh"""'], {'prefix_dir': 'sfepy.data_dir'}), "('meshes/2d/square_quad.mesh', prefix_dir=sfepy.data_dir)\n", (1539, 1596), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1644, 1668), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""domain"""', 'mesh'], {}), "('domain', mesh)\n", (1652, 1668), False, 'from sfepy.discrete.fem import FEDomain, Field\n'), ((1741, 1813), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""bilinear"""', 'nm.float64', '"""scalar"""', 'omega'], {'approx_order': '(1)'}), "('bilinear', nm.float64, 'scalar', omega, approx_order=1)\n", (1756, 1813), False, 'from sfepy.discrete.fem import FEDomain, Field\n'), ((1864, 1901), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""ut"""', '"""unknown"""', 'field'], {}), "('ut', 'unknown', field)\n", (1877, 1901), False, 'from sfepy.discrete import FieldVariable\n'), ((1911, 1945), 'sfepy.discrete.projections.make_l2_projection', 'make_l2_projection', (['target', 'source'], {}), '(target, source)\n', (1929, 1945), False, 'from sfepy.discrete.projections import make_l2_projection, make_l2_projection_data\n'), ((1962, 2030), 'os.path.join', 'op.join', (['self.options.out_dir', '"""test_projection_tri_quad_target.vtk"""'], {}), "(self.options.out_dir, 'test_projection_tri_quad_target.vtk')\n", (1969, 2030), True, 'import os.path as op\n'), ((2158, 2213), 'numpy.linspace', 'nm.linspace', (['(bbox[0, 0] + 0.001)', '(bbox[1, 0] - 0.001)', '(20)'], {}), '(bbox[0, 0] + 0.001, bbox[1, 0] - 0.001, 20)\n', (2169, 2213), True, 'import numpy as nm\n'), ((2226, 2281), 'numpy.linspace', 'nm.linspace', (['(bbox[0, 1] + 0.001)', '(bbox[1, 1] - 0.001)', '(20)'], {}), '(bbox[0, 1] + 0.001, bbox[1, 1] - 0.001, 20)\n', (2237, 2281), True, 'import numpy as nm\n'), ((2300, 2317), 'numpy.meshgrid', 'nm.meshgrid', (['x', 'y'], {}), '(x, y)\n', (2311, 2317), True, 'import numpy as nm\n'), ((3162, 3250), 'sfepy.discrete.iga.domain_generators.gen_patch_block_domain', 'gen_patch_block_domain', (['dims', 'shape', 'centre', 'degrees'], {'cp_mode': '"""greville"""', 'name': '"""iga"""'}), "(dims, shape, centre, degrees, cp_mode='greville',\n name='iga')\n", (3184, 3250), False, 'from sfepy.discrete.iga.domain_generators import gen_patch_block_domain\n'), ((3432, 3478), 'sfepy.discrete.iga.domain.IGDomain', 'IGDomain', (['"""iga"""', 'nurbs', 'bmesh'], {'regions': 'regions'}), "('iga', nurbs, bmesh, regions=regions)\n", (3440, 3478), False, 'from sfepy.discrete.iga.domain import IGDomain\n'), ((3558, 3652), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""iga"""', 'nm.float64', '(1)', 'ig_omega'], {'approx_order': '"""iga"""', 'poly_space_base': '"""iga"""'}), "('iga', nm.float64, 1, ig_omega, approx_order='iga',\n poly_space_base='iga')\n", (3573, 3652), False, 'from sfepy.discrete.fem import FEDomain, Field\n'), ((3699, 3777), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""ig_u"""', '"""parameter"""', 'ig_field'], {'primary_var_name': '"""(set-to-None)"""'}), "('ig_u', 'parameter', ig_field, primary_var_name='(set-to-None)')\n", (3712, 3777), False, 'from sfepy.discrete import FieldVariable\n'), ((3823, 3870), 'sfepy.mesh.mesh_generators.gen_block_mesh', 'gen_block_mesh', (['dims', 'shape', 'centre'], {'name': '"""fem"""'}), "(dims, shape, centre, name='fem')\n", (3837, 3870), False, 'from sfepy.mesh.mesh_generators import gen_block_mesh\n'), ((3891, 3912), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""fem"""', 'mesh'], {}), "('fem', mesh)\n", (3899, 3912), False, 'from sfepy.discrete.fem import FEDomain, Field\n'), ((3992, 4055), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""fem"""', 'nm.float64', '(1)', 'fe_omega'], {'approx_order': '(2)'}), "('fem', nm.float64, 1, fe_omega, approx_order=2)\n", (4007, 4055), False, 'from sfepy.discrete.fem import FEDomain, Field\n'), ((4106, 4184), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""fe_u"""', '"""parameter"""', 'fe_field'], {'primary_var_name': '"""(set-to-None)"""'}), "('fe_u', 'parameter', fe_field, primary_var_name='(set-to-None)')\n", (4119, 4184), False, 'from sfepy.discrete import FieldVariable\n'), ((4335, 4376), 'sfepy.discrete.projections.make_l2_projection_data', 'make_l2_projection_data', (['ig_u', '_eval_data'], {}), '(ig_u, _eval_data)\n', (4358, 4376), False, 'from sfepy.discrete.projections import make_l2_projection, make_l2_projection_data\n'), ((4386, 4416), 'sfepy.discrete.projections.make_l2_projection', 'make_l2_projection', (['fe_u', 'ig_u'], {}), '(fe_u, ig_u)\n', (4404, 4416), False, 'from sfepy.discrete.projections import make_l2_projection, make_l2_projection_data\n'), ((4601, 4652), 'numpy.allclose', 'nm.allclose', (['ig_vals', 'fe_vals'], {'rtol': '(0.0)', 'atol': '(1e-12)'}), '(ig_vals, fe_vals, rtol=0.0, atol=1e-12)\n', (4612, 4652), True, 'import numpy as nm\n'), ((5113, 5190), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""u"""', '"""parameter"""', 'self.field'], {'primary_var_name': '"""(set-to-None)"""'}), "('u', 'parameter', self.field, primary_var_name='(set-to-None)')\n", (5126, 5190), False, 'from sfepy.discrete import FieldVariable\n'), ((5266, 5356), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""component"""', '"""parameter"""', 'self.field'], {'primary_var_name': '"""(set-to-None)"""'}), "('component', 'parameter', self.field, primary_var_name=\n '(set-to-None)')\n", (5279, 5356), False, 'from sfepy.discrete import FieldVariable\n'), ((5482, 5560), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""u2"""', '"""parameter"""', 'self.field'], {'primary_var_name': '"""(set-to-None)"""'}), "('u2', 'parameter', self.field, primary_var_name='(set-to-None)')\n", (5495, 5560), False, 'from sfepy.discrete import FieldVariable\n'), ((5596, 5691), 'sfepy.discrete.projections.project_by_component', 'project_by_component', (['u2', 'u_qp', 'component', 'self.field.approx_order'], {'nls_options': 'nls_options'}), '(u2, u_qp, component, self.field.approx_order,\n nls_options=nls_options)\n', (5616, 5691), False, 'from sfepy.discrete.projections import project_by_component\n'), ((5847, 5945), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""gu"""', 'nm.float64', '(2)', 'self.field.region'], {'approx_order': 'self.field.approx_order'}), "('gu', nm.float64, 2, self.field.region, approx_order=self.\n field.approx_order)\n", (5862, 5945), False, 'from sfepy.discrete.fem import FEDomain, Field\n'), ((5987, 6061), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""gu"""', '"""parameter"""', 'gfield'], {'primary_var_name': '"""(set-to-None)"""'}), "('gu', 'parameter', gfield, primary_var_name='(set-to-None)')\n", (6000, 6061), False, 'from sfepy.discrete import FieldVariable\n'), ((6098, 6191), 'sfepy.discrete.projections.project_by_component', 'project_by_component', (['gu', 'gu_qp', 'component', 'gfield.approx_order'], {'nls_options': 'nls_options'}), '(gu, gu_qp, component, gfield.approx_order, nls_options\n =nls_options)\n', (6118, 6191), False, 'from sfepy.discrete.projections import project_by_component\n'), ((4285, 4312), 'numpy.prod', 'nm.prod', (['(coors ** 2)'], {'axis': '(1)'}), '(coors ** 2, axis=1)\n', (4292, 4312), True, 'import numpy as nm\n'), ((4473, 4494), 'numpy.random.rand', 'nm.random.rand', (['(20)', '(3)'], {}), '(20, 3)\n', (4487, 4494), True, 'import numpy as nm\n'), ((2484, 2503), 'numpy.abs', 'nm.abs', (['(vec1 - vec2)'], {}), '(vec1 - vec2)\n', (2490, 2503), True, 'import numpy as nm\n'), ((4880, 4905), 'numpy.abs', 'nm.abs', (['(ig_vals - fe_vals)'], {}), '(ig_vals - fe_vals)\n', (4886, 4905), True, 'import numpy as nm\n')] |
# Vibroacoustics
#
# E.Rohan, V.Lukeš
# Homogenization of the vibro–acoustic transmission on periodically
# perforated elastic plates with arrays of resonators.
# https://arxiv.org/abs/2104.01367 (arXiv:2104.01367v1)
import os.path as op
import numpy as nm
from collections.abc import Iterable
from scipy.io import savemat, loadmat
from sfepy.base.base import output, debug, Struct
from sfepy import data_dir
from sfepy.discrete.fem.periodic import match_y_plane, match_x_plane
from acoustics_macro_utils import eval_phi, post_process,\
generate_plate_mesh, get_region_entities
from sfepy.discrete.projections import project_by_component
from sfepy.discrete.fem import Mesh, FEDomain
wdir = op.dirname(__file__)
def post_process_macro(out, pb, state, extend=False):
pbvars = pb.get_variables()
n1, ng1, c1, cg1, ds1, nmap1 = get_region_entities(pbvars['p1'])
noff = n1.shape[0]
n2, ng2, c2, cg2, _, nmap2 = get_region_entities(pbvars['p2'], noff=noff)
nend = nm.max(c2) + 1
nmap = nm.hstack([nmap1, nmap2])
n1[:, 2] += pb.conf.eps0 * 0.5
n2[:, 2] -= pb.conf.eps0 * 0.5
mesh2 = Mesh.from_data('m2', nm.vstack([n1, n2]), nm.hstack([ng1, ng2]),
[nm.vstack([c1, c2])], [nm.hstack([cg1, cg2])],
[ds1])
oname = op.join(pb.output_dir, pb.ofn_trunk + '_p.vtk')
out2 = {}
for ir in ['real.', 'imag.']:
pdata = nm.zeros((nmap.shape[0], 1), dtype=nm.float64)
for v, idxs in [('p1', slice(0, noff)), ('p2', slice(noff, nend))]:
pdata[idxs, :] = out[ir + v].data
out2[ir + 'p'] = Struct(name='p', mode='vertex', data=pdata)
mesh2.write(oname, out=out2)
post_process(out, pb, state, save_var0='dp0')
for k1 in ['g01', 'imag.g01', 'real.g01']:
o = out[k1]
k0 = k1.replace('01', '0')
k2 = k1.replace('01', '02')
out[k0] = Struct(name=o.name,
mode=o.mode,
dofs=o.dofs,
var_name=o.var_name,
data=(out[k1].data - out[k2].data) / pb.conf.eps0)
for k in ['', 'imag.', 'real.']:
o = out[k + 'dp0']
k0 = k + 'jP1'
out[k0] = Struct(name=o.name,
mode=o.mode,
dofs=o.dofs,
var_name=o.var_name,
data=o.data / pb.conf.eps0)
o = out[k + 'g01']
o2 = out[k + 'g02']
out[k + 'G1'] = Struct(name=o.name,
mode=o.mode,
dofs=o.dofs,
var_name=o.var_name,
data=(o.data - o2.data) / pb.conf.eps0)
return out
def get_mat(coors, mode, pb):
if mode == 'qp':
conf = pb.conf
c = conf.sound_speed
w = conf.wave_num * c
nqp = coors.shape[0]
aux = nm.ones((nqp, 1, 1), dtype=nm.float64)
out = {
'c2': aux * c**2,
'w2': aux * w**2,
'wc': aux * w * c,
'wc2': aux * w * c**2,
}
print('### material: wave number = ', conf.wave_num)
return out
def param_w(pb):
out = []
tl_out = []
conf = pb.conf
ofn_trunk = pb.ofn_trunk
for k in conf.wave_nums:
print('### wave number: ', k)
conf.wave_num = k
pb.ofn_trunk = ofn_trunk + '_w%d' % (k * pb.conf.sound_speed)
pb.conf.ofn_trunk = pb.ofn_trunk
yield pb, out
state = out[-1][1].get_parts()
tl_out.append(eval_phi(pb, state['p1'], state['p2'], conf.p_inc))
print('>>> TL: ', tl_out[-1])
yield None
savemat(op.join(wdir, 'results', 'tloss.mat'), {'k': conf.wave_nums, 'tl': tl_out})
############################################################
def define(filename_mesh=None, sound_speed=None, rho0=None,
freqs=None, p_inc=None, eps0=None,
coefs_filename=None, coefs_filename_plate=None):
# generate mid mesh
filename_mesh_plate = generate_plate_mesh(op.join(wdir, filename_mesh))
wave_num = nm.array(freqs) / sound_speed
wave_nums, wave_num = wave_num, wave_num[0]
regions = {
'Omega1': 'cells of group 1',
'Omega2': 'cells of group 2',
'GammaIn': ('vertices of group 1', 'facet'),
'GammaOut': ('vertices of group 2', 'facet'),
'Gamma_aux': ('r.Omega1 *v r.Omega2', 'facet'),
'Gamma0_1': ('copy r.Gamma_aux', 'facet', 'Omega1'),
'Gamma0_2': ('copy r.Gamma_aux', 'facet', 'Omega2'),
'Recovery': ('copy r.Gamma0_1', 'facet'),
}
fields = {
'pressure1': ('complex', 'scalar', 'Omega1', 1),
'pressure2': ('complex', 'scalar', 'Omega2', 1),
'tvelocity0': ('complex', 'scalar', 'Gamma0_1', 1),
'pressure0': ('complex', 'scalar', 'Gamma0_1', 1),
'vfield1': ('complex', 'vector', 'Omega1', 1),
'vfield2': ('complex', 'vector', 'Omega2', 1),
}
variables = {
'p1': ('unknown field', 'pressure1', 0),
'q1': ('test field', 'pressure1', 'p1'),
'p2': ('unknown field', 'pressure2', 1),
'q2': ('test field', 'pressure2', 'p2'),
'sp0': ('unknown field', 'pressure0', 2),
'sq0': ('test field', 'pressure0', 'sp0'),
'dp0': ('unknown field', 'pressure0', 3),
'dq0': ('test field', 'pressure0', 'dp0'),
'g01': ('unknown field', 'tvelocity0', 4),
'f01': ('test field', 'tvelocity0', 'g01'),
'g02': ('unknown field', 'tvelocity0', 5),
'f02': ('test field', 'tvelocity0', 'g02'),
'P1': ('parameter field', 'pressure1', '(set-to-None)'),
'P2': ('parameter field', 'pressure2', '(set-to-None)'),
's1': ('parameter field', 'pressure1', '(set-to-None)'),
's2': ('parameter field', 'pressure2', '(set-to-None)'),
'v1': ('parameter field', 'vfield1', '(set-to-None)'),
'v2': ('parameter field', 'vfield2', '(set-to-None)'),
}
integrals = {
'i': 2,
}
ebcs = {}
functions = {
'get_mat': (lambda ts, coors, mode=None, problem=None, **kwargs:
get_mat(coors, mode, problem),),
'match_y_plane': (match_y_plane,),
}
materials = {
'ac': 'get_mat',
}
regions.update({
'Near': ('vertices of group 3', 'facet'),
'Far': ('vertices of group 4', 'facet'),
})
epbcs = {
'per_p1': (['Near', 'Far'], {'p1.0': 'p1.0'}, 'match_y_plane'),
'per_p2': (['Near', 'Far'], {'p2.0': 'p2.0'}, 'match_y_plane'),
}
options = {
'output_dir': op.join(wdir, 'results'),
'file_per_var': True,
'post_process_hook': 'post_process_macro',
'parametric_hook': 'param_w',
}
# p1 = P^+, p2 = P^-
equations = {
'eq_p1': """
dw_laplace.i.Omega1(ac.c2, q1, p1)
- dw_volume_dot.i.Omega1(ac.w2, q1, p1)
+ %s * dw_surface_dot.i.GammaOut(ac.wc, q1, p1)
- %s * dw_surface_dot.i.Gamma0_1(ac.wc2, q1, g01)
= 0""" % (1j, 1j),
'eq_p2': """
dw_laplace.i.Omega2(ac.c2, q2, p2)
- dw_volume_dot.i.Omega2(ac.w2, q2, p2)
+ %s * dw_surface_dot.i.GammaIn(ac.wc, q2, p2)
+ %s * dw_surface_dot.i.Gamma0_2(ac.wc2, q2, tr(g02))
= %s * dw_surface_integrate.i.GammaIn(ac.wc, q2)"""
% (1j, 1j, 2j * p_inc),
'eq_dp': """
dw_surface_dot.i.Gamma0_1(dq0, p1)
- dw_surface_dot.i.Gamma0_1(dq0, tr(p2))
- dw_surface_dot.i.Gamma0_1(dq0, dp0)
= 0""",
'eq_sp': """
dw_surface_dot.i.Gamma0_1(sq0, p1)
+ dw_surface_dot.i.Gamma0_1(sq0, tr(p2))
- dw_surface_dot.i.Gamma0_1(sq0, sp0)
= 0""",
}
solvers = {
'nls': ('nls.newton', {'i_max': 1,
'eps_a': 1e-6,
'eps_r': 1e-6,
'problem': 'nonlinear', })
}
mid_file = op.join(wdir, 'acoustics_macro_plate.py')
solvers.update({
'ls': ('ls.cm_pb',
{'others': [mid_file],
'coupling_variables': ['g01', 'g02', 'dp0', 'sp0'],
'needs_problem_instance': True,
})
})
return locals()
| [
"sfepy.base.base.Struct"
] | [((697, 717), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (707, 717), True, 'import os.path as op\n'), ((842, 875), 'acoustics_macro_utils.get_region_entities', 'get_region_entities', (["pbvars['p1']"], {}), "(pbvars['p1'])\n", (861, 875), False, 'from acoustics_macro_utils import eval_phi, post_process, generate_plate_mesh, get_region_entities\n'), ((932, 976), 'acoustics_macro_utils.get_region_entities', 'get_region_entities', (["pbvars['p2']"], {'noff': 'noff'}), "(pbvars['p2'], noff=noff)\n", (951, 976), False, 'from acoustics_macro_utils import eval_phi, post_process, generate_plate_mesh, get_region_entities\n'), ((1014, 1039), 'numpy.hstack', 'nm.hstack', (['[nmap1, nmap2]'], {}), '([nmap1, nmap2])\n', (1023, 1039), True, 'import numpy as nm\n'), ((1310, 1357), 'os.path.join', 'op.join', (['pb.output_dir', "(pb.ofn_trunk + '_p.vtk')"], {}), "(pb.output_dir, pb.ofn_trunk + '_p.vtk')\n", (1317, 1357), True, 'import os.path as op\n'), ((1701, 1746), 'acoustics_macro_utils.post_process', 'post_process', (['out', 'pb', 'state'], {'save_var0': '"""dp0"""'}), "(out, pb, state, save_var0='dp0')\n", (1713, 1746), False, 'from acoustics_macro_utils import eval_phi, post_process, generate_plate_mesh, get_region_entities\n'), ((8070, 8111), 'os.path.join', 'op.join', (['wdir', '"""acoustics_macro_plate.py"""'], {}), "(wdir, 'acoustics_macro_plate.py')\n", (8077, 8111), True, 'import os.path as op\n'), ((988, 998), 'numpy.max', 'nm.max', (['c2'], {}), '(c2)\n', (994, 998), True, 'import numpy as nm\n'), ((1144, 1163), 'numpy.vstack', 'nm.vstack', (['[n1, n2]'], {}), '([n1, n2])\n', (1153, 1163), True, 'import numpy as nm\n'), ((1165, 1186), 'numpy.hstack', 'nm.hstack', (['[ng1, ng2]'], {}), '([ng1, ng2])\n', (1174, 1186), True, 'import numpy as nm\n'), ((1423, 1469), 'numpy.zeros', 'nm.zeros', (['(nmap.shape[0], 1)'], {'dtype': 'nm.float64'}), '((nmap.shape[0], 1), dtype=nm.float64)\n', (1431, 1469), True, 'import numpy as nm\n'), ((1618, 1661), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""p"""', 'mode': '"""vertex"""', 'data': 'pdata'}), "(name='p', mode='vertex', data=pdata)\n", (1624, 1661), False, 'from sfepy.base.base import output, debug, Struct\n'), ((1904, 2026), 'sfepy.base.base.Struct', 'Struct', ([], {'name': 'o.name', 'mode': 'o.mode', 'dofs': 'o.dofs', 'var_name': 'o.var_name', 'data': '((out[k1].data - out[k2].data) / pb.conf.eps0)'}), '(name=o.name, mode=o.mode, dofs=o.dofs, var_name=o.var_name, data=(\n out[k1].data - out[k2].data) / pb.conf.eps0)\n', (1910, 2026), False, 'from sfepy.base.base import output, debug, Struct\n'), ((2228, 2327), 'sfepy.base.base.Struct', 'Struct', ([], {'name': 'o.name', 'mode': 'o.mode', 'dofs': 'o.dofs', 'var_name': 'o.var_name', 'data': '(o.data / pb.conf.eps0)'}), '(name=o.name, mode=o.mode, dofs=o.dofs, var_name=o.var_name, data=o.\n data / pb.conf.eps0)\n', (2234, 2327), False, 'from sfepy.base.base import output, debug, Struct\n'), ((2503, 2614), 'sfepy.base.base.Struct', 'Struct', ([], {'name': 'o.name', 'mode': 'o.mode', 'dofs': 'o.dofs', 'var_name': 'o.var_name', 'data': '((o.data - o2.data) / pb.conf.eps0)'}), '(name=o.name, mode=o.mode, dofs=o.dofs, var_name=o.var_name, data=(o.\n data - o2.data) / pb.conf.eps0)\n', (2509, 2614), False, 'from sfepy.base.base import output, debug, Struct\n'), ((2928, 2966), 'numpy.ones', 'nm.ones', (['(nqp, 1, 1)'], {'dtype': 'nm.float64'}), '((nqp, 1, 1), dtype=nm.float64)\n', (2935, 2966), True, 'import numpy as nm\n'), ((3711, 3748), 'os.path.join', 'op.join', (['wdir', '"""results"""', '"""tloss.mat"""'], {}), "(wdir, 'results', 'tloss.mat')\n", (3718, 3748), True, 'import os.path as op\n'), ((4087, 4115), 'os.path.join', 'op.join', (['wdir', 'filename_mesh'], {}), '(wdir, filename_mesh)\n', (4094, 4115), True, 'import os.path as op\n'), ((4132, 4147), 'numpy.array', 'nm.array', (['freqs'], {}), '(freqs)\n', (4140, 4147), True, 'import numpy as nm\n'), ((6659, 6683), 'os.path.join', 'op.join', (['wdir', '"""results"""'], {}), "(wdir, 'results')\n", (6666, 6683), True, 'import os.path as op\n'), ((1216, 1235), 'numpy.vstack', 'nm.vstack', (['[c1, c2]'], {}), '([c1, c2])\n', (1225, 1235), True, 'import numpy as nm\n'), ((1239, 1260), 'numpy.hstack', 'nm.hstack', (['[cg1, cg2]'], {}), '([cg1, cg2])\n', (1248, 1260), True, 'import numpy as nm\n'), ((3588, 3638), 'acoustics_macro_utils.eval_phi', 'eval_phi', (['pb', "state['p1']", "state['p2']", 'conf.p_inc'], {}), "(pb, state['p1'], state['p2'], conf.p_inc)\n", (3596, 3638), False, 'from acoustics_macro_utils import eval_phi, post_process, generate_plate_mesh, get_region_entities\n')] |
#!/usr/bin/env python
"""
First solve the stationary electric conduction problem. Then use its
results to solve the evolutionary heat conduction problem.
Run this example as on a command line::
$ python <path_to_this_file>/thermal_electric.py
"""
from __future__ import absolute_import
import sys
sys.path.append( '.' )
import os
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/2d/special/circle_in_square.mesh'
# Time stepping for the heat conduction problem.
t0 = 0.0
t1 = 0.5
n_step = 11
# Material parameters.
specific_heat = 1.2
##########
cwd = os.path.split(os.path.join(os.getcwd(), __file__))[0]
options = {
'absolute_mesh_path' : True,
'output_dir' : os.path.join(cwd, 'output')
}
regions = {
'Omega' : 'all',
'Omega1' : 'cells of group 1',
'Omega2' : 'cells of group 2',
'Omega2_Surface': ('r.Omega1 *v r.Omega2', 'facet'),
'Left' : ('vertices in (x < %f)' % -0.4999, 'facet'),
'Right' : ('vertices in (x > %f)' % 0.4999, 'facet'),
}
materials = {
'm' : ({
'thermal_conductivity' : 2.0,
'electric_conductivity' : 1.5,
},),
}
# The fields use the same approximation, so a single field could be used
# instead.
fields = {
'temperature': ('real', 1, 'Omega', 1),
'potential' : ('real', 1, 'Omega', 1),
}
variables = {
'T' : ('unknown field', 'temperature', 0, 1),
's' : ('test field', 'temperature', 'T'),
'phi' : ('unknown field', 'potential', 1),
'psi' : ('test field', 'potential', 'phi'),
'phi_known' : ('parameter field', 'potential', '(set-to-None)'),
}
ics = {
'ic' : ('Omega', {'T.0' : 0.0}),
}
ebcs = {
'left' : ('Left', {'T.0' : 0.0, 'phi.0' : 0.0}),
'right' : ('Right', {'T.0' : 2.0, 'phi.0' : 0.0}),
'inside' : ('Omega2_Surface', {'phi.0' : 'set_electric_bc'}),
}
def set_electric_bc(coor):
y = coor[:,1]
ymin, ymax = y.min(), y.max()
val = 2.0 * (((y - ymin) / (ymax - ymin)) - 0.5)
return val
functions = {
'set_electric_bc' : (lambda ts, coor, bc, problem, **kwargs:
set_electric_bc(coor),),
}
equations = {
'2' : """%.12e * dw_volume_dot.2.Omega( s, dT/dt )
+ dw_laplace.2.Omega( m.thermal_conductivity, s, T )
= dw_electric_source.2.Omega( m.electric_conductivity,
s, phi_known ) """ % specific_heat,
'1' : """dw_laplace.2.Omega( m.electric_conductivity, psi, phi ) = 0""",
}
solvers = {
'ls' : ('ls.scipy_direct', {}),
'newton' : ('nls.newton', {
'i_max' : 1,
'eps_a' : 1e-10,
'problem' : 'nonlinear',
}),
'ts' : ('ts.simple', {
't0' : t0,
't1' : t1,
'dt' : None,
'n_step' : n_step, # has precedence over dt!
}),
}
def main():
from sfepy.base.base import output
from sfepy.base.conf import ProblemConf, get_standard_keywords
from sfepy.discrete import Problem
output.prefix = 'therel:'
required, other = get_standard_keywords()
conf = ProblemConf.from_file(__file__, required, other)
problem = Problem.from_conf(conf, init_equations=False)
# Setup output directory according to options above.
problem.setup_default_output()
# First solve the stationary electric conduction problem.
problem.set_equations({'eq' : conf.equations['1']})
problem.time_update()
state_el = problem.solve()
problem.save_state(problem.get_output_name(suffix = 'el'), state_el)
# Then solve the evolutionary heat conduction problem, using state_el.
problem.set_equations({'eq' : conf.equations['2']})
phi_var = problem.get_variables()['phi_known']
phi_var.set_data(state_el())
time_solver = problem.get_time_solver()
time_solver.init_time()
for _ in time_solver():
pass
output('results saved in %s' % problem.get_output_name(suffix = '*'))
if __name__ == '__main__':
main()
| [
"sfepy.discrete.Problem.from_conf",
"sfepy.base.conf.ProblemConf.from_file",
"sfepy.base.conf.get_standard_keywords"
] | [((303, 323), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (318, 323), False, 'import sys\n'), ((697, 724), 'os.path.join', 'os.path.join', (['cwd', '"""output"""'], {}), "(cwd, 'output')\n", (709, 724), False, 'import os\n'), ((3013, 3036), 'sfepy.base.conf.get_standard_keywords', 'get_standard_keywords', ([], {}), '()\n', (3034, 3036), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((3048, 3096), 'sfepy.base.conf.ProblemConf.from_file', 'ProblemConf.from_file', (['__file__', 'required', 'other'], {}), '(__file__, required, other)\n', (3069, 3096), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((3112, 3157), 'sfepy.discrete.Problem.from_conf', 'Problem.from_conf', (['conf'], {'init_equations': '(False)'}), '(conf, init_equations=False)\n', (3129, 3157), False, 'from sfepy.discrete import Problem\n'), ((605, 616), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (614, 616), False, 'import os\n')] |
#!/usr/bin/env python
"""
Plot quadrature points for the given geometry and integration order.
"""
from __future__ import absolute_import, print_function
import sys
sys.path.append('.')
from argparse import ArgumentParser
import sfepy.postprocess.plot_quadrature as pq
helps = {
'geometry' :
'reference element geometry, one of "2_3", "2_4", "3_4", "3_8"'
' [default: %(default)s]',
'order' :
'quadrature order [default: %(default)s]',
'boundary' :
'plot boundary quadrature points',
'min_radius' :
'min. radius of points corresponding to the min. weight'
' [default: %(default)s]',
'max_radius' :
'max. radius of points corresponding to the max. weight'
' [default: %(default)s]',
'show_colorbar' :
'show colorbar for quadrature weights',
'show_labels' :
'label quadrature points',
'print_qp' :
'print quadrature points and weights',
}
def main():
parser = ArgumentParser(description=__doc__)
parser.add_argument('--version', action='version', version='%(prog)s')
parser.add_argument('-g', '--geometry', metavar='name',
action='store', dest='geometry',
default='2_4', help=helps['geometry'])
parser.add_argument('-n', '--order', metavar='order', type=int,
action='store', dest='order',
default=2, help=helps['order'])
parser.add_argument('-b', '--boundary',
action='store_true', dest='boundary',
default=False, help=helps['boundary'])
parser.add_argument('-r', '--min-radius', metavar='float', type=float,
action='store', dest='min_radius',
default=10, help=helps['min_radius'])
parser.add_argument('-R', '--max-radius', metavar='float', type=float,
action='store', dest='max_radius',
default=50, help=helps['max_radius'])
parser.add_argument('-c', '--show-colorbar',
action='store_true', dest='show_colorbar',
default=False, help=helps['show_colorbar'])
parser.add_argument('-l', '---show-labels',
action='store_true', dest='show_labels',
default=False, help=helps['show_labels'])
parser.add_argument('-p', '--print-qp',
action='store_true', dest='print_qp',
default=False, help=helps['print_qp'])
options = parser.parse_args()
aux = pq.plot_quadrature(None, options.geometry, options.order,
boundary=options.boundary,
min_radius=options.min_radius,
max_radius=options.max_radius,
show_colorbar=options.show_colorbar,
show_labels=options.show_labels)
if options.print_qp:
ax, coors, weights = aux
for ic, coor in enumerate(coors):
print(ic, coor, weights[ic])
pq.plt.show()
if __name__ == '__main__':
main()
| [
"sfepy.postprocess.plot_quadrature.plt.show",
"sfepy.postprocess.plot_quadrature.plot_quadrature"
] | [((165, 185), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (180, 185), False, 'import sys\n'), ((943, 978), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (957, 978), False, 'from argparse import ArgumentParser\n'), ((2550, 2775), 'sfepy.postprocess.plot_quadrature.plot_quadrature', 'pq.plot_quadrature', (['None', 'options.geometry', 'options.order'], {'boundary': 'options.boundary', 'min_radius': 'options.min_radius', 'max_radius': 'options.max_radius', 'show_colorbar': 'options.show_colorbar', 'show_labels': 'options.show_labels'}), '(None, options.geometry, options.order, boundary=options.\n boundary, min_radius=options.min_radius, max_radius=options.max_radius,\n show_colorbar=options.show_colorbar, show_labels=options.show_labels)\n', (2568, 2775), True, 'import sfepy.postprocess.plot_quadrature as pq\n'), ((3059, 3072), 'sfepy.postprocess.plot_quadrature.plt.show', 'pq.plt.show', ([], {}), '()\n', (3070, 3072), True, 'import sfepy.postprocess.plot_quadrature as pq\n')] |
#!/usr/bin/env python
"""
Plot quadrature points for the given geometry and integration order.
"""
from optparse import OptionParser
import sfepy.postprocess.plot_quadrature as pq
usage = '%prog [options]\n' + __doc__.rstrip()
helps = {
'geometry' :
'reference element geometry, one of "2_3", "2_4", "3_4", "3_8"'
' [default: %default]',
'order' :
'quadrature order [default: %default]',
'min_radius' :
'min. radius of points corresponding to the min. weight'
' [default: %default]',
'max_radius' :
'max. radius of points corresponding to the max. weight'
' [default: %default]',
'show_colorbar' :
'show colorbar for quadrature weights'
}
def main():
parser = OptionParser(usage=usage, version='%prog')
parser.add_option('-g', '--geometry', metavar='name',
action='store', dest='geometry',
default='2_4', help=helps['geometry'])
parser.add_option('-n', '--order', metavar='order', type=int,
action='store', dest='order',
default=2, help=helps['order'])
parser.add_option('-r', '--min-radius', metavar='float', type=float,
action='store', dest='min_radius',
default=10, help=helps['min_radius'])
parser.add_option('-R', '--max-radius', metavar='float', type=float,
action='store', dest='max_radius',
default=50, help=helps['max_radius'])
parser.add_option('-c', '--show-colorbar',
action='store_true', dest='show_colorbar',
default=False, help=helps['show_colorbar'])
options, args = parser.parse_args()
if len(args) != 0:
parser.print_help(),
return
pq.plot_quadrature(None, options.geometry, options.order,
options.min_radius, options.max_radius,
options.show_colorbar)
pq.plt.show()
if __name__ == '__main__':
main()
| [
"sfepy.postprocess.plot_quadrature.plt.show",
"sfepy.postprocess.plot_quadrature.plot_quadrature"
] | [((722, 764), 'optparse.OptionParser', 'OptionParser', ([], {'usage': 'usage', 'version': '"""%prog"""'}), "(usage=usage, version='%prog')\n", (734, 764), False, 'from optparse import OptionParser\n'), ((1782, 1907), 'sfepy.postprocess.plot_quadrature.plot_quadrature', 'pq.plot_quadrature', (['None', 'options.geometry', 'options.order', 'options.min_radius', 'options.max_radius', 'options.show_colorbar'], {}), '(None, options.geometry, options.order, options.\n min_radius, options.max_radius, options.show_colorbar)\n', (1800, 1907), True, 'import sfepy.postprocess.plot_quadrature as pq\n'), ((1953, 1966), 'sfepy.postprocess.plot_quadrature.plt.show', 'pq.plt.show', ([], {}), '()\n', (1964, 1966), True, 'import sfepy.postprocess.plot_quadrature as pq\n')] |
"""
The Dirichlet, periodic and linear combination boundary condition
classes, as well as the initial condition class.
"""
from __future__ import absolute_import
import numpy as nm
from sfepy.base.base import basestr, Container, Struct
from sfepy.discrete.functions import Function
import six
def get_condition_value(val, functions, kind, name):
"""
Check a boundary/initial condition value type and return the value or
corresponding function.
"""
if type(val) == str:
if functions is not None:
try:
fun = functions[val]
except IndexError:
raise ValueError('unknown function %s given for %s %s!'
% (val, kind, name))
else:
raise ValueError('no functions given for %s %s!' % (kind, name))
elif (isinstance(val, Function) or nm.isscalar(val)
or isinstance(val, nm.ndarray)):
fun = val
else:
raise ValueError('unknown value type for %s %s!'
% (kind, name))
return fun
def _get_region(name, regions, bc_name):
try:
region = regions[name]
except IndexError:
msg = "no region '%s' used in condition %s!" % (name, bc_name)
raise IndexError(msg)
return region
class Conditions(Container):
"""
Container for various conditions.
"""
@staticmethod
def from_conf(conf, regions):
conds = []
for key, cc in six.iteritems(conf):
times = cc.get('times', None)
if 'ebc' in key:
region = _get_region(cc.region, regions, cc.name)
cond = EssentialBC(cc.name, region, cc.dofs, key=key,
times=times)
elif 'epbc' in key:
rs = [_get_region(ii, regions, cc.name) for ii in cc.region]
cond = PeriodicBC(cc.name, rs, cc.dofs, cc.match, key=key,
times=times)
elif 'lcbc' in key:
if isinstance(cc.region, basestr):
rs = [_get_region(cc.region, regions, cc.name), None]
else:
rs = [_get_region(ii, regions, cc.name)
for ii in cc.region]
cond = LinearCombinationBC(cc.name, rs, cc.dofs,
cc.dof_map_fun, cc.kind,
key=key,
times=times,
arguments=cc.get('arguments', None))
elif 'ic' in key:
region = _get_region(cc.region, regions, cc.name)
cond = InitialCondition(cc.name, region, cc.dofs, key=key)
else:
raise ValueError('unknown condition type! (%s)' % key)
conds.append(cond)
obj = Conditions(conds)
return obj
def group_by_variables(self, groups=None):
"""
Group boundary conditions of each variable. Each condition is a
group is a single condition.
Parameters
----------
groups : dict, optional
If present, update the `groups` dictionary.
Returns
-------
out : dict
The dictionary with variable names as keys and lists of
single condition instances as values.
"""
if groups is None:
out = {}
else:
out = groups
for cond in self:
for single_cond in cond.iter_single():
vname = single_cond.dofs[0].split('.')[0]
out.setdefault(vname, Conditions()).append(single_cond)
return out
def canonize_dof_names(self, dofs):
"""
Canonize the DOF names using the full list of DOFs of a
variable.
"""
for cond in self:
cond.canonize_dof_names(dofs)
def sort(self):
"""
Sort boundary conditions by their key.
"""
self._objs.sort(key=lambda a: a.key)
self.update()
def zero_dofs(self):
"""
Set all boundary condition values to zero, if applicable.
"""
for cond in self:
if isinstance(cond, EssentialBC):
cond.zero_dofs()
def _canonize(dofs, all_dofs):
"""
Helper function.
"""
vname, dd = dofs.split('.')
if dd == 'all':
cdofs = all_dofs
elif dd[0] == '[':
cdofs = [vname + '.' + ii.strip()
for ii in dd[1:-1].split(',')]
else:
cdofs = [dofs]
return cdofs
class Condition(Struct):
"""
Common boundary condition methods.
"""
def __init__(self, name, **kwargs):
Struct.__init__(self, name=name, **kwargs)
self.is_single = False
def iter_single(self):
"""
Create a single condition instance for each item in self.dofs
and yield it.
"""
for dofs, val in six.iteritems(self.dofs):
single_cond = self.copy(name=self.name)
single_cond.is_single = True
single_cond.dofs = [dofs, val]
yield single_cond
def canonize_dof_names(self, dofs):
"""
Canonize the DOF names using the full list of DOFs of a
variable.
Assumes single condition instance.
"""
self.dofs[0] = _canonize(self.dofs[0], dofs)
class EssentialBC(Condition):
"""
Essential boundary condidion.
Parameters
----------
name : str
The boundary condition name.
region : Region instance
The region where the boundary condition is applied.
dofs : dict
The boundary condition specification defining the constrained
DOFs and their values.
key : str, optional
The sorting key.
times : list or str, optional
The list of time intervals or a function returning True at time
steps, when the condition applies.
"""
def __init__(self, name, region, dofs, key='', times=None):
Condition.__init__(self, name=name, region=region, dofs=dofs, key=key,
times=times)
def zero_dofs(self):
"""
Set all essential boundary condition values to zero.
"""
if self.is_single:
self.dofs[1] = 0.0
else:
new_dofs = {}
for key in six.iterkeys(self.dofs):
new_dofs[key] = 0.0
self.dofs = new_dofs
class PeriodicBC(Condition):
"""
Periodic boundary condidion.
Parameters
----------
name : str
The boundary condition name.
regions : list of two Region instances
The master region and the slave region where the DOFs should match.
dofs : dict
The boundary condition specification defining the DOFs in the master
region and the corresponding DOFs in the slave region.
match : str
The name of function for matching corresponding nodes in the
two regions.
key : str, optional
The sorting key.
times : list or str, optional
The list of time intervals or a function returning True at time
steps, when the condition applies.
"""
def __init__(self, name, regions, dofs, match, key='', times=None):
Condition.__init__(self, name=name, regions=regions, dofs=dofs,
match=match, key=key, times=times)
def canonize_dof_names(self, dofs):
"""
Canonize the DOF names using the full list of DOFs of a
variable.
Assumes single condition instance.
"""
self.dofs[0] = _canonize(self.dofs[0], dofs)
self.dofs[1] = _canonize(self.dofs[1], dofs)
class LinearCombinationBC(Condition):
"""
Linear combination boundary condidion.
Parameters
----------
name : str
The boundary condition name.
regions : list of two Region instances
The constrained (master) DOFs region and the new (slave) DOFs
region. The latter can be None if new DOFs are not field variable DOFs.
dofs : dict
The boundary condition specification defining the constrained
DOFs and the new DOFs (can be None).
dof_map_fun : str
The name of function for mapping the constrained DOFs to new DOFs (can
be None).
kind : str
The linear combination condition kind.
key : str, optional
The sorting key.
times : list or str, optional
The list of time intervals or a function returning True at time
steps, when the condition applies.
arguments: tuple, optional
Additional arguments, depending on the condition kind.
"""
def __init__(self, name, regions, dofs, dof_map_fun, kind, key='',
times=None, arguments=None):
Condition.__init__(self, name=name, regions=regions, dofs=dofs,
dof_map_fun=dof_map_fun, kind=kind,
key=key, times=times, arguments=arguments)
def get_var_names(self):
"""
Get names of variables corresponding to the constrained and new DOFs.
"""
names = [self.dofs[0].split('.')[0]]
if self.dofs[1] is not None:
names.append(self.dofs[1].split('.')[0])
return names
def canonize_dof_names(self, dofs0, dofs1=None):
"""
Canonize the DOF names using the full list of DOFs of a
variable.
Assumes single condition instance.
"""
self.dofs[0] = _canonize(self.dofs[0], dofs0)
if self.dofs[1] is not None:
self.dofs[1] = _canonize(self.dofs[1], dofs1)
class InitialCondition(Condition):
"""
Initial condidion.
Parameters
----------
name : str
The initial condition name.
region : Region instance
The region where the initial condition is applied.
dofs : dict
The initial condition specification defining the constrained
DOFs and their values.
key : str, optional
The sorting key.
"""
def __init__(self, name, region, dofs, key=''):
Condition.__init__(self, name=name, region=region, dofs=dofs, key=key)
| [
"sfepy.base.base.Struct.__init__"
] | [((1475, 1494), 'six.iteritems', 'six.iteritems', (['conf'], {}), '(conf)\n', (1488, 1494), False, 'import six\n'), ((4772, 4814), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'name': 'name'}), '(self, name=name, **kwargs)\n', (4787, 4814), False, 'from sfepy.base.base import basestr, Container, Struct\n'), ((5015, 5039), 'six.iteritems', 'six.iteritems', (['self.dofs'], {}), '(self.dofs)\n', (5028, 5039), False, 'import six\n'), ((869, 885), 'numpy.isscalar', 'nm.isscalar', (['val'], {}), '(val)\n', (880, 885), True, 'import numpy as nm\n'), ((6435, 6458), 'six.iterkeys', 'six.iterkeys', (['self.dofs'], {}), '(self.dofs)\n', (6447, 6458), False, 'import six\n')] |
import numpy as nm
from sfepy.linalg import dot_sequences
from sfepy.terms.terms import Term, terms
from sfepy.terms.terms_th import THTerm, ETHTerm
from sfepy.terms.terms_elastic import CauchyStressTerm
class BiotTerm(Term):
r"""
Biot coupling term with :math:`\alpha_{ij}` given in:
* vector form exploiting symmetry - in 3D it has the
indices ordered as :math:`[11, 22, 33, 12, 13, 23]`, in 2D it has
the indices ordered as :math:`[11, 22, 12]`,
* matrix form - non-symmetric coupling parameter.
Corresponds to weak forms of Biot gradient and divergence terms.
Can be evaluated. Can use derivatives.
:Definition:
.. math::
\int_{\Omega} p\ \alpha_{ij} e_{ij}(\ul{v}) \mbox{ , } \int_{\Omega}
q\ \alpha_{ij} e_{ij}(\ul{u})
:Arguments 1:
- material : :math:`\alpha_{ij}`
- virtual : :math:`\ul{v}`
- state : :math:`p`
:Arguments 2:
- material : :math:`\alpha_{ij}`
- state : :math:`\ul{u}`
- virtual : :math:`q`
:Arguments 3:
- material : :math:`\alpha_{ij}`
- parameter_v : :math:`\ul{u}`
- parameter_s : :math:`p`
"""
name = 'dw_biot'
arg_types = (('material', 'virtual', 'state'),
('material', 'state', 'virtual'),
('material', 'parameter_v', 'parameter_s'))
arg_shapes = [{'material' : 'S, 1',
'virtual/grad' : ('D', None), 'state/grad' : 1,
'virtual/div' : (1, None), 'state/div' : 'D',
'parameter_v' : 'D', 'parameter_s' : 1},
{'material' : 'D, D'}]
modes = ('grad', 'div', 'eval')
def get_fargs(self, mat, vvar, svar,
mode=None, term_mode=None, diff_var=None, **kwargs):
sym_mode = False if mat.shape[-2] == mat.shape[-1] > 1 else True
if not sym_mode:
sh = mat.shape
# the gradient given by 'self.get' is transposed
mat = nm.swapaxes(mat, 2, 3)
mat = mat.reshape(sh[:2] + (sh[2]**2, 1))
if self.mode == 'grad':
qp_var, qp_name = svar, 'val'
else:
if sym_mode:
qp_var, qp_name = vvar, 'cauchy_strain'
else:
qp_var, qp_name = vvar, 'grad'
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)
if qp_name == 'grad':
sh = val_qp.shape
val_qp = val_qp.reshape(sh[:2] + (sh[2]**2, 1))
fmode = 0
else:
val_qp = nm.array([0], ndmin=4, dtype=nm.float64)
fmode = 1
return 1.0, val_qp, mat, svg, vvg, fmode
elif mode == 'eval':
vvg, _ = self.get_mapping(vvar)
if sym_mode:
strain = self.get(vvar, 'cauchy_strain')
else:
strain = self.get(vvar, 'grad')
sh = strain.shape
strain = strain.reshape(sh[:2] + (sh[2]**2, 1))
pval = self.get(svar, 'val')
return 1.0, pval, strain, mat, vvg
else:
raise ValueError('unsupported evaluation mode in %s! (%s)'
% (self.name, mode))
def get_eval_shape(self, mat, 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_biot_grad,
'div' : terms.dw_biot_div,
'eval' : terms.d_biot_div,
}[self.mode]
class BiotStressTerm(CauchyStressTerm):
r"""
Evaluate Biot stress tensor.
It is given in the usual vector form exploiting symmetry: in 3D it has 6
components with the indices ordered as :math:`[11, 22, 33, 12, 13, 23]`, in
2D it has 3 components with the indices ordered as :math:`[11, 22, 12]`.
Supports 'eval', 'el_avg' and 'qp' evaluation modes.
:Definition:
.. math::
- \int_{\Omega} \alpha_{ij} \bar{p}
.. math::
\mbox{vector for } K \from \Ical_h:
- \int_{T_K} \alpha_{ij} \bar{p} / \int_{T_K} 1
.. math::
- \alpha_{ij} \bar{p}|_{qp}
:Arguments:
- material : :math:`\alpha_{ij}`
- parameter : :math:`\bar{p}`
"""
name = 'ev_biot_stress'
arg_types = ('material', 'parameter')
arg_shapes = {'material' : 'S, 1', 'parameter' : 1}
@staticmethod
def function(out, val_qp, mat, vg, fmode):
if fmode == 2:
out[:] = dot_sequences(mat, val_qp)
status = 0
else:
status = terms.de_cauchy_stress(out, val_qp, mat, vg, fmode)
out *= -1.0
return status
def get_fargs(self, mat, parameter,
mode=None, term_mode=None, diff_var=None, **kwargs):
vg, _ = self.get_mapping(parameter)
val_qp = self.get(parameter, 'val')
fmode = {'eval' : 0, 'el_avg' : 1, 'qp' : 2}.get(mode, 1)
return val_qp, mat, vg, fmode
class BiotTHTerm(BiotTerm, THTerm):
r"""
Fading memory Biot term. Can use derivatives.
:Definition:
.. math::
\begin{array}{l}
\int_{\Omega} \left [\int_0^t \alpha_{ij}(t-\tau)\,p(\tau)) \difd{\tau}
\right]\,e_{ij}(\ul{v}) \mbox{ ,} \\
\int_{\Omega} \left [\int_0^t
\alpha_{ij}(t-\tau) e_{kl}(\ul{u}(\tau)) \difd{\tau} \right] q
\end{array}
:Arguments 1:
- ts : :class:`TimeStepper` instance
- material : :math:`\alpha_{ij}(\tau)`
- virtual : :math:`\ul{v}`
- state : :math:`p`
:Arguments 2:
- ts : :class:`TimeStepper` instance
- material : :math:`\alpha_{ij}(\tau)`
- state : :math:`\ul{u}`
- virtual : :math:`q`
"""
name = 'dw_biot_th'
arg_types = (('ts', 'material', 'virtual', 'state'),
('ts', 'material', 'state', 'virtual'))
arg_shapes = {'material' : '.: N, S, 1',
'virtual/grad' : ('D', None), 'state/grad' : 1,
'virtual/div' : (1, None), 'state/div' : 'D'}
modes = ('grad', 'div')
def get_fargs(self, ts, mats, 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, 'cauchy_strain'
n_el, n_qp, dim, n_en, n_c = self.get_data_shape(svar)
if mode == 'weak':
vvg, _ = self.get_mapping(vvar)
svg, _ = self.get_mapping(svar)
if diff_var is None:
def iter_kernel():
for ii, mat in enumerate(mats):
val_qp = self.get(qp_var, qp_name, step=-ii)
mat = nm.tile(mat, (n_el, n_qp, 1, 1))
yield ii, (ts.dt, val_qp, mat, svg, vvg, 0)
fargs = iter_kernel
else:
val_qp = nm.array([0], ndmin=4, dtype=nm.float64)
mat = nm.tile(mats[0], (n_el, n_qp, 1, 1))
fargs = ts.dt, val_qp, mat, svg, vvg, 1
return fargs
else:
raise ValueError('unsupported evaluation mode in %s! (%s)'
% (self.name, mode))
class BiotETHTerm(BiotTerm, ETHTerm):
r"""
This term has the same definition as dw_biot_th, but assumes an
exponential approximation of the convolution kernel resulting in much
higher efficiency. Can use derivatives.
:Definition:
.. math::
\begin{array}{l}
\int_{\Omega} \left [\int_0^t \alpha_{ij}(t-\tau)\,p(\tau)) \difd{\tau}
\right]\,e_{ij}(\ul{v}) \mbox{ ,} \\
\int_{\Omega} \left [\int_0^t
\alpha_{ij}(t-\tau) e_{kl}(\ul{u}(\tau)) \difd{\tau} \right] q
\end{array}
:Arguments 1:
- ts : :class:`TimeStepper` instance
- material_0 : :math:`\alpha_{ij}(0)`
- material_1 : :math:`\exp(-\lambda \Delta t)` (decay at :math:`t_1`)
- virtual : :math:`\ul{v}`
- state : :math:`p`
:Arguments 2:
- ts : :class:`TimeStepper` instance
- material_0 : :math:`\alpha_{ij}(0)`
- material_1 : :math:`\exp(-\lambda \Delta t)` (decay at :math:`t_1`)
- state : :math:`\ul{u}`
- virtual : :math:`q`
"""
name = 'dw_biot_eth'
arg_types = (('ts', 'material_0', 'material_1', 'virtual', 'state'),
('ts', 'material_0', 'material_1', 'state', 'virtual'))
arg_shapes = {'material_0' : 'S, 1', 'material_1' : '1, 1',
'virtual/grad' : ('D', None), 'state/grad' : 1,
'virtual/div' : (1, None), 'state/div' : 'D'}
modes = ('grad', 'div')
def get_fargs(self, ts, mat0, mat1, vvar, svar,
mode=None, term_mode=None, diff_var=None, **kwargs):
if self.mode == 'grad':
qp_var, qp_name, iv = svar, 'val', 4
else:
qp_var, qp_name, iv = vvar, 'cauchy_strain', 3
if mode == 'weak':
vvg, _, key = self.get_mapping(vvar, return_key=True)
svg, _ = self.get_mapping(svar)
if diff_var is None:
val_qp = self.get(qp_var, qp_name)
key += tuple(self.arg_names[ii] for ii in [1, 2, iv])
data = self.get_eth_data(key, qp_var, mat1, val_qp)
val = data.history + data.values
fargs = (ts.dt, val, mat0, svg, vvg, 0)
else:
val_qp = nm.array([0], ndmin=4, dtype=nm.float64)
fargs = (ts.dt, val_qp, mat0, svg, vvg, 1)
return fargs
else:
raise ValueError('unsupported evaluation mode in %s! (%s)'
% (self.name, mode))
| [
"sfepy.linalg.dot_sequences",
"sfepy.terms.terms.terms.de_cauchy_stress"
] | [((2000, 2022), 'numpy.swapaxes', 'nm.swapaxes', (['mat', '(2)', '(3)'], {}), '(mat, 2, 3)\n', (2011, 2022), True, 'import numpy as nm\n'), ((4783, 4809), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['mat', 'val_qp'], {}), '(mat, val_qp)\n', (4796, 4809), False, 'from sfepy.linalg import dot_sequences\n'), ((4869, 4920), 'sfepy.terms.terms.terms.de_cauchy_stress', 'terms.de_cauchy_stress', (['out', 'val_qp', 'mat', 'vg', 'fmode'], {}), '(out, val_qp, mat, vg, fmode)\n', (4891, 4920), False, 'from sfepy.terms.terms import Term, terms\n'), ((2729, 2769), 'numpy.array', 'nm.array', (['[0]'], {'ndmin': '(4)', 'dtype': 'nm.float64'}), '([0], ndmin=4, dtype=nm.float64)\n', (2737, 2769), True, 'import numpy as nm\n'), ((7237, 7277), 'numpy.array', 'nm.array', (['[0]'], {'ndmin': '(4)', 'dtype': 'nm.float64'}), '([0], ndmin=4, dtype=nm.float64)\n', (7245, 7277), True, 'import numpy as nm\n'), ((7300, 7336), 'numpy.tile', 'nm.tile', (['mats[0]', '(n_el, n_qp, 1, 1)'], {}), '(mats[0], (n_el, n_qp, 1, 1))\n', (7307, 7336), True, 'import numpy as nm\n'), ((9827, 9867), 'numpy.array', 'nm.array', (['[0]'], {'ndmin': '(4)', 'dtype': 'nm.float64'}), '([0], ndmin=4, dtype=nm.float64)\n', (9835, 9867), True, 'import numpy as nm\n'), ((7056, 7088), 'numpy.tile', 'nm.tile', (['mat', '(n_el, n_qp, 1, 1)'], {}), '(mat, (n_el, n_qp, 1, 1))\n', (7063, 7088), True, 'import numpy as nm\n')] |
r"""
Diametrically point loaded 2-D disk. See :ref:`sec-primer`.
Find :math:`\ul{u}` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
= 0
\;, \quad \forall \ul{v} \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
"""
from __future__ import absolute_import
from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson
from sfepy.discrete.fem.utils import refine_mesh
from sfepy import data_dir
# Fix the mesh file name if you run this file outside the SfePy directory.
filename_mesh = data_dir + '/meshes/2d/its2D.mesh'
refinement_level = 0
filename_mesh = refine_mesh(filename_mesh, refinement_level)
output_dir = '.' # set this to a valid directory you have write access to
young = 2000.0 # Young's modulus [MPa]
poisson = 0.4 # Poisson's ratio
options = {
'output_dir' : output_dir,
}
regions = {
'Omega' : 'all',
'Left' : ('vertices in (x < 0.001)', 'facet'),
'Bottom' : ('vertices in (y < 0.001)', 'facet'),
'Top' : ('vertex 2', 'vertex'),
}
materials = {
'Asphalt' : ({'D': stiffness_from_youngpoisson(2, young, poisson)},),
'Load' : ({'.val' : [0.0, -1000.0]},),
}
fields = {
'displacement': ('real', 'vector', 'Omega', 1),
}
equations = {
'balance_of_forces' :
"""dw_lin_elastic.2.Omega(Asphalt.D, v, u)
= dw_point_load.0.Top(Load.val, v)""",
}
variables = {
'u' : ('unknown field', 'displacement', 0),
'v' : ('test field', 'displacement', 'u'),
}
ebcs = {
'XSym' : ('Bottom', {'u.1' : 0.0}),
'YSym' : ('Left', {'u.0' : 0.0}),
}
solvers = {
'ls' : ('ls.scipy_direct', {}),
'newton' : ('nls.newton', {
'i_max' : 1,
'eps_a' : 1e-6,
}),
}
| [
"sfepy.discrete.fem.utils.refine_mesh",
"sfepy.mechanics.matcoefs.stiffness_from_youngpoisson"
] | [((691, 735), 'sfepy.discrete.fem.utils.refine_mesh', 'refine_mesh', (['filename_mesh', 'refinement_level'], {}), '(filename_mesh, refinement_level)\n', (702, 735), False, 'from sfepy.discrete.fem.utils import refine_mesh\n'), ((1144, 1190), 'sfepy.mechanics.matcoefs.stiffness_from_youngpoisson', 'stiffness_from_youngpoisson', (['(2)', 'young', 'poisson'], {}), '(2, young, poisson)\n', (1171, 1190), False, 'from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson\n')] |
"""
Friction-slip model formulated as the implicit complementarity problem.
To integrate over a (dual) mesh, one needs:
* coordinates of element vertices
* element connectivity
* local base for each element
* constant in each sub-triangle of the dual mesh
Data for each dual element:
* connectivity of its sub-triangles
* base directions t_1, t_2
Normal stresses:
* Assemble the rezidual and apply the LCBC operator described below.
Solution in \hat{V}_h^c:
* construct a restriction operator via LCBC just like in the no-penetration case
* use the substitution:
u_1 = n_1 * w
u_2 = n_2 * w
u_3 = n_3 * w
The new DOF is `w`.
* for the record, no-penetration does:
w_1 = - (1 / n_1) * (u_2 * n_2 + u_3 * n_3)
w_2 = u_2
w_3 = u_3
"""
from sfepy.base.base import *
from sfepy.base.compat import unique
import sfepy.linalg as la
from sfepy.fem import Mesh, Domain, Field, Variables
from sfepy.fem.mappings import VolumeMapping, SurfaceMapping
from sfepy.fem.fe_surface import FESurface
from sfepy.fem.utils import compute_nodal_normals
def edge_data_to_output(coors, conn, e_sort, data):
out = nm.zeros_like(coors)
out[conn[e_sort,0]] = data
return Struct(name='output_data',
mode='vertex', data=out,
dofs=None)
class DualMesh(Struct):
"""Dual mesh corresponding to a (surface) region."""
def __init__(self, region):
"""
Assume a single GeometryElement type in all groups, linear
approximation.
Works for one group only for the moment.
"""
domain = region.domain
self.dim = domain.shape.dim
self.region = copy(region)
self.region.setup_face_indices()
self.mesh_coors = domain.mesh.coors
# add_to_regions=True due to Field implementation shortcomings.
omega = domain.create_region('Omega', 'all', add_to_regions=True)
self.field = Field('displacements', nm.float64, (3,), omega, 1)
self.gel = domain.geom_els.values()[0]
self.sgel = self.gel.surface_facet
face_key = 's%d' % self.sgel.n_vertex
# Coordinate interpolation to face centres.
self.ps = self.gel.interp.poly_spaces[face_key]
centre = self.ps.node_coors.sum(axis=0) / self.ps.n_nod
self.bf = self.ps.eval_base(centre[None,:])
self.surfaces = surfaces = {}
self.dual_surfaces = dual_surfaces = {}
for ig, conn in enumerate(domain.mesh.conns):
surface = FESurface(None, self.region, self.gel.faces, conn, ig)
surfaces[ig] = surface
dual_surface = self.describe_dual_surface(surface)
dual_surfaces[ig] = dual_surface
def describe_dual_surface(self, surface):
n_fa, n_edge = surface.n_fa, self.sgel.n_edge
mesh_coors = self.mesh_coors
# Face centres.
fcoors = mesh_coors[surface.econn]
centre_coors = nm.dot(self.bf.squeeze(), fcoors)
surface_coors = mesh_coors[surface.nodes]
dual_coors = nm.r_[surface_coors, centre_coors]
coor_offset = surface.nodes.shape[0]
# Normals in primary mesh nodes.
nodal_normals = compute_nodal_normals(surface.nodes, self.region,
self.field)
ee = surface.leconn[:,self.sgel.edges].copy()
edges_per_face = ee.copy()
sh = edges_per_face.shape
ee.shape = edges_per_face.shape = (sh[0] * sh[1], sh[2])
edges_per_face.sort(axis=1)
eo = nm.empty((sh[0] * sh[1],), dtype=nm.object)
eo[:] = [tuple(ii) for ii in edges_per_face]
ueo, e_sort, e_id = unique(eo, return_index=True, return_inverse=True)
ueo = edges_per_face[e_sort]
# edge centre, edge point 1, face centre, edge point 2
conn = nm.empty((n_edge * n_fa, 4), dtype=nm.int32)
conn[:,0] = e_id
conn[:,1] = ee[:,0]
conn[:,2] = nm.repeat(nm.arange(n_fa, dtype=nm.int32), n_edge) \
+ coor_offset
conn[:,3] = ee[:,1]
# face centre, edge point 2, edge point 1
tri_conn = nm.ascontiguousarray(conn[:,[2,1,3]])
# Ensure orientation - outward normal.
cc = dual_coors[tri_conn]
v1 = cc[:,1] - cc[:,0]
v2 = cc[:,2] - cc[:,0]
normals = nm.cross(v1, v2)
nn = nodal_normals[surface.leconn].sum(axis=1).repeat(n_edge, 0)
centre_normals = (1.0 / surface.n_fp) * nn
centre_normals /= la.norm_l2_along_axis(centre_normals)[:,None]
dot = nm.sum(normals * centre_normals, axis=1)
assert_((dot > 0.0).all())
# Prepare mapping from reference triangle e_R to a
# triangle within reference face e_D.
gel = self.gel.surface_facet
ref_coors = gel.coors
ref_centre = nm.dot(self.bf.squeeze(), ref_coors)
cc = nm.r_[ref_coors, ref_centre[None,:]]
rconn = nm.empty((n_edge, 3), dtype=nm.int32)
rconn[:,0] = gel.n_vertex
rconn[:,1] = gel.edges[:,0]
rconn[:,2] = gel.edges[:,1]
map_er_ed = VolumeMapping(cc, rconn, gel=gel)
# Prepare mapping from reference triangle e_R to a
# physical triangle e.
map_er_e = SurfaceMapping(dual_coors, tri_conn, gel=gel)
# Compute triangle basis (edge) vectors.
nn = surface.nodes[ueo]
edge_coors = mesh_coors[nn]
edge_centre_coors = 0.5 * edge_coors.sum(axis=1)
edge_normals = 0.5 * nodal_normals[ueo].sum(axis=1)
edge_normals /= la.norm_l2_along_axis(edge_normals)[:,None]
nn = surface.nodes[ueo]
edge_dirs = edge_coors[:,1] - edge_coors[:,0]
edge_dirs /= la.norm_l2_along_axis(edge_dirs)[:,None]
edge_ortho = nm.cross(edge_normals, edge_dirs)
edge_ortho /= la.norm_l2_along_axis(edge_ortho)[:,None]
# Primary face - dual sub-faces map.
# i-th row: indices to conn corresponding to sub-faces of i-th face.
face_map = nm.arange(n_fa * n_edge, dtype=nm.int32)
face_map.shape = (n_fa, n_edge)
# The actual connectivity for assembling (unique nodes per master
# faces).
asm_conn = e_id[face_map]
n_nod = ueo.shape[0] # One node per unique edge.
n_components = self.dim - 1
dual_surface = Struct(name = 'dual_surface_description',
dim = self.dim,
n_dual_fa = conn.shape[0],
n_dual_fp = self.dim,
n_fa = n_fa,
n_edge = n_edge,
n_nod = n_nod,
n_components = n_components,
n_dof = n_nod * n_components,
dual_coors = dual_coors,
coor_offset = coor_offset,
e_sort = e_sort,
conn = conn,
tri_conn = tri_conn,
map_er_e = map_er_e,
map_er_ed = map_er_ed,
face_map = face_map,
asm_conn = asm_conn,
nodal_normals = nodal_normals,
edge_centre_coors = edge_centre_coors,
edge_normals = edge_normals,
edge_dirs = edge_dirs,
edge_ortho = edge_ortho)
return dual_surface
def save(self, filename):
coors = []
conns = []
mat_ids = []
offset = 0
for ig, dual_surface in self.dual_surfaces.iteritems():
cc = dual_surface.dual_coors
coors.append(cc)
conn = dual_surface.conn[:,1:].copy() + offset
conns.append(conn)
mat_id = nm.empty((conn.shape[0],), dtype=nm.int32)
mat_id[:] = ig
mat_ids.append(mat_id)
offset += cc.shape[0]
coors = nm.concatenate(coors, axis=0)
dual_mesh = Mesh.from_data('dual_mesh', coors, None, conns,
mat_ids, ['2_3'] * len(conns))
dual_mesh.write(filename, io='auto')
def save_axes(self, filename):
coors = []
conns = []
mat_ids = []
offset = 0
for ig, dual_surface in self.dual_surfaces.iteritems():
cc = nm.r_[dual_surface.edge_centre_coors,
dual_surface.dual_coors]
coors.append(cc)
conn = dual_surface.conn.copy() + offset
conn[:,1:] += dual_surface.edge_centre_coors.shape[0]
conns.append(conn)
mat_id = nm.empty((conn.shape[0],), dtype=nm.int32)
mat_id[:] = ig
mat_ids.append(mat_id)
offset += cc.shape[0]
coors = nm.concatenate(coors, axis=0)
out = {}
for ig, dual_surface in self.dual_surfaces.iteritems():
eto = edge_data_to_output
out['en_%d' % ig] = eto(coors, conns[ig], dual_surface.e_sort,
dual_surface.edge_normals)
out['ed_%d' % ig] = eto(coors, conns[ig], dual_surface.e_sort,
dual_surface.edge_dirs)
out['eo_%d' % ig] = eto(coors, conns[ig], dual_surface.e_sort,
dual_surface.edge_ortho)
dual_mesh = Mesh.from_data('dual_mesh_vectors', coors, None, conns,
mat_ids, ['2_4'] * len(conns))
dual_mesh.write(filename, io='auto', out=out)
| [
"sfepy.fem.fe_surface.FESurface",
"sfepy.linalg.norm_l2_along_axis",
"sfepy.fem.utils.compute_nodal_normals",
"sfepy.base.compat.unique",
"sfepy.fem.Field",
"sfepy.fem.mappings.SurfaceMapping",
"sfepy.fem.mappings.VolumeMapping"
] | [((1918, 1968), 'sfepy.fem.Field', 'Field', (['"""displacements"""', 'nm.float64', '(3,)', 'omega', '(1)'], {}), "('displacements', nm.float64, (3,), omega, 1)\n", (1923, 1968), False, 'from sfepy.fem import Mesh, Domain, Field, Variables\n'), ((3178, 3239), 'sfepy.fem.utils.compute_nodal_normals', 'compute_nodal_normals', (['surface.nodes', 'self.region', 'self.field'], {}), '(surface.nodes, self.region, self.field)\n', (3199, 3239), False, 'from sfepy.fem.utils import compute_nodal_normals\n'), ((3651, 3701), 'sfepy.base.compat.unique', 'unique', (['eo'], {'return_index': '(True)', 'return_inverse': '(True)'}), '(eo, return_index=True, return_inverse=True)\n', (3657, 3701), False, 'from sfepy.base.compat import unique\n'), ((5088, 5121), 'sfepy.fem.mappings.VolumeMapping', 'VolumeMapping', (['cc', 'rconn'], {'gel': 'gel'}), '(cc, rconn, gel=gel)\n', (5101, 5121), False, 'from sfepy.fem.mappings import VolumeMapping, SurfaceMapping\n'), ((5232, 5277), 'sfepy.fem.mappings.SurfaceMapping', 'SurfaceMapping', (['dual_coors', 'tri_conn'], {'gel': 'gel'}), '(dual_coors, tri_conn, gel=gel)\n', (5246, 5277), False, 'from sfepy.fem.mappings import VolumeMapping, SurfaceMapping\n'), ((2496, 2550), 'sfepy.fem.fe_surface.FESurface', 'FESurface', (['None', 'self.region', 'self.gel.faces', 'conn', 'ig'], {}), '(None, self.region, self.gel.faces, conn, ig)\n', (2505, 2550), False, 'from sfepy.fem.fe_surface import FESurface\n'), ((4489, 4526), 'sfepy.linalg.norm_l2_along_axis', 'la.norm_l2_along_axis', (['centre_normals'], {}), '(centre_normals)\n', (4510, 4526), True, 'import sfepy.linalg as la\n'), ((5540, 5575), 'sfepy.linalg.norm_l2_along_axis', 'la.norm_l2_along_axis', (['edge_normals'], {}), '(edge_normals)\n', (5561, 5575), True, 'import sfepy.linalg as la\n'), ((5692, 5724), 'sfepy.linalg.norm_l2_along_axis', 'la.norm_l2_along_axis', (['edge_dirs'], {}), '(edge_dirs)\n', (5713, 5724), True, 'import sfepy.linalg as la\n'), ((5811, 5844), 'sfepy.linalg.norm_l2_along_axis', 'la.norm_l2_along_axis', (['edge_ortho'], {}), '(edge_ortho)\n', (5832, 5844), True, 'import sfepy.linalg as la\n')] |
# -*- coding: utf-8 -*-
r"""
Linear elasticity with given displacements.
Find :math:`\ul{u}` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
= 0
\;, \quad \forall \ul{v} \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
This example models a cylinder that is fixed at one end while the second end
has a specified displacement of 0.01 in the x direction (this boundary
condition is named ``'Displaced'``). There is also a specified displacement of
0.005 in the z direction for points in the region labeled
``'SomewhereTop'``. This boundary condition is named
``'PerturbedSurface'``. The region ``'SomewhereTop'`` is specified as those
vertices for which::
(z > 0.017) & (x > 0.03) & (x < 0.07)
The displacement field (three DOFs/node) in the ``'Omega region'`` is
approximated using P1 (four-node tetrahedral) finite elements. The material is
linear elastic and its properties are specified as Lamé parameters
:math:`\lambda` and :math:`\mu` (see
http://en.wikipedia.org/wiki/Lam%C3%A9_parameters)
The output is the displacement for each vertex, saved by default to
cylinder.vtk. View the results using::
$ ./postproc.py cylinder.vtk --wireframe -b --only-names=u -d'u,plot_displacements,rel_scaling=1'
"""
from sfepy import data_dir
from sfepy.mechanics.matcoefs import stiffness_from_lame
filename_mesh = data_dir + '/meshes/3d/cylinder.mesh'
regions = {
'Omega' : 'all',
'Left' : ('vertices in (x < 0.001)', 'facet'),
'Right' : ('vertices in (x > 0.099)', 'facet'),
'SomewhereTop' : ('vertices in (z > 0.017) & (x > 0.03) & (x < 0.07)',
'vertex'),
}
materials = {
'solid' : ({'D': stiffness_from_lame(dim=3, lam=1e1, mu=1e0)},),
}
fields = {
'displacement': ('real', 'vector', 'Omega', 1),
}
integrals = {
'i' : 1,
}
variables = {
'u' : ('unknown field', 'displacement', 0),
'v' : ('test field', 'displacement', 'u'),
}
ebcs = {
'Fixed' : ('Left', {'u.all' : 0.0}),
'Displaced' : ('Right', {'u.0' : 0.01, 'u.[1,2]' : 0.0}),
'PerturbedSurface' : ('SomewhereTop', {'u.2' : 0.005}),
}
equations = {
'balance_of_forces' :
"""dw_lin_elastic.i.Omega(solid.D, v, u) = 0""",
}
solvers = {
'ls' : ('ls.scipy_direct', {}),
'newton' : ('nls.newton', {
'i_max' : 1,
'eps_a' : 1e-10,
}),
}
| [
"sfepy.mechanics.matcoefs.stiffness_from_lame"
] | [((1770, 1814), 'sfepy.mechanics.matcoefs.stiffness_from_lame', 'stiffness_from_lame', ([], {'dim': '(3)', 'lam': '(10.0)', 'mu': '(1.0)'}), '(dim=3, lam=10.0, mu=1.0)\n', (1789, 1814), False, 'from sfepy.mechanics.matcoefs import stiffness_from_lame\n')] |
import os
import numpy as nm
try:
from enthought.tvtk.api import tvtk
from enthought.mayavi.sources.vtk_data_source import VTKDataSource
from enthought.pyface.timer.api import Timer
except:
from tvtk.api import tvtk
from mayavi.sources.vtk_data_source import VTKDataSource
from pyface.timer.api import Timer
from dataset_manager import DatasetManager
from sfepy.base.base import Struct, basestr
from sfepy.postprocess.utils import mlab
from sfepy.discrete.fem import Mesh
from sfepy.discrete.fem.meshio import MeshIO, vtk_cell_types, supported_formats
def create_file_source(filename, watch=False, offscreen=True):
"""Factory function to create a file source corresponding to the
given file format."""
kwargs = {'watch' : watch, 'offscreen' : offscreen}
if isinstance(filename, basestr):
fmt = os.path.splitext(filename)[1]
is_sequence = False
else: # A sequence.
fmt = os.path.splitext(filename[0])[1]
is_sequence = True
fmt = fmt.lower()
if fmt == '.vtk':
# VTK is supported directly by Mayavi, no need to use MeshIO.
if is_sequence:
return VTKSequenceFileSource(filename, **kwargs)
else:
return VTKFileSource(filename, **kwargs)
elif fmt in supported_formats.keys():
if is_sequence:
if fmt == '.h5':
raise ValueError('format .h5 does not support file sequences!')
else:
return GenericSequenceFileSource(filename, **kwargs)
else:
return GenericFileSource(filename, **kwargs)
else:
raise ValueError('unknown file format! (%s)' % fmt)
class FileSource(Struct):
"""General file source."""
def __init__(self, filename, watch=False, offscreen=True):
"""Create a file source using the given file name."""
mlab.options.offscreen = offscreen
self.watch = watch
self.filename = filename
self.reset()
def __call__(self, step=0):
"""Get the file source."""
if self.source is None:
self.source = self.create_source()
if self.watch:
self.timer = Timer(1000, self.poll_file)
return self.source
def reset(self):
"""Reset."""
self.mat_id_name = None
self.source = None
self.notify_obj = None
self.steps = []
self.times = []
self.step = 0
self.time = 0.0
if self.watch:
self.last_stat = os.stat(self.filename)
def setup_mat_id(self, mat_id_name='mat_id', single_color=False):
self.mat_id_name = mat_id_name
self.single_color = single_color
def get_step_time(self, step=None, time=None):
"""
Set current step and time to the values closest greater or equal to
either step or time. Return the found values.
"""
if (step is not None) and len(self.steps):
step = step if step >= 0 else self.steps[-1] + step + 1
ii = nm.searchsorted(self.steps, step)
ii = nm.clip(ii, 0, len(self.steps) - 1)
self.step = self.steps[ii]
if len(self.times):
self.time = self.times[ii]
elif (time is not None) and len(self.times):
ii = nm.searchsorted(self.times, time)
ii = nm.clip(ii, 0, len(self.steps) - 1)
self.step = self.steps[ii]
self.time = self.times[ii]
return self.step, self.time
def get_ts_info(self):
return self.steps, self.times
def get_mat_id(self, mat_id_name='mat_id'):
"""
Get material ID numbers of the underlying mesh elements.
"""
if self.source is not None:
dm = DatasetManager(dataset=self.source.outputs[0])
mat_id = dm.cell_scalars[mat_id_name]
return mat_id
def file_changed(self):
pass
def setup_notification(self, obj, attr):
"""The attribute 'attr' of the object 'obj' will be set to True
when the source file is watched and changes."""
self.notify_obj = obj
self.notify_attr = attr
def poll_file(self):
"""Check the source file's time stamp and notify the
self.notify_obj in case it changed. Subclasses should implement
the file_changed() method."""
if not self.notify_obj:
return
s = os.stat(self.filename)
if s[-2] == self.last_stat[-2]:
setattr(self.notify_obj, self.notify_attr, False)
else:
self.file_changed()
setattr(self.notify_obj, self.notify_attr, True)
self.last_stat = s
class VTKFileSource(FileSource):
"""A thin wrapper around mlab.pipeline.open()."""
def create_source(self):
"""Create a VTK file source """
return mlab.pipeline.open(self.filename)
def get_bounding_box(self):
bbox = nm.array(self.source.reader.unstructured_grid_output.bounds)
return bbox.reshape((3,2)).T
def set_filename(self, filename, vis_source):
self.filename = filename
vis_source.base_file_name = filename
# Force re-read.
vis_source.reader.modified()
vis_source.update()
# Propagate changes in the pipeline.
vis_source.data_changed = True
class VTKSequenceFileSource(VTKFileSource):
"""A thin wrapper around mlab.pipeline.open() for VTK file sequences."""
def __init__(self, *args, **kwargs):
FileSource.__init__(self, *args, **kwargs)
self.steps = nm.arange(len(self.filename), dtype=nm.int32)
def create_source(self):
"""Create a VTK file source """
return mlab.pipeline.open(self.filename[0])
def set_filename(self, filename, vis_source):
self.filename = filename
vis_source.base_file_name = filename[self.step]
class GenericFileSource(FileSource):
"""File source usable with any format supported by MeshIO classes."""
def __init__(self, *args, **kwargs):
FileSource.__init__(self, *args, **kwargs)
self.read_common(self.filename)
def read_common(self, filename):
self.io = MeshIO.any_from_filename(filename)
self.steps, self.times, _ = self.io.read_times()
self.mesh = Mesh.from_file(filename)
self.n_nod, self.dim = self.mesh.coors.shape
def create_source(self):
"""
Create a VTK source from data in a SfePy-supported file.
Notes
-----
All data need to be set here, otherwise time stepping will not
work properly - data added by user later will be thrown away on
time step change.
"""
if self.io is None:
self.read_common(self.filename)
dataset = self.create_dataset()
try:
out = self.io.read_data(self.step)
except ValueError:
out = None
if out is not None:
self.add_data_to_dataset(dataset, out)
if self.mat_id_name is not None:
mat_id = nm.concatenate(self.mesh.mat_ids)
if self.single_color:
rm = mat_id.min(), mat_id.max()
mat_id[mat_id > rm[0]] = rm[1]
dm = DatasetManager(dataset=dataset)
dm.add_array(mat_id, self.mat_id_name, 'cell')
src = VTKDataSource(data=dataset)
# src.print_traits()
# debug()
return src
def get_bounding_box(self):
bbox = self.mesh.get_bounding_box()
if self.dim == 2:
bbox = nm.c_[bbox, [0.0, 0.0]]
return bbox
def set_filename(self, filename, vis_source):
self.filename = filename
self.source = self.create_source()
vis_source.data = self.source.data
def get_mat_id(self, mat_id_name='mat_id'):
"""
Get material ID numbers of the underlying mesh elements.
"""
if self.source is not None:
mat_id = nm.concatenate(self.mesh.mat_ids)
return mat_id
def file_changed(self):
self.steps, self.times, _ = self.io.read_times()
def create_dataset(self):
"""Create a tvtk.UnstructuredGrid dataset from the Mesh instance of the
file source."""
mesh = self.mesh
n_nod, dim = self.n_nod, self.dim
n_el, n_els, n_e_ps = mesh.n_el, mesh.n_els, mesh.n_e_ps
if dim == 2:
nod_zz = nm.zeros((n_nod, 1), dtype=mesh.coors.dtype)
points = nm.c_[mesh.coors, nod_zz]
else:
points = mesh.coors
dataset = tvtk.UnstructuredGrid(points=points)
cell_types = []
cells = []
offset = [0]
for ig, conn in enumerate(mesh.conns):
cell_types += [vtk_cell_types[mesh.descs[ig]]] * n_els[ig]
nn = nm.array([conn.shape[1]] * n_els[ig])
aux = nm.c_[nn[:,None], conn]
cells.extend(aux.ravel())
offset.extend([aux.shape[1]] * n_els[ig])
cells = nm.array(cells)
cell_types = nm.array(cell_types)
offset = nm.cumsum(offset)[:-1]
cell_array = tvtk.CellArray()
cell_array.set_cells(n_el, cells)
dataset.set_cells(cell_types, offset, cell_array)
return dataset
def add_data_to_dataset(self, dataset, data):
"""Add point and cell data to the dataset."""
dim = self.dim
sym = (dim + 1) * dim / 2
dm = DatasetManager(dataset=dataset)
for key, val in data.iteritems():
vd = val.data
## print vd.shape
if val.mode == 'vertex':
if vd.shape[1] == 1:
aux = vd.reshape((vd.shape[0],))
elif vd.shape[1] == 2:
zz = nm.zeros((vd.shape[0], 1), dtype=vd.dtype)
aux = nm.c_[vd, zz]
elif vd.shape[1] == 3:
aux = vd
else:
raise ValueError('unknown vertex data format! (%s)'\
% vd.shape)
dm.add_array(aux, key, 'point')
elif val.mode == 'cell':
ne, aux, nr, nc = vd.shape
if (nr == 1) and (nc == 1):
aux = vd.reshape((ne,))
elif (nr == dim) and (nc == 1):
if dim == 3:
aux = vd.reshape((ne, dim))
else:
zz = nm.zeros((vd.shape[0], 1), dtype=vd.dtype);
aux = nm.c_[vd.squeeze(), zz]
elif (((nr == sym) or (nr == (dim * dim))) and (nc == 1)) \
or ((nr == dim) and (nc == dim)):
vd = vd.squeeze()
if dim == 3:
if nr == sym:
aux = vd[:,[0,3,4,3,1,5,4,5,2]]
elif nr == (dim * dim):
aux = vd[:,[0,3,4,6,1,5,7,8,2]]
else:
aux = vd.reshape((vd.shape[0], dim*dim))
else:
zz = nm.zeros((vd.shape[0], 1), dtype=vd.dtype);
if nr == sym:
aux = nm.c_[vd[:,[0,2]], zz, vd[:,[2,1]],
zz, zz, zz, zz]
elif nr == (dim * dim):
aux = nm.c_[vd[:,[0,2]], zz, vd[:,[3,1]],
zz, zz, zz, zz]
else:
aux = nm.c_[vd[:,0,[0,1]], zz, vd[:,1,[0,1]],
zz, zz, zz, zz]
dm.add_array(aux, key, 'cell')
class GenericSequenceFileSource(GenericFileSource):
"""File source usable with any format supported by MeshIO classes, with
exception of HDF5 (.h5), for file sequences."""
def read_common(self, filename):
self.steps = nm.arange(len(self.filename), dtype=nm.int32)
def create_source(self):
"""Create a VTK source from data in a SfePy-supported file."""
if self.io is None:
self.read_common(self.filename[self.step])
dataset = self.create_dataset()
src = VTKDataSource(data=dataset)
return src
def set_filename(self, filename, vis_source):
self.filename = filename
self.io = None
self.source = self.create_source()
vis_source.data = self.source.data
| [
"sfepy.postprocess.utils.mlab.pipeline.open",
"sfepy.discrete.fem.Mesh.from_file",
"sfepy.discrete.fem.meshio.MeshIO.any_from_filename",
"sfepy.discrete.fem.meshio.supported_formats.keys"
] | [((4437, 4459), 'os.stat', 'os.stat', (['self.filename'], {}), '(self.filename)\n', (4444, 4459), False, 'import os\n'), ((4873, 4906), 'sfepy.postprocess.utils.mlab.pipeline.open', 'mlab.pipeline.open', (['self.filename'], {}), '(self.filename)\n', (4891, 4906), False, 'from sfepy.postprocess.utils import mlab\n'), ((4955, 5015), 'numpy.array', 'nm.array', (['self.source.reader.unstructured_grid_output.bounds'], {}), '(self.source.reader.unstructured_grid_output.bounds)\n', (4963, 5015), True, 'import numpy as nm\n'), ((5725, 5761), 'sfepy.postprocess.utils.mlab.pipeline.open', 'mlab.pipeline.open', (['self.filename[0]'], {}), '(self.filename[0])\n', (5743, 5761), False, 'from sfepy.postprocess.utils import mlab\n'), ((6204, 6238), 'sfepy.discrete.fem.meshio.MeshIO.any_from_filename', 'MeshIO.any_from_filename', (['filename'], {}), '(filename)\n', (6228, 6238), False, 'from sfepy.discrete.fem.meshio import MeshIO, vtk_cell_types, supported_formats\n'), ((6317, 6341), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['filename'], {}), '(filename)\n', (6331, 6341), False, 'from sfepy.discrete.fem import Mesh\n'), ((7366, 7393), 'mayavi.sources.vtk_data_source.VTKDataSource', 'VTKDataSource', ([], {'data': 'dataset'}), '(data=dataset)\n', (7379, 7393), False, 'from mayavi.sources.vtk_data_source import VTKDataSource\n'), ((8602, 8638), 'tvtk.api.tvtk.UnstructuredGrid', 'tvtk.UnstructuredGrid', ([], {'points': 'points'}), '(points=points)\n', (8623, 8638), False, 'from tvtk.api import tvtk\n'), ((9030, 9045), 'numpy.array', 'nm.array', (['cells'], {}), '(cells)\n', (9038, 9045), True, 'import numpy as nm\n'), ((9067, 9087), 'numpy.array', 'nm.array', (['cell_types'], {}), '(cell_types)\n', (9075, 9087), True, 'import numpy as nm\n'), ((9158, 9174), 'tvtk.api.tvtk.CellArray', 'tvtk.CellArray', ([], {}), '()\n', (9172, 9174), False, 'from tvtk.api import tvtk\n'), ((9476, 9507), 'dataset_manager.DatasetManager', 'DatasetManager', ([], {'dataset': 'dataset'}), '(dataset=dataset)\n', (9490, 9507), False, 'from dataset_manager import DatasetManager\n'), ((12284, 12311), 'mayavi.sources.vtk_data_source.VTKDataSource', 'VTKDataSource', ([], {'data': 'dataset'}), '(data=dataset)\n', (12297, 12311), False, 'from mayavi.sources.vtk_data_source import VTKDataSource\n'), ((849, 875), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (865, 875), False, 'import os\n'), ((946, 975), 'os.path.splitext', 'os.path.splitext', (['filename[0]'], {}), '(filename[0])\n', (962, 975), False, 'import os\n'), ((1291, 1315), 'sfepy.discrete.fem.meshio.supported_formats.keys', 'supported_formats.keys', ([], {}), '()\n', (1313, 1315), False, 'from sfepy.discrete.fem.meshio import MeshIO, vtk_cell_types, supported_formats\n'), ((2525, 2547), 'os.stat', 'os.stat', (['self.filename'], {}), '(self.filename)\n', (2532, 2547), False, 'import os\n'), ((3041, 3074), 'numpy.searchsorted', 'nm.searchsorted', (['self.steps', 'step'], {}), '(self.steps, step)\n', (3056, 3074), True, 'import numpy as nm\n'), ((3774, 3820), 'dataset_manager.DatasetManager', 'DatasetManager', ([], {'dataset': 'self.source.outputs[0]'}), '(dataset=self.source.outputs[0])\n', (3788, 3820), False, 'from dataset_manager import DatasetManager\n'), ((7079, 7112), 'numpy.concatenate', 'nm.concatenate', (['self.mesh.mat_ids'], {}), '(self.mesh.mat_ids)\n', (7093, 7112), True, 'import numpy as nm\n'), ((7260, 7291), 'dataset_manager.DatasetManager', 'DatasetManager', ([], {'dataset': 'dataset'}), '(dataset=dataset)\n', (7274, 7291), False, 'from dataset_manager import DatasetManager\n'), ((7989, 8022), 'numpy.concatenate', 'nm.concatenate', (['self.mesh.mat_ids'], {}), '(self.mesh.mat_ids)\n', (8003, 8022), True, 'import numpy as nm\n'), ((8445, 8489), 'numpy.zeros', 'nm.zeros', (['(n_nod, 1)'], {'dtype': 'mesh.coors.dtype'}), '((n_nod, 1), dtype=mesh.coors.dtype)\n', (8453, 8489), True, 'import numpy as nm\n'), ((8840, 8877), 'numpy.array', 'nm.array', (['([conn.shape[1]] * n_els[ig])'], {}), '([conn.shape[1]] * n_els[ig])\n', (8848, 8877), True, 'import numpy as nm\n'), ((9105, 9122), 'numpy.cumsum', 'nm.cumsum', (['offset'], {}), '(offset)\n', (9114, 9122), True, 'import numpy as nm\n'), ((2190, 2217), 'pyface.timer.api.Timer', 'Timer', (['(1000)', 'self.poll_file'], {}), '(1000, self.poll_file)\n', (2195, 2217), False, 'from pyface.timer.api import Timer\n'), ((3314, 3347), 'numpy.searchsorted', 'nm.searchsorted', (['self.times', 'time'], {}), '(self.times, time)\n', (3329, 3347), True, 'import numpy as nm\n'), ((9798, 9840), 'numpy.zeros', 'nm.zeros', (['(vd.shape[0], 1)'], {'dtype': 'vd.dtype'}), '((vd.shape[0], 1), dtype=vd.dtype)\n', (9806, 9840), True, 'import numpy as nm\n'), ((10502, 10544), 'numpy.zeros', 'nm.zeros', (['(vd.shape[0], 1)'], {'dtype': 'vd.dtype'}), '((vd.shape[0], 1), dtype=vd.dtype)\n', (10510, 10544), True, 'import numpy as nm\n'), ((11168, 11210), 'numpy.zeros', 'nm.zeros', (['(vd.shape[0], 1)'], {'dtype': 'vd.dtype'}), '((vd.shape[0], 1), dtype=vd.dtype)\n', (11176, 11210), True, 'import numpy as nm\n')] |
from __future__ import absolute_import
import numpy as nm
from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr
from sfepy.base.timing import Timer
import six
def parse_approx_order(approx_order):
"""
Parse the uniform approximation order value (str or int).
"""
ao_msg = 'unsupported approximation order! (%s)'
force_bubble = False
discontinuous = False
if approx_order is None:
return 'iga', force_bubble, discontinuous
elif isinstance(approx_order, basestr):
if approx_order.startswith('iga'):
return approx_order, force_bubble, discontinuous
try:
ao = int(approx_order)
except ValueError:
mode = approx_order[-1].lower()
if mode == 'b':
ao = int(approx_order[:-1])
force_bubble = True
elif mode == 'd':
ao = int(approx_order[:-1])
discontinuous = True
else:
raise ValueError(ao_msg % approx_order)
if ao < 0:
raise ValueError(ao_msg % approx_order)
elif ao == 0:
discontinuous = True
return ao, force_bubble, discontinuous
def parse_shape(shape, dim):
if isinstance(shape, basestr):
try:
shape = {'scalar' : (1,),
'vector' : (dim,)}[shape]
except KeyError:
raise ValueError('unsupported field shape! (%s)', shape)
elif isinstance(shape, six.integer_types):
shape = (int(shape),)
return shape
def setup_extra_data(conn_info):
"""
Setup extra data required for non-volume integration.
"""
for key, ii, info in iter_dict_of_lists(conn_info, return_keys=True):
for var in info.all_vars:
field = var.get_field()
if var == info.primary:
field.setup_extra_data(info.ps_tg, info, info.is_trace)
def fields_from_conf(conf, regions):
fields = {}
for key, val in six.iteritems(conf):
field = Field.from_conf(val, regions)
fields[field.name] = field
return fields
class Field(Struct):
"""
Base class for fields.
"""
_all = None
@staticmethod
def from_args(name, dtype, shape, region, approx_order=1,
space='H1', poly_space_base='lagrange'):
"""
Create a Field subclass instance corresponding to a given space.
Parameters
----------
name : str
The field name.
dtype : numpy.dtype
The field data type: float64 or complex128.
shape : int/tuple/str
The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,)
or 3 or (3,)) or 'vector', or a tuple. The field shape determines
the shape of the FE base functions and is related to the number of
components of variables and to the DOF per node count, depending
on the field kind.
region : Region
The region where the field is defined.
approx_order : int/str
The FE approximation order, e.g. 0, 1, 2, '1B' (1 with bubble).
space : str
The function space name.
poly_space_base : str
The name of polynomial space base.
Notes
-----
Assumes one cell type for the whole region!
"""
conf = Struct(name=name, dtype=dtype, shape=shape, region=region.name,
approx_order=approx_order, space=space,
poly_space_base=poly_space_base)
return Field.from_conf(conf, {region.name : region})
@staticmethod
def from_conf(conf, regions):
"""
Create a Field subclass instance based on the configuration.
"""
if Field._all is None:
from sfepy import get_paths
from sfepy.base.base import load_classes
field_files = [ii for ii
in get_paths('sfepy/discrete/fem/fields*.py')
if 'fields_base.py' not in ii]
field_files += get_paths('sfepy/discrete/iga/fields*.py')
field_files += get_paths('sfepy/discrete/structural/fields*.py')
Field._all = load_classes(field_files, [Field], ignore_errors=True,
name_attr='family_name')
table = Field._all
space = conf.get('space', 'H1')
poly_space_base = conf.get('poly_space_base', 'lagrange')
key = space + '_' + poly_space_base
approx_order = parse_approx_order(conf.approx_order)
ao, force_bubble, discontinuous = approx_order
region = regions[conf.region]
if region.kind == 'cell':
# Volume fields.
kind = 'volume'
if discontinuous:
cls = table[kind + '_' + key + '_discontinuous']
else:
cls = table[kind + '_' + key]
obj = cls(conf.name, conf.dtype, conf.shape, region,
approx_order=approx_order[:2])
else:
# Surface fields.
kind = 'surface'
cls = table[kind + '_' + key]
obj = cls(conf.name, conf.dtype, conf.shape, region,
approx_order=approx_order[:2])
return obj
def _setup_kind(self):
name = self.get('family_name', None,
'An abstract Field method called!')
aux = name.split('_')
self.space = aux[1]
self.poly_space_base = aux[2]
def clear_mappings(self, clear_all=False):
"""
Clear current reference mappings.
"""
self.mappings = {}
if clear_all:
if hasattr(self, 'mappings0'):
self.mappings0.clear()
else:
self.mappings0 = {}
def save_mappings(self):
"""
Save current reference mappings to `mappings0` attribute.
"""
import sfepy.base.multiproc as multi
if multi.is_remote_dict(self.mappings0):
for k, v in six.iteritems(self.mappings):
m, _ = self.mappings[k]
nv = (m.bf, m.bfg, m.det, m.volume, m.normal)
self.mappings0[k] = nv
else:
self.mappings0 = self.mappings.copy()
def get_mapping(self, region, integral, integration,
get_saved=False, return_key=False):
"""
For given region, integral and integration type, get a reference
mapping, i.e. jacobians, element volumes and base function
derivatives for Volume-type geometries, and jacobians, normals
and base function derivatives for Surface-type geometries
corresponding to the field approximation.
The mappings are cached in the field instance in `mappings`
attribute. The mappings can be saved to `mappings0` using
`Field.save_mappings`. The saved mapping can be retrieved by
passing `get_saved=True`. If the required (saved) mapping
is not in cache, a new one is created.
Returns
-------
geo : CMapping instance
The reference mapping.
mapping : VolumeMapping or SurfaceMapping instance
The mapping.
key : tuple
The key of the mapping in `mappings` or `mappings0`.
"""
import sfepy.base.multiproc as multi
key = (region.name, integral.order, integration)
if get_saved:
out = self.mappings0.get(key, None)
if multi.is_remote_dict(self.mappings0) and out is not None:
m, i = self.create_mapping(region, integral, integration)
m.bf[:], m.bfg[:], m.det[:], m.volume[:] = out[0:4]
if m.normal is not None:
m.normal[:] = m[4]
out = m, i
else:
out = self.mappings.get(key, None)
if out is None:
out = self.create_mapping(region, integral, integration)
self.mappings[key] = out
if return_key:
out = out + (key,)
return out
def create_eval_mesh(self):
"""
Create a mesh for evaluating the field. The default implementation
returns None, because this mesh is for most fields the same as the one
created by `Field.create_mesh()`.
"""
def evaluate_at(self, coors, source_vals, mode='val', strategy='general',
close_limit=0.1, get_cells_fun=None, cache=None,
ret_cells=False, ret_status=False, ret_ref_coors=False,
verbose=False):
"""
Evaluate source DOF values corresponding to the field in the given
coordinates using the field interpolation.
Parameters
----------
coors : array, shape ``(n_coor, dim)``
The coordinates the source values should be interpolated into.
source_vals : array, shape ``(n_nod, n_components)``
The source DOF values corresponding to the field.
mode : {'val', 'grad'}, optional
The evaluation mode: the field value (default) or the field value
gradient.
strategy : {'general', 'convex'}, optional
The strategy for finding the elements that contain the
coordinates. For convex meshes, the 'convex' strategy might be
faster than the 'general' one.
close_limit : float, optional
The maximum limit distance of a point from the closest
element allowed for extrapolation.
get_cells_fun : callable, optional
If given, a function with signature ``get_cells_fun(coors, cmesh,
**kwargs)`` returning cells and offsets that potentially contain
points with the coordinates `coors`. Applicable only when
`strategy` is 'general'. When not given,
:func:`get_potential_cells()
<sfepy.discrete.common.global_interp.get_potential_cells>` is used.
cache : Struct, optional
To speed up a sequence of evaluations, the field mesh and other
data can be cached. Optionally, the cache can also contain the
reference element coordinates as `cache.ref_coors`, `cache.cells`
and `cache.status`, if the evaluation occurs in the same
coordinates repeatedly. In that case the mesh related data are
ignored. See :func:`Field.get_evaluate_cache()
<sfepy.discrete.fem.fields_base.FEField.get_evaluate_cache()>`.
ret_ref_coors : bool, optional
If True, return also the found reference element coordinates.
ret_status : bool, optional
If True, return also the enclosing cell status for each point.
ret_cells : bool, optional
If True, return also the cell indices the coordinates are in.
verbose : bool
If False, reduce verbosity.
Returns
-------
vals : array
The interpolated values with shape ``(n_coor, n_components)`` or
gradients with shape ``(n_coor, n_components, dim)`` according to
the `mode`. If `ret_status` is False, the values where the status
is greater than one are set to ``numpy.nan``.
ref_coors : array
The found reference element coordinates, if `ret_ref_coors` is True.
cells : array
The cell indices, if `ret_ref_coors` or `ret_cells` or `ret_status`
are True.
status : array
The status, if `ret_ref_coors` or `ret_status` are True, with the
following meaning: 0 is success, 1 is extrapolation within
`close_limit`, 2 is extrapolation outside `close_limit`, 3 is
failure, 4 is failure due to non-convergence of the Newton
iteration in tensor product cells. If close_limit is 0, then for
the 'general' strategy the status 5 indicates points outside of the
field domain that had no potential cells.
"""
from sfepy.discrete.common.global_interp import get_ref_coors
from sfepy.discrete.common.extmods.crefcoors import evaluate_in_rc
from sfepy.base.base import complex_types
output('evaluating in %d points...' % coors.shape[0], verbose=verbose)
ref_coors, cells, status = get_ref_coors(self, coors,
strategy=strategy,
close_limit=close_limit,
get_cells_fun=get_cells_fun,
cache=cache,
verbose=verbose)
timer = Timer(start=True)
# Interpolate to the reference coordinates.
source_dtype = nm.float64 if source_vals.dtype in complex_types\
else source_vals.dtype
if mode == 'val':
vals = nm.empty((coors.shape[0], source_vals.shape[1], 1),
dtype=source_dtype)
cmode = 0
elif mode == 'grad':
vals = nm.empty((coors.shape[0], source_vals.shape[1],
coors.shape[1]),
dtype=source_dtype)
cmode = 1
ctx = self.create_basis_context()
if source_vals.dtype in complex_types:
valsi = vals.copy()
evaluate_in_rc(vals, ref_coors, cells, status,
nm.ascontiguousarray(source_vals.real),
self.get_econn('volume', self.region), cmode, ctx)
evaluate_in_rc(valsi, ref_coors, cells, status,
nm.ascontiguousarray(source_vals.imag),
self.get_econn('volume', self.region), cmode, ctx)
vals = vals + valsi * 1j
else:
evaluate_in_rc(vals, ref_coors, cells, status, source_vals,
self.get_econn('volume', self.region), cmode, ctx)
output('interpolation: %f s' % timer.stop(),verbose=verbose)
output('...done',verbose=verbose)
if mode == 'val':
vals.shape = (coors.shape[0], source_vals.shape[1])
if not ret_status:
ii = nm.where(status > 1)[0]
vals[ii] = nm.nan
if ret_ref_coors:
return vals, ref_coors, cells, status
elif ret_status:
return vals, cells, status
elif ret_cells:
return vals, cells
else:
return vals
| [
"sfepy.get_paths",
"sfepy.base.base.Struct",
"sfepy.discrete.common.global_interp.get_ref_coors",
"sfepy.base.multiproc.is_remote_dict",
"sfepy.base.timing.Timer",
"sfepy.base.base.iter_dict_of_lists",
"sfepy.base.base.load_classes",
"sfepy.base.base.output"
] | [((1640, 1687), 'sfepy.base.base.iter_dict_of_lists', 'iter_dict_of_lists', (['conn_info'], {'return_keys': '(True)'}), '(conn_info, return_keys=True)\n', (1658, 1687), False, 'from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr\n'), ((1941, 1960), 'six.iteritems', 'six.iteritems', (['conf'], {}), '(conf)\n', (1954, 1960), False, 'import six\n'), ((3337, 3477), 'sfepy.base.base.Struct', 'Struct', ([], {'name': 'name', 'dtype': 'dtype', 'shape': 'shape', 'region': 'region.name', 'approx_order': 'approx_order', 'space': 'space', 'poly_space_base': 'poly_space_base'}), '(name=name, dtype=dtype, shape=shape, region=region.name,\n approx_order=approx_order, space=space, poly_space_base=poly_space_base)\n', (3343, 3477), False, 'from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr\n'), ((5974, 6010), 'sfepy.base.multiproc.is_remote_dict', 'multi.is_remote_dict', (['self.mappings0'], {}), '(self.mappings0)\n', (5994, 6010), True, 'import sfepy.base.multiproc as multi\n'), ((12248, 12318), 'sfepy.base.base.output', 'output', (["('evaluating in %d points...' % coors.shape[0])"], {'verbose': 'verbose'}), "('evaluating in %d points...' % coors.shape[0], verbose=verbose)\n", (12254, 12318), False, 'from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr\n'), ((12355, 12488), 'sfepy.discrete.common.global_interp.get_ref_coors', 'get_ref_coors', (['self', 'coors'], {'strategy': 'strategy', 'close_limit': 'close_limit', 'get_cells_fun': 'get_cells_fun', 'cache': 'cache', 'verbose': 'verbose'}), '(self, coors, strategy=strategy, close_limit=close_limit,\n get_cells_fun=get_cells_fun, cache=cache, verbose=verbose)\n', (12368, 12488), False, 'from sfepy.discrete.common.global_interp import get_ref_coors\n'), ((12747, 12764), 'sfepy.base.timing.Timer', 'Timer', ([], {'start': '(True)'}), '(start=True)\n', (12752, 12764), False, 'from sfepy.base.timing import Timer\n'), ((14118, 14152), 'sfepy.base.base.output', 'output', (['"""...done"""'], {'verbose': 'verbose'}), "('...done', verbose=verbose)\n", (14124, 14152), False, 'from sfepy.base.base import output, iter_dict_of_lists, Struct, basestr\n'), ((4045, 4087), 'sfepy.get_paths', 'get_paths', (['"""sfepy/discrete/iga/fields*.py"""'], {}), "('sfepy/discrete/iga/fields*.py')\n", (4054, 4087), False, 'from sfepy import get_paths\n'), ((4115, 4164), 'sfepy.get_paths', 'get_paths', (['"""sfepy/discrete/structural/fields*.py"""'], {}), "('sfepy/discrete/structural/fields*.py')\n", (4124, 4164), False, 'from sfepy import get_paths\n'), ((4190, 4269), 'sfepy.base.base.load_classes', 'load_classes', (['field_files', '[Field]'], {'ignore_errors': '(True)', 'name_attr': '"""family_name"""'}), "(field_files, [Field], ignore_errors=True, name_attr='family_name')\n", (4202, 4269), False, 'from sfepy.base.base import load_classes\n'), ((6036, 6064), 'six.iteritems', 'six.iteritems', (['self.mappings'], {}), '(self.mappings)\n', (6049, 6064), False, 'import six\n'), ((12971, 13042), 'numpy.empty', 'nm.empty', (['(coors.shape[0], source_vals.shape[1], 1)'], {'dtype': 'source_dtype'}), '((coors.shape[0], source_vals.shape[1], 1), dtype=source_dtype)\n', (12979, 13042), True, 'import numpy as nm\n'), ((7511, 7547), 'sfepy.base.multiproc.is_remote_dict', 'multi.is_remote_dict', (['self.mappings0'], {}), '(self.mappings0)\n', (7531, 7547), True, 'import sfepy.base.multiproc as multi\n'), ((13142, 13231), 'numpy.empty', 'nm.empty', (['(coors.shape[0], source_vals.shape[1], coors.shape[1])'], {'dtype': 'source_dtype'}), '((coors.shape[0], source_vals.shape[1], coors.shape[1]), dtype=\n source_dtype)\n', (13150, 13231), True, 'import numpy as nm\n'), ((13515, 13553), 'numpy.ascontiguousarray', 'nm.ascontiguousarray', (['source_vals.real'], {}), '(source_vals.real)\n', (13535, 13553), True, 'import numpy as nm\n'), ((13720, 13758), 'numpy.ascontiguousarray', 'nm.ascontiguousarray', (['source_vals.imag'], {}), '(source_vals.imag)\n', (13740, 13758), True, 'import numpy as nm\n'), ((14288, 14308), 'numpy.where', 'nm.where', (['(status > 1)'], {}), '(status > 1)\n', (14296, 14308), True, 'import numpy as nm\n'), ((3917, 3959), 'sfepy.get_paths', 'get_paths', (['"""sfepy/discrete/fem/fields*.py"""'], {}), "('sfepy/discrete/fem/fields*.py')\n", (3926, 3959), False, 'from sfepy import get_paths\n')] |
import numpy as nm
from sfepy.base.base import output, Struct
from sfepy.base.conf import ProblemConf, get_standard_keywords
from sfepy.homogenization.homogen_app import HomogenizationApp
from sfepy.homogenization.coefficients import Coefficients
import tables as pt
from sfepy.discrete.fem.meshio import HDF5MeshIO
import os.path as op
def get_homog_coefs_linear(ts, coor, mode,
micro_filename=None, regenerate=False,
coefs_filename=None):
oprefix = output.prefix
output.prefix = 'micro:'
required, other = get_standard_keywords()
required.remove( 'equations' )
conf = ProblemConf.from_file(micro_filename, required, other, verbose=False)
if coefs_filename is None:
coefs_filename = conf.options.get('coefs_filename', 'coefs')
coefs_filename = op.join(conf.options.get('output_dir', '.'),
coefs_filename) + '.h5'
if not regenerate:
if op.exists( coefs_filename ):
if not pt.isHDF5File( coefs_filename ):
regenerate = True
else:
regenerate = True
if regenerate:
options = Struct( output_filename_trunk = None )
app = HomogenizationApp( conf, options, 'micro:' )
coefs = app()
if type(coefs) is tuple:
coefs = coefs[0]
coefs.to_file_hdf5( coefs_filename )
else:
coefs = Coefficients.from_file_hdf5( coefs_filename )
out = {}
if mode == None:
for key, val in coefs.__dict__.iteritems():
out[key] = val
elif mode == 'qp':
for key, val in coefs.__dict__.iteritems():
if type( val ) == nm.ndarray or type(val) == nm.float64:
out[key] = nm.tile( val, (coor.shape[0], 1, 1) )
elif type(val) == dict:
for key2, val2 in val.iteritems():
if type(val2) == nm.ndarray or type(val2) == nm.float64:
out[key+'_'+key2] = \
nm.tile(val2, (coor.shape[0], 1, 1))
else:
out = None
output.prefix = oprefix
return out
def get_correctors_from_file( coefs_filename = 'coefs.h5',
dump_names = None ):
if dump_names == None:
coefs = Coefficients.from_file_hdf5( coefs_filename )
if hasattr( coefs, 'dump_names' ):
dump_names = coefs.dump_names
else:
raise ValueError( ' "filenames" coefficient must be used!' )
out = {}
for key, val in dump_names.iteritems():
corr_name = op.split( val )[-1]
io = HDF5MeshIO( val+'.h5' )
data = io.read_data( 0 )
dkeys = data.keys()
corr = {}
for dk in dkeys:
corr[dk] = data[dk].data.reshape(data[dk].shape)
out[corr_name] = corr
return out
| [
"sfepy.base.conf.ProblemConf.from_file",
"sfepy.discrete.fem.meshio.HDF5MeshIO",
"sfepy.base.base.Struct",
"sfepy.homogenization.coefficients.Coefficients.from_file_hdf5",
"sfepy.base.conf.get_standard_keywords",
"sfepy.homogenization.homogen_app.HomogenizationApp"
] | [((578, 601), 'sfepy.base.conf.get_standard_keywords', 'get_standard_keywords', ([], {}), '()\n', (599, 601), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((649, 718), 'sfepy.base.conf.ProblemConf.from_file', 'ProblemConf.from_file', (['micro_filename', 'required', 'other'], {'verbose': '(False)'}), '(micro_filename, required, other, verbose=False)\n', (670, 718), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((981, 1006), 'os.path.exists', 'op.exists', (['coefs_filename'], {}), '(coefs_filename)\n', (990, 1006), True, 'import os.path as op\n'), ((1178, 1212), 'sfepy.base.base.Struct', 'Struct', ([], {'output_filename_trunk': 'None'}), '(output_filename_trunk=None)\n', (1184, 1212), False, 'from sfepy.base.base import output, Struct\n'), ((1232, 1274), 'sfepy.homogenization.homogen_app.HomogenizationApp', 'HomogenizationApp', (['conf', 'options', '"""micro:"""'], {}), "(conf, options, 'micro:')\n", (1249, 1274), False, 'from sfepy.homogenization.homogen_app import HomogenizationApp\n'), ((1433, 1476), 'sfepy.homogenization.coefficients.Coefficients.from_file_hdf5', 'Coefficients.from_file_hdf5', (['coefs_filename'], {}), '(coefs_filename)\n', (1460, 1476), False, 'from sfepy.homogenization.coefficients import Coefficients\n'), ((2322, 2365), 'sfepy.homogenization.coefficients.Coefficients.from_file_hdf5', 'Coefficients.from_file_hdf5', (['coefs_filename'], {}), '(coefs_filename)\n', (2349, 2365), False, 'from sfepy.homogenization.coefficients import Coefficients\n'), ((2652, 2675), 'sfepy.discrete.fem.meshio.HDF5MeshIO', 'HDF5MeshIO', (["(val + '.h5')"], {}), "(val + '.h5')\n", (2662, 2675), False, 'from sfepy.discrete.fem.meshio import HDF5MeshIO\n'), ((2619, 2632), 'os.path.split', 'op.split', (['val'], {}), '(val)\n', (2627, 2632), True, 'import os.path as op\n'), ((1029, 1058), 'tables.isHDF5File', 'pt.isHDF5File', (['coefs_filename'], {}), '(coefs_filename)\n', (1042, 1058), True, 'import tables as pt\n'), ((1765, 1800), 'numpy.tile', 'nm.tile', (['val', '(coor.shape[0], 1, 1)'], {}), '(val, (coor.shape[0], 1, 1))\n', (1772, 1800), True, 'import numpy as nm\n'), ((2055, 2091), 'numpy.tile', 'nm.tile', (['val2', '(coor.shape[0], 1, 1)'], {}), '(val2, (coor.shape[0], 1, 1))\n', (2062, 2091), True, 'import numpy as nm\n')] |
#!/usr/bin/env python
r"""
Parallel assembling and solving of a Poisson's equation, using commands for
interactive use.
Find :math:`u` such that:
.. math::
\int_{\Omega} \nabla v \cdot \nabla u
= \int_{\Omega} v f
\;, \quad \forall s \;.
Important Notes
---------------
- This example requires petsc4py, mpi4py and (optionally) pymetis with their
dependencies installed!
- This example generates a number of files - do not use an existing non-empty
directory for the ``output_dir`` argument.
- Use the ``--clear`` option with care!
Notes
-----
- Each task is responsible for a subdomain consisting of a set of cells (a cell
region).
- Each subdomain owns PETSc DOFs within a consecutive range.
- When both global and task-local variables exist, the task-local
variables have ``_i`` suffix.
- This example does not use a nonlinear solver.
- This example can serve as a template for solving a linear single-field scalar
problem - just replace the equations in :func:`create_local_problem()`.
- The command line options are saved into <output_dir>/options.txt file.
Usage Examples
--------------
See all options::
$ python examples/diffusion/poisson_parallel_interactive.py -h
See PETSc options::
$ python examples/diffusion/poisson_parallel_interactive.py -help
Single process run useful for debugging with :func:`debug()
<sfepy.base.base.debug>`::
$ python examples/diffusion/poisson_parallel_interactive.py output-parallel
Parallel runs::
$ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101
$ mpiexec -n 3 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --metis
$ mpiexec -n 5 python examples/diffusion/poisson_parallel_interactive.py output-parallel -2 --shape=101,101 --verify --metis -ksp_monitor -ksp_converged_reason
View the results using::
$ python postproc.py output-parallel/sol.h5 --wireframe -b -d'u,plot_warp_scalar'
"""
from __future__ import absolute_import
from argparse import RawDescriptionHelpFormatter, ArgumentParser
import os
import sys
sys.path.append('.')
import csv
import numpy as nm
import matplotlib.pyplot as plt
from sfepy.base.base import output, Struct
from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options
from sfepy.base.timing import Timer
from sfepy.discrete.fem import Mesh, FEDomain, Field
from sfepy.discrete.common.region import Region
from sfepy.discrete import (FieldVariable, Material, Integral, Function,
Equation, Equations, Problem, State)
from sfepy.discrete.conditions import Conditions, EssentialBC
from sfepy.discrete.evaluate import apply_ebc_to_matrix
from sfepy.terms import Term
from sfepy.solvers.ls import PETScKrylovSolver
import sfepy.parallel.parallel as pl
import sfepy.parallel.plot_parallel_dofs as ppd
def create_local_problem(omega_gi, order):
"""
Local problem definition using a domain corresponding to the global region
`omega_gi`.
"""
mesh = omega_gi.domain.mesh
# All tasks have the whole mesh.
bbox = mesh.get_bounding_box()
min_x, max_x = bbox[:, 0]
eps_x = 1e-8 * (max_x - min_x)
mesh_i = Mesh.from_region(omega_gi, mesh, localize=True)
domain_i = FEDomain('domain_i', mesh_i)
omega_i = domain_i.create_region('Omega', 'all')
gamma1_i = domain_i.create_region('Gamma1',
'vertices in (x < %.10f)'
% (min_x + eps_x),
'facet', allow_empty=True)
gamma2_i = domain_i.create_region('Gamma2',
'vertices in (x > %.10f)'
% (max_x - eps_x),
'facet', allow_empty=True)
field_i = Field.from_args('fu', nm.float64, 1, omega_i,
approx_order=order)
output('number of local field DOFs:', field_i.n_nod)
u_i = FieldVariable('u_i', 'unknown', field_i)
v_i = FieldVariable('v_i', 'test', field_i, primary_var_name='u_i')
integral = Integral('i', order=2*order)
mat = Material('m', lam=10, mu=5)
t1 = Term.new('dw_laplace(m.lam, v_i, u_i)',
integral, omega_i, m=mat, v_i=v_i, u_i=u_i)
def _get_load(coors):
val = nm.ones_like(coors[:, 0])
for coor in coors.T:
val *= nm.sin(4 * nm.pi * coor)
return val
def get_load(ts, coors, mode=None, **kwargs):
if mode == 'qp':
return {'val' : _get_load(coors).reshape(coors.shape[0], 1, 1)}
load = Material('load', function=Function('get_load', get_load))
t2 = Term.new('dw_volume_lvf(load.val, v_i)',
integral, omega_i, load=load, v_i=v_i)
eq = Equation('balance', t1 - 100 * t2)
eqs = Equations([eq])
ebc1 = EssentialBC('ebc1', gamma1_i, {'u_i.all' : 0.0})
ebc2 = EssentialBC('ebc2', gamma2_i, {'u_i.all' : 0.1})
pb = Problem('problem_i', equations=eqs, active_only=False)
pb.time_update(ebcs=Conditions([ebc1, ebc2]))
pb.update_materials()
return pb
def verify_save_dof_maps(field, cell_tasks, dof_maps, id_map, options,
verbose=False):
vec = pl.verify_task_dof_maps(dof_maps, id_map, field, verbose=verbose)
order = options.order
mesh = field.domain.mesh
sfield = Field.from_args('aux', nm.float64, 'scalar', field.region,
approx_order=order)
aux = FieldVariable('aux', 'parameter', sfield,
primary_var_name='(set-to-None)')
out = aux.create_output(vec,
linearization=Struct(kind='adaptive',
min_level=order-1,
max_level=order-1,
eps=1e-8))
filename = os.path.join(options.output_dir,
'para-domains-dofs.h5')
if field.is_higher_order():
out['aux'].mesh.write(filename, out=out)
else:
mesh.write(filename, out=out)
out = Struct(name='cells', mode='cell',
data=cell_tasks[:, None, None, None])
filename = os.path.join(options.output_dir,
'para-domains-cells.h5')
mesh.write(filename, out={'cells' : out})
def solve_problem(mesh_filename, options, comm):
order = options.order
rank, size = comm.Get_rank(), comm.Get_size()
output('rank', rank, 'of', size)
stats = Struct()
timer = Timer('solve_timer')
timer.start()
mesh = Mesh.from_file(mesh_filename)
stats.t_read_mesh = timer.stop()
timer.start()
if rank == 0:
cell_tasks = pl.partition_mesh(mesh, size, use_metis=options.metis,
verbose=True)
else:
cell_tasks = None
stats.t_partition_mesh = timer.stop()
output('creating global domain and field...')
timer.start()
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order)
stats.t_create_global_fields = timer.stop()
output('...done in', timer.dt)
output('distributing field %s...' % field.name)
timer.start()
distribute = pl.distribute_fields_dofs
lfds, gfds = distribute([field], cell_tasks,
is_overlap=True,
save_inter_regions=options.save_inter_regions,
output_dir=options.output_dir,
comm=comm, verbose=True)
lfd = lfds[0]
stats.t_distribute_fields_dofs = timer.stop()
output('...done in', timer.dt)
if rank == 0:
dof_maps = gfds[0].dof_maps
id_map = gfds[0].id_map
if options.verify:
verify_save_dof_maps(field, cell_tasks,
dof_maps, id_map, options, verbose=True)
if options.plot:
ppd.plot_partitioning([None, None], field, cell_tasks, gfds[0],
options.output_dir, size)
output('creating local problem...')
timer.start()
omega_gi = Region.from_cells(lfd.cells, field.domain)
omega_gi.finalize()
omega_gi.update_shape()
pb = create_local_problem(omega_gi, order)
variables = pb.get_variables()
eqs = pb.equations
u_i = variables['u_i']
field_i = u_i.field
stats.t_create_local_problem = timer.stop()
output('...done in', timer.dt)
if options.plot:
ppd.plot_local_dofs([None, None], field, field_i, omega_gi,
options.output_dir, rank)
output('allocating global system...')
timer.start()
sizes, drange = pl.get_sizes(lfd.petsc_dofs_range, field.n_nod, 1)
output('sizes:', sizes)
output('drange:', drange)
pdofs = pl.get_local_ordering(field_i, lfd.petsc_dofs_conn)
output('pdofs:', pdofs)
pmtx, psol, prhs = pl.create_petsc_system(pb.mtx_a, sizes, pdofs, drange,
is_overlap=True, comm=comm,
verbose=True)
stats.t_allocate_global_system = timer.stop()
output('...done in', timer.dt)
output('evaluating local problem...')
timer.start()
state = State(variables)
state.fill(0.0)
state.apply_ebc()
rhs_i = eqs.eval_residuals(state())
# This must be after pl.create_petsc_system() call!
mtx_i = eqs.eval_tangent_matrices(state(), pb.mtx_a)
stats.t_evaluate_local_problem = timer.stop()
output('...done in', timer.dt)
output('assembling global system...')
timer.start()
apply_ebc_to_matrix(mtx_i, u_i.eq_map.eq_ebc)
pl.assemble_rhs_to_petsc(prhs, rhs_i, pdofs, drange, is_overlap=True,
comm=comm, verbose=True)
pl.assemble_mtx_to_petsc(pmtx, mtx_i, pdofs, drange, is_overlap=True,
comm=comm, verbose=True)
stats.t_assemble_global_system = timer.stop()
output('...done in', timer.dt)
output('creating solver...')
timer.start()
conf = Struct(method='cg', precond='gamg', sub_precond='none',
i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True)
status = {}
ls = PETScKrylovSolver(conf, comm=comm, mtx=pmtx, status=status)
stats.t_create_solver = timer.stop()
output('...done in', timer.dt)
output('solving...')
timer.start()
psol = ls(prhs, psol)
psol_i = pl.create_local_petsc_vector(pdofs)
gather, scatter = pl.create_gather_scatter(pdofs, psol_i, psol, comm=comm)
scatter(psol_i, psol)
sol0_i = state() - psol_i[...]
psol_i[...] = sol0_i
gather(psol, psol_i)
stats.t_solve = timer.stop()
output('...done in', timer.dt)
output('saving solution...')
timer.start()
u_i.set_data(sol0_i)
out = u_i.create_output()
filename = os.path.join(options.output_dir, 'sol_%02d.h5' % comm.rank)
pb.domain.mesh.write(filename, io='auto', out=out)
gather_to_zero = pl.create_gather_to_zero(psol)
psol_full = gather_to_zero(psol)
if comm.rank == 0:
sol = psol_full[...].copy()[id_map]
u = FieldVariable('u', 'parameter', field,
primary_var_name='(set-to-None)')
filename = os.path.join(options.output_dir, 'sol.h5')
if (order == 1) or (options.linearization == 'strip'):
out = u.create_output(sol)
mesh.write(filename, io='auto', out=out)
else:
out = u.create_output(sol, linearization=Struct(kind='adaptive',
min_level=0,
max_level=order,
eps=1e-3))
out['u'].mesh.write(filename, io='auto', out=out)
stats.t_save_solution = timer.stop()
output('...done in', timer.dt)
stats.t_total = timer.total
stats.n_dof = sizes[1]
stats.n_dof_local = sizes[0]
stats.n_cell = omega.shape.n_cell
stats.n_cell_local = omega_gi.shape.n_cell
if options.show:
plt.show()
return stats
def save_stats(filename, pars, stats, overwrite, rank, comm=None):
out = stats.to_dict()
names = sorted(out.keys())
shape_dict = {'n%d' % ii : pars.shape[ii] for ii in range(pars.dim)}
keys = ['size', 'rank', 'dim'] + list(shape_dict.keys()) + ['order'] + names
out['size'] = comm.size
out['rank'] = rank
out['dim'] = pars.dim
out.update(shape_dict)
out['order'] = pars.order
if rank == 0 and overwrite:
with open(filename, 'w') as fd:
writer = csv.DictWriter(fd, fieldnames=keys)
writer.writeheader()
writer.writerow(out)
else:
with open(filename, 'a') as fd:
writer = csv.DictWriter(fd, fieldnames=keys)
writer.writerow(out)
helps = {
'output_dir' :
'output directory',
'dims' :
'dimensions of the block [default: %(default)s]',
'shape' :
'shape (counts of nodes in x, y, z) of the block [default: %(default)s]',
'centre' :
'centre of the block [default: %(default)s]',
'2d' :
'generate a 2D rectangle, the third components of the above'
' options are ignored',
'order' :
'field approximation order',
'linearization' :
'linearization used for storing the results with approximation order > 1'
' [default: %(default)s]',
'metis' :
'use metis for domain partitioning',
'verify' :
'verify domain partitioning, save cells and DOFs of tasks'
' for visualization',
'plot' :
'make partitioning plots',
'save_inter_regions' :
'save inter-task regions for debugging partitioning problems',
'show' :
'show partitioning plots (implies --plot)',
'stats_filename' :
'name of the stats file for storing elapsed time statistics',
'new_stats' :
'create a new stats file with a header line (overwrites existing!)',
'silent' : 'do not print messages to screen',
'clear' :
'clear old solution files from output directory'
' (DANGEROUS - use with care!)',
}
def main():
parser = ArgumentParser(description=__doc__.rstrip(),
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('output_dir', help=helps['output_dir'])
parser.add_argument('--dims', metavar='dims',
action='store', dest='dims',
default='1.0,1.0,1.0', help=helps['dims'])
parser.add_argument('--shape', metavar='shape',
action='store', dest='shape',
default='11,11,11', help=helps['shape'])
parser.add_argument('--centre', metavar='centre',
action='store', dest='centre',
default='0.0,0.0,0.0', help=helps['centre'])
parser.add_argument('-2', '--2d',
action='store_true', dest='is_2d',
default=False, help=helps['2d'])
parser.add_argument('--order', metavar='int', type=int,
action='store', dest='order',
default=1, help=helps['order'])
parser.add_argument('--linearization', choices=['strip', 'adaptive'],
action='store', dest='linearization',
default='strip', help=helps['linearization'])
parser.add_argument('--metis',
action='store_true', dest='metis',
default=False, help=helps['metis'])
parser.add_argument('--verify',
action='store_true', dest='verify',
default=False, help=helps['verify'])
parser.add_argument('--plot',
action='store_true', dest='plot',
default=False, help=helps['plot'])
parser.add_argument('--show',
action='store_true', dest='show',
default=False, help=helps['show'])
parser.add_argument('--save-inter-regions',
action='store_true', dest='save_inter_regions',
default=False, help=helps['save_inter_regions'])
parser.add_argument('--stats', metavar='filename',
action='store', dest='stats_filename',
default=None, help=helps['stats_filename'])
parser.add_argument('--new-stats',
action='store_true', dest='new_stats',
default=False, help=helps['new_stats'])
parser.add_argument('--silent',
action='store_true', dest='silent',
default=False, help=helps['silent'])
parser.add_argument('--clear',
action='store_true', dest='clear',
default=False, help=helps['clear'])
options, petsc_opts = parser.parse_known_args()
if options.show:
options.plot = True
comm = pl.PETSc.COMM_WORLD
output_dir = options.output_dir
filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank)
if comm.rank == 0:
ensure_path(filename)
comm.barrier()
output.prefix = 'sfepy_%02d:' % comm.rank
output.set_output(filename=filename, combined=options.silent == False)
output('petsc options:', petsc_opts)
mesh_filename = os.path.join(options.output_dir, 'para.h5')
dim = 2 if options.is_2d else 3
dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim]
shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim]
centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim]
output('dimensions:', dims)
output('shape: ', shape)
output('centre: ', centre)
if comm.rank == 0:
from sfepy.mesh.mesh_generators import gen_block_mesh
if options.clear:
remove_files_patterns(output_dir,
['*.h5', '*.mesh', '*.txt', '*.png'],
ignores=['output_log_%02d.txt' % ii
for ii in range(comm.size)],
verbose=True)
save_options(os.path.join(output_dir, 'options.txt'),
[('options', vars(options))])
mesh = gen_block_mesh(dims, shape, centre, name='block-fem',
verbose=True)
mesh.write(mesh_filename, io='auto')
comm.barrier()
output('field order:', options.order)
stats = solve_problem(mesh_filename, options, comm)
output(stats)
if options.stats_filename:
if comm.rank == 0:
ensure_path(options.stats_filename)
comm.barrier()
pars = Struct(dim=dim, shape=shape, order=options.order)
pl.call_in_rank_order(
lambda rank, comm:
save_stats(options.stats_filename, pars, stats, options.new_stats,
rank, comm),
comm
)
if __name__ == '__main__':
main()
| [
"sfepy.parallel.parallel.assemble_rhs_to_petsc",
"sfepy.mesh.mesh_generators.gen_block_mesh",
"sfepy.parallel.parallel.create_gather_scatter",
"sfepy.base.ioutils.ensure_path",
"sfepy.parallel.parallel.create_local_petsc_vector",
"sfepy.discrete.fem.Mesh.from_region",
"sfepy.discrete.fem.Mesh.from_file"... | [((2114, 2134), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (2129, 2134), False, 'import sys\n'), ((3216, 3263), 'sfepy.discrete.fem.Mesh.from_region', 'Mesh.from_region', (['omega_gi', 'mesh'], {'localize': '(True)'}), '(omega_gi, mesh, localize=True)\n', (3232, 3263), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((3279, 3307), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""domain_i"""', 'mesh_i'], {}), "('domain_i', mesh_i)\n", (3287, 3307), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((3845, 3910), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""fu"""', 'nm.float64', '(1)', 'omega_i'], {'approx_order': 'order'}), "('fu', nm.float64, 1, omega_i, approx_order=order)\n", (3860, 3910), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((3946, 3998), 'sfepy.base.base.output', 'output', (['"""number of local field DOFs:"""', 'field_i.n_nod'], {}), "('number of local field DOFs:', field_i.n_nod)\n", (3952, 3998), False, 'from sfepy.base.base import output, Struct\n'), ((4010, 4050), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""u_i"""', '"""unknown"""', 'field_i'], {}), "('u_i', 'unknown', field_i)\n", (4023, 4050), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State\n'), ((4061, 4122), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""v_i"""', '"""test"""', 'field_i'], {'primary_var_name': '"""u_i"""'}), "('v_i', 'test', field_i, primary_var_name='u_i')\n", (4074, 4122), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State\n'), ((4139, 4169), 'sfepy.discrete.Integral', 'Integral', (['"""i"""'], {'order': '(2 * order)'}), "('i', order=2 * order)\n", (4147, 4169), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State\n'), ((4179, 4206), 'sfepy.discrete.Material', 'Material', (['"""m"""'], {'lam': '(10)', 'mu': '(5)'}), "('m', lam=10, mu=5)\n", (4187, 4206), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State\n'), ((4216, 4303), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_laplace(m.lam, v_i, u_i)"""', 'integral', 'omega_i'], {'m': 'mat', 'v_i': 'v_i', 'u_i': 'u_i'}), "('dw_laplace(m.lam, v_i, u_i)', integral, omega_i, m=mat, v_i=v_i,\n u_i=u_i)\n", (4224, 4303), False, 'from sfepy.terms import Term\n'), ((4709, 4788), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_volume_lvf(load.val, v_i)"""', 'integral', 'omega_i'], {'load': 'load', 'v_i': 'v_i'}), "('dw_volume_lvf(load.val, v_i)', integral, omega_i, load=load, v_i=v_i)\n", (4717, 4788), False, 'from sfepy.terms import Term\n'), ((4817, 4851), 'sfepy.discrete.Equation', 'Equation', (['"""balance"""', '(t1 - 100 * t2)'], {}), "('balance', t1 - 100 * t2)\n", (4825, 4851), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State\n'), ((4862, 4877), 'sfepy.discrete.Equations', 'Equations', (['[eq]'], {}), '([eq])\n', (4871, 4877), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State\n'), ((4890, 4937), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""ebc1"""', 'gamma1_i', "{'u_i.all': 0.0}"], {}), "('ebc1', gamma1_i, {'u_i.all': 0.0})\n", (4901, 4937), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((4950, 4997), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""ebc2"""', 'gamma2_i', "{'u_i.all': 0.1}"], {}), "('ebc2', gamma2_i, {'u_i.all': 0.1})\n", (4961, 4997), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((5009, 5063), 'sfepy.discrete.Problem', 'Problem', (['"""problem_i"""'], {'equations': 'eqs', 'active_only': '(False)'}), "('problem_i', equations=eqs, active_only=False)\n", (5016, 5063), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State\n'), ((5278, 5343), 'sfepy.parallel.parallel.verify_task_dof_maps', 'pl.verify_task_dof_maps', (['dof_maps', 'id_map', 'field'], {'verbose': 'verbose'}), '(dof_maps, id_map, field, verbose=verbose)\n', (5301, 5343), True, 'import sfepy.parallel.parallel as pl\n'), ((5414, 5492), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""aux"""', 'nm.float64', '"""scalar"""', 'field.region'], {'approx_order': 'order'}), "('aux', nm.float64, 'scalar', field.region, approx_order=order)\n", (5429, 5492), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((5532, 5607), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""aux"""', '"""parameter"""', 'sfield'], {'primary_var_name': '"""(set-to-None)"""'}), "('aux', 'parameter', sfield, primary_var_name='(set-to-None)')\n", (5545, 5607), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State\n'), ((5943, 5999), 'os.path.join', 'os.path.join', (['options.output_dir', '"""para-domains-dofs.h5"""'], {}), "(options.output_dir, 'para-domains-dofs.h5')\n", (5955, 5999), False, 'import os\n'), ((6169, 6240), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""cells"""', 'mode': '"""cell"""', 'data': 'cell_tasks[:, None, None, None]'}), "(name='cells', mode='cell', data=cell_tasks[:, None, None, None])\n", (6175, 6240), False, 'from sfepy.base.base import output, Struct\n'), ((6273, 6330), 'os.path.join', 'os.path.join', (['options.output_dir', '"""para-domains-cells.h5"""'], {}), "(options.output_dir, 'para-domains-cells.h5')\n", (6285, 6330), False, 'import os\n'), ((6537, 6569), 'sfepy.base.base.output', 'output', (['"""rank"""', 'rank', '"""of"""', 'size'], {}), "('rank', rank, 'of', size)\n", (6543, 6569), False, 'from sfepy.base.base import output, Struct\n'), ((6583, 6591), 'sfepy.base.base.Struct', 'Struct', ([], {}), '()\n', (6589, 6591), False, 'from sfepy.base.base import output, Struct\n'), ((6604, 6624), 'sfepy.base.timing.Timer', 'Timer', (['"""solve_timer"""'], {}), "('solve_timer')\n", (6609, 6624), False, 'from sfepy.base.timing import Timer\n'), ((6655, 6684), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['mesh_filename'], {}), '(mesh_filename)\n', (6669, 6684), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((6973, 7018), 'sfepy.base.base.output', 'output', (['"""creating global domain and field..."""'], {}), "('creating global domain and field...')\n", (6979, 7018), False, 'from sfepy.base.base import output, Struct\n'), ((7051, 7075), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""domain"""', 'mesh'], {}), "('domain', mesh)\n", (7059, 7075), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((7137, 7200), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""fu"""', 'nm.float64', '(1)', 'omega'], {'approx_order': 'order'}), "('fu', nm.float64, 1, omega, approx_order=order)\n", (7152, 7200), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((7254, 7284), 'sfepy.base.base.output', 'output', (['"""...done in"""', 'timer.dt'], {}), "('...done in', timer.dt)\n", (7260, 7284), False, 'from sfepy.base.base import output, Struct\n'), ((7290, 7337), 'sfepy.base.base.output', 'output', (["('distributing field %s...' % field.name)"], {}), "('distributing field %s...' % field.name)\n", (7296, 7337), False, 'from sfepy.base.base import output, Struct\n'), ((7754, 7784), 'sfepy.base.base.output', 'output', (['"""...done in"""', 'timer.dt'], {}), "('...done in', timer.dt)\n", (7760, 7784), False, 'from sfepy.base.base import output, Struct\n'), ((8193, 8228), 'sfepy.base.base.output', 'output', (['"""creating local problem..."""'], {}), "('creating local problem...')\n", (8199, 8228), False, 'from sfepy.base.base import output, Struct\n'), ((8263, 8305), 'sfepy.discrete.common.region.Region.from_cells', 'Region.from_cells', (['lfd.cells', 'field.domain'], {}), '(lfd.cells, field.domain)\n', (8280, 8305), False, 'from sfepy.discrete.common.region import Region\n'), ((8570, 8600), 'sfepy.base.base.output', 'output', (['"""...done in"""', 'timer.dt'], {}), "('...done in', timer.dt)\n", (8576, 8600), False, 'from sfepy.base.base import output, Struct\n'), ((8750, 8787), 'sfepy.base.base.output', 'output', (['"""allocating global system..."""'], {}), "('allocating global system...')\n", (8756, 8787), False, 'from sfepy.base.base import output, Struct\n'), ((8827, 8877), 'sfepy.parallel.parallel.get_sizes', 'pl.get_sizes', (['lfd.petsc_dofs_range', 'field.n_nod', '(1)'], {}), '(lfd.petsc_dofs_range, field.n_nod, 1)\n', (8839, 8877), True, 'import sfepy.parallel.parallel as pl\n'), ((8882, 8905), 'sfepy.base.base.output', 'output', (['"""sizes:"""', 'sizes'], {}), "('sizes:', sizes)\n", (8888, 8905), False, 'from sfepy.base.base import output, Struct\n'), ((8910, 8935), 'sfepy.base.base.output', 'output', (['"""drange:"""', 'drange'], {}), "('drange:', drange)\n", (8916, 8935), False, 'from sfepy.base.base import output, Struct\n'), ((8949, 9000), 'sfepy.parallel.parallel.get_local_ordering', 'pl.get_local_ordering', (['field_i', 'lfd.petsc_dofs_conn'], {}), '(field_i, lfd.petsc_dofs_conn)\n', (8970, 9000), True, 'import sfepy.parallel.parallel as pl\n'), ((9006, 9029), 'sfepy.base.base.output', 'output', (['"""pdofs:"""', 'pdofs'], {}), "('pdofs:', pdofs)\n", (9012, 9029), False, 'from sfepy.base.base import output, Struct\n'), ((9054, 9154), 'sfepy.parallel.parallel.create_petsc_system', 'pl.create_petsc_system', (['pb.mtx_a', 'sizes', 'pdofs', 'drange'], {'is_overlap': '(True)', 'comm': 'comm', 'verbose': '(True)'}), '(pb.mtx_a, sizes, pdofs, drange, is_overlap=True,\n comm=comm, verbose=True)\n', (9076, 9154), True, 'import sfepy.parallel.parallel as pl\n'), ((9298, 9328), 'sfepy.base.base.output', 'output', (['"""...done in"""', 'timer.dt'], {}), "('...done in', timer.dt)\n", (9304, 9328), False, 'from sfepy.base.base import output, Struct\n'), ((9334, 9371), 'sfepy.base.base.output', 'output', (['"""evaluating local problem..."""'], {}), "('evaluating local problem...')\n", (9340, 9371), False, 'from sfepy.base.base import output, Struct\n'), ((9403, 9419), 'sfepy.discrete.State', 'State', (['variables'], {}), '(variables)\n', (9408, 9419), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State\n'), ((9671, 9701), 'sfepy.base.base.output', 'output', (['"""...done in"""', 'timer.dt'], {}), "('...done in', timer.dt)\n", (9677, 9701), False, 'from sfepy.base.base import output, Struct\n'), ((9707, 9744), 'sfepy.base.base.output', 'output', (['"""assembling global system..."""'], {}), "('assembling global system...')\n", (9713, 9744), False, 'from sfepy.base.base import output, Struct\n'), ((9768, 9813), 'sfepy.discrete.evaluate.apply_ebc_to_matrix', 'apply_ebc_to_matrix', (['mtx_i', 'u_i.eq_map.eq_ebc'], {}), '(mtx_i, u_i.eq_map.eq_ebc)\n', (9787, 9813), False, 'from sfepy.discrete.evaluate import apply_ebc_to_matrix\n'), ((9818, 9917), 'sfepy.parallel.parallel.assemble_rhs_to_petsc', 'pl.assemble_rhs_to_petsc', (['prhs', 'rhs_i', 'pdofs', 'drange'], {'is_overlap': '(True)', 'comm': 'comm', 'verbose': '(True)'}), '(prhs, rhs_i, pdofs, drange, is_overlap=True, comm=\n comm, verbose=True)\n', (9842, 9917), True, 'import sfepy.parallel.parallel as pl\n'), ((9946, 10045), 'sfepy.parallel.parallel.assemble_mtx_to_petsc', 'pl.assemble_mtx_to_petsc', (['pmtx', 'mtx_i', 'pdofs', 'drange'], {'is_overlap': '(True)', 'comm': 'comm', 'verbose': '(True)'}), '(pmtx, mtx_i, pdofs, drange, is_overlap=True, comm=\n comm, verbose=True)\n', (9970, 10045), True, 'import sfepy.parallel.parallel as pl\n'), ((10125, 10155), 'sfepy.base.base.output', 'output', (['"""...done in"""', 'timer.dt'], {}), "('...done in', timer.dt)\n", (10131, 10155), False, 'from sfepy.base.base import output, Struct\n'), ((10161, 10189), 'sfepy.base.base.output', 'output', (['"""creating solver..."""'], {}), "('creating solver...')\n", (10167, 10189), False, 'from sfepy.base.base import output, Struct\n'), ((10220, 10348), 'sfepy.base.base.Struct', 'Struct', ([], {'method': '"""cg"""', 'precond': '"""gamg"""', 'sub_precond': '"""none"""', 'i_max': '(10000)', 'eps_a': '(1e-50)', 'eps_r': '(1e-05)', 'eps_d': '(10000.0)', 'verbose': '(True)'}), "(method='cg', precond='gamg', sub_precond='none', i_max=10000, eps_a=\n 1e-50, eps_r=1e-05, eps_d=10000.0, verbose=True)\n", (10226, 10348), False, 'from sfepy.base.base import output, Struct\n'), ((10382, 10441), 'sfepy.solvers.ls.PETScKrylovSolver', 'PETScKrylovSolver', (['conf'], {'comm': 'comm', 'mtx': 'pmtx', 'status': 'status'}), '(conf, comm=comm, mtx=pmtx, status=status)\n', (10399, 10441), False, 'from sfepy.solvers.ls import PETScKrylovSolver\n'), ((10488, 10518), 'sfepy.base.base.output', 'output', (['"""...done in"""', 'timer.dt'], {}), "('...done in', timer.dt)\n", (10494, 10518), False, 'from sfepy.base.base import output, Struct\n'), ((10524, 10544), 'sfepy.base.base.output', 'output', (['"""solving..."""'], {}), "('solving...')\n", (10530, 10544), False, 'from sfepy.base.base import output, Struct\n'), ((10604, 10639), 'sfepy.parallel.parallel.create_local_petsc_vector', 'pl.create_local_petsc_vector', (['pdofs'], {}), '(pdofs)\n', (10632, 10639), True, 'import sfepy.parallel.parallel as pl\n'), ((10662, 10718), 'sfepy.parallel.parallel.create_gather_scatter', 'pl.create_gather_scatter', (['pdofs', 'psol_i', 'psol'], {'comm': 'comm'}), '(pdofs, psol_i, psol, comm=comm)\n', (10686, 10718), True, 'import sfepy.parallel.parallel as pl\n'), ((10871, 10901), 'sfepy.base.base.output', 'output', (['"""...done in"""', 'timer.dt'], {}), "('...done in', timer.dt)\n", (10877, 10901), False, 'from sfepy.base.base import output, Struct\n'), ((10907, 10935), 'sfepy.base.base.output', 'output', (['"""saving solution..."""'], {}), "('saving solution...')\n", (10913, 10935), False, 'from sfepy.base.base import output, Struct\n'), ((11026, 11085), 'os.path.join', 'os.path.join', (['options.output_dir', "('sol_%02d.h5' % comm.rank)"], {}), "(options.output_dir, 'sol_%02d.h5' % comm.rank)\n", (11038, 11085), False, 'import os\n'), ((11163, 11193), 'sfepy.parallel.parallel.create_gather_to_zero', 'pl.create_gather_to_zero', (['psol'], {}), '(psol)\n', (11187, 11193), True, 'import sfepy.parallel.parallel as pl\n'), ((12052, 12082), 'sfepy.base.base.output', 'output', (['"""...done in"""', 'timer.dt'], {}), "('...done in', timer.dt)\n", (12058, 12082), False, 'from sfepy.base.base import output, Struct\n'), ((17239, 17298), 'os.path.join', 'os.path.join', (['output_dir', "('output_log_%02d.txt' % comm.rank)"], {}), "(output_dir, 'output_log_%02d.txt' % comm.rank)\n", (17251, 17298), False, 'import os\n'), ((17422, 17492), 'sfepy.base.base.output.set_output', 'output.set_output', ([], {'filename': 'filename', 'combined': '(options.silent == False)'}), '(filename=filename, combined=options.silent == False)\n', (17439, 17492), False, 'from sfepy.base.base import output, Struct\n'), ((17498, 17534), 'sfepy.base.base.output', 'output', (['"""petsc options:"""', 'petsc_opts'], {}), "('petsc options:', petsc_opts)\n", (17504, 17534), False, 'from sfepy.base.base import output, Struct\n'), ((17556, 17599), 'os.path.join', 'os.path.join', (['options.output_dir', '"""para.h5"""'], {}), "(options.output_dir, 'para.h5')\n", (17568, 17599), False, 'import os\n'), ((17837, 17864), 'sfepy.base.base.output', 'output', (['"""dimensions:"""', 'dims'], {}), "('dimensions:', dims)\n", (17843, 17864), False, 'from sfepy.base.base import output, Struct\n'), ((17869, 17897), 'sfepy.base.base.output', 'output', (['"""shape: """', 'shape'], {}), "('shape: ', shape)\n", (17875, 17897), False, 'from sfepy.base.base import output, Struct\n'), ((17902, 17931), 'sfepy.base.base.output', 'output', (['"""centre: """', 'centre'], {}), "('centre: ', centre)\n", (17908, 17931), False, 'from sfepy.base.base import output, Struct\n'), ((18651, 18688), 'sfepy.base.base.output', 'output', (['"""field order:"""', 'options.order'], {}), "('field order:', options.order)\n", (18657, 18688), False, 'from sfepy.base.base import output, Struct\n'), ((18750, 18763), 'sfepy.base.base.output', 'output', (['stats'], {}), '(stats)\n', (18756, 18763), False, 'from sfepy.base.base import output, Struct\n'), ((4359, 4384), 'numpy.ones_like', 'nm.ones_like', (['coors[:, 0]'], {}), '(coors[:, 0])\n', (4371, 4384), True, 'import numpy as nm\n'), ((6780, 6848), 'sfepy.parallel.parallel.partition_mesh', 'pl.partition_mesh', (['mesh', 'size'], {'use_metis': 'options.metis', 'verbose': '(True)'}), '(mesh, size, use_metis=options.metis, verbose=True)\n', (6797, 6848), True, 'import sfepy.parallel.parallel as pl\n'), ((8631, 8721), 'sfepy.parallel.plot_parallel_dofs.plot_local_dofs', 'ppd.plot_local_dofs', (['[None, None]', 'field', 'field_i', 'omega_gi', 'options.output_dir', 'rank'], {}), '([None, None], field, field_i, omega_gi, options.\n output_dir, rank)\n', (8650, 8721), True, 'import sfepy.parallel.plot_parallel_dofs as ppd\n'), ((11313, 11385), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""u"""', '"""parameter"""', 'field'], {'primary_var_name': '"""(set-to-None)"""'}), "('u', 'parameter', field, primary_var_name='(set-to-None)')\n", (11326, 11385), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State\n'), ((11432, 11474), 'os.path.join', 'os.path.join', (['options.output_dir', '"""sol.h5"""'], {}), "(options.output_dir, 'sol.h5')\n", (11444, 11474), False, 'import os\n'), ((12292, 12302), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12300, 12302), True, 'import matplotlib.pyplot as plt\n'), ((17330, 17351), 'sfepy.base.ioutils.ensure_path', 'ensure_path', (['filename'], {}), '(filename)\n', (17341, 17351), False, 'from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options\n'), ((18483, 18550), 'sfepy.mesh.mesh_generators.gen_block_mesh', 'gen_block_mesh', (['dims', 'shape', 'centre'], {'name': '"""block-fem"""', 'verbose': '(True)'}), "(dims, shape, centre, name='block-fem', verbose=True)\n", (18497, 18550), False, 'from sfepy.mesh.mesh_generators import gen_block_mesh\n'), ((18910, 18959), 'sfepy.base.base.Struct', 'Struct', ([], {'dim': 'dim', 'shape': 'shape', 'order': 'options.order'}), '(dim=dim, shape=shape, order=options.order)\n', (18916, 18959), False, 'from sfepy.base.base import output, Struct\n'), ((4433, 4457), 'numpy.sin', 'nm.sin', (['(4 * nm.pi * coor)'], {}), '(4 * nm.pi * coor)\n', (4439, 4457), True, 'import numpy as nm\n'), ((4667, 4697), 'sfepy.discrete.Function', 'Function', (['"""get_load"""', 'get_load'], {}), "('get_load', get_load)\n", (4675, 4697), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem, State\n'), ((5088, 5112), 'sfepy.discrete.conditions.Conditions', 'Conditions', (['[ebc1, ebc2]'], {}), '([ebc1, ebc2])\n', (5098, 5112), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((5707, 5783), 'sfepy.base.base.Struct', 'Struct', ([], {'kind': '"""adaptive"""', 'min_level': '(order - 1)', 'max_level': '(order - 1)', 'eps': '(1e-08)'}), "(kind='adaptive', min_level=order - 1, max_level=order - 1, eps=1e-08)\n", (5713, 5783), False, 'from sfepy.base.base import output, Struct\n'), ((8064, 8158), 'sfepy.parallel.plot_parallel_dofs.plot_partitioning', 'ppd.plot_partitioning', (['[None, None]', 'field', 'cell_tasks', 'gfds[0]', 'options.output_dir', 'size'], {}), '([None, None], field, cell_tasks, gfds[0], options.\n output_dir, size)\n', (8085, 8158), True, 'import sfepy.parallel.plot_parallel_dofs as ppd\n'), ((12829, 12864), 'csv.DictWriter', 'csv.DictWriter', (['fd'], {'fieldnames': 'keys'}), '(fd, fieldnames=keys)\n', (12843, 12864), False, 'import csv\n'), ((13003, 13038), 'csv.DictWriter', 'csv.DictWriter', (['fd'], {'fieldnames': 'keys'}), '(fd, fieldnames=keys)\n', (13017, 13038), False, 'import csv\n'), ((18375, 18414), 'os.path.join', 'os.path.join', (['output_dir', '"""options.txt"""'], {}), "(output_dir, 'options.txt')\n", (18387, 18414), False, 'import os\n'), ((18835, 18870), 'sfepy.base.ioutils.ensure_path', 'ensure_path', (['options.stats_filename'], {}), '(options.stats_filename)\n', (18846, 18870), False, 'from sfepy.base.ioutils import ensure_path, remove_files_patterns, save_options\n'), ((11698, 11762), 'sfepy.base.base.Struct', 'Struct', ([], {'kind': '"""adaptive"""', 'min_level': '(0)', 'max_level': 'order', 'eps': '(0.001)'}), "(kind='adaptive', min_level=0, max_level=order, eps=0.001)\n", (11704, 11762), False, 'from sfepy.base.base import output, Struct\n')] |
#!/usr/bin/env python
r"""
This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose
contribution to the deformation energy density per unit reference volume is
given by
.. math::
W = K \, \left( \overline I_1 - 3 \right)^{p}
where :math:`\overline I_1` is the first main invariant of the deviatoric part
of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p`
are its parameters.
This term may be used to implement the generalized Yeoh hyperelastic material
model [1] by adding three such terms:
.. math::
W =
K_1 \, \left( \overline I_1 - 3 \right)^{m}
+K_2 \, \left( \overline I_1 - 3 \right)^{p}
+K_3 \, \left( \overline I_1 - 3 \right)^{q}
where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are
material parameters. Only a single term is used in this example for the sake of
simplicity.
Components of the second Piola-Kirchhoff stress are in the case of an
incompressible material
.. math::
S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;,
where :math:`p` is the hydrostatic pressure.
The large deformation is described using the total Lagrangian formulation in
this example. The incompressibility is treated by mixed displacement-pressure
formulation. The weak formulation is:
Find the displacement field :math:`\ul{u}` and pressure field :math:`p`
such that:
.. math::
\intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v})
\difd{V} = 0
\;, \quad \forall \ul{v} \;,
\intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0
\;, \quad \forall q \;.
The following formula holds for the axial true (Cauchy) stress in the case of
uniaxial stress:
.. math::
\sigma(\lambda) =
\frac{2}{3} \, m \, K_1 \,
\left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \,
\left( \lambda - \frac{1}{\lambda^2} \right) \;,
where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and
:math:`l` being the original and deformed specimen length respectively).
The boundary conditions are set so that a state of uniaxial stress is achieved,
i.e. appropriate components of displacement are fixed on the "Left", "Bottom",
and "Near" faces and a monotonously increasing displacement is prescribed on
the "Right" face. This prescribed displacement is then used to calculate
:math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true
(Cauchy) stress.
Note on material parameters
---------------------------
The three-term generalized Yeoh model is meant to be used for modelling of
filled rubbers. The following choice of parameters is suggested [1] based on
experimental data and stability considerations:
:math:`K_1 > 0`,
:math:`K_2 < 0`,
:math:`K_3 > 0`,
:math:`0.7 < m < 1`,
:math:`m < p < q`.
Usage Examples
--------------
Default options::
$ python examples/large_deformation/gen_yeoh_tl_up_interactive.py
To show a comparison of stress against the analytic formula::
$ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p
Using different mesh fineness::
$ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \
--shape "5, 5, 5"
Different dimensions of the computational domain::
$ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \
--dims "2, 1, 3"
Different length of time interval and/or number of time steps::
$ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \
-t 0,15,21
Use higher approximation order (the ``-t`` option to decrease the time step is
required for convergence here)::
$ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \
--order 2 -t 0,2,21
Change material parameters::
$ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1
View the results using ``resview.py``
-------------------------------------
Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back)::
$ python resview.py --fields=p:f1:wu:p1 domain.??.vtk
Show the axial component of stress (second Piola-Kirchhoff)::
$ python resview.py --fields=stress:c0 domain.??.vtk
[1] <NAME>, <NAME>, <NAME>, <NAME>.
Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In
Highly Filled Elastomers And Implementation With User-Defined Material
Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp.
653-686 (2019)
"""
from __future__ import print_function, absolute_import
import argparse
import sys
SFEPY_DIR = '.'
sys.path.append(SFEPY_DIR)
import matplotlib.pyplot as plt
import numpy as np
from sfepy.base.base import IndexedStruct, Struct
from sfepy.discrete import (
FieldVariable, Material, Integral, Function, Equation, Equations, Problem)
from sfepy.discrete.conditions import Conditions, EssentialBC
from sfepy.discrete.fem import FEDomain, Field
from sfepy.homogenization.utils import define_box_regions
from sfepy.mesh.mesh_generators import gen_block_mesh
from sfepy.solvers.ls import ScipyDirect
from sfepy.solvers.nls import Newton
from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver
from sfepy.terms import Term
DIMENSION = 3
def get_displacement(ts, coors, bc=None, problem=None):
"""
Define the time-dependent displacement.
"""
out = 1. * ts.time * coors[:, 0]
return out
def _get_analytic_stress(stretches, coef, exp):
out = np.array([
2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1)
* (stretch - stretch**-2)
if (stretch**2 + 2 / stretch > 3) else 0.
for stretch in stretches])
return out
def plot_graphs(
material_parameters, global_stress, global_displacement,
undeformed_length):
"""
Plot a comparison of the nominal stress computed by the FEM and using the
analytic formula.
Parameters
----------
material_parameters : list or tuple of float
The K_1 coefficient and exponent m.
global_displacement
The total displacement for each time step, from the FEM.
global_stress
The true (Cauchy) stress for each time step, from the FEM.
undeformed_length : float
The length of the undeformed specimen.
"""
coef, exp = material_parameters
stretch = 1 + np.array(global_displacement) / undeformed_length
# axial stress values
stress_fem_2pk = np.array([sig for sig in global_stress])
stress_fem = stress_fem_2pk * stretch
stress_analytic = _get_analytic_stress(stretch, coef, exp)
fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True)
ax_stress.plot(stretch, stress_fem, '.-', label='FEM')
ax_stress.plot(stretch, stress_analytic, '--', label='analytic')
ax_difference.plot(stretch, stress_fem - stress_analytic, '.-')
ax_stress.legend(loc='best').set_draggable(True)
ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$')
ax_stress.grid()
ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$')
ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$')
ax_difference.grid()
plt.tight_layout()
plt.show()
def stress_strain(
out, problem, _state, order=1, global_stress=None,
global_displacement=None, **_):
"""
Compute the stress and the strain and add them to the output.
Parameters
----------
out : dict
Holds the results of the finite element computation.
problem : sfepy.discrete.Problem
order : int
The approximation order of the displacement field.
global_displacement
Total displacement for each time step, current value will be appended.
global_stress
The true (Cauchy) stress for each time step, current value will be
appended.
Returns
-------
out : dict
"""
strain = problem.evaluate(
'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order),
mode='el_avg', term_mode='strain', copy_materials=False)
out['green_strain'] = Struct(
name='output_data', mode='cell', data=strain, dofs=None)
stress_1 = problem.evaluate(
'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order),
mode='el_avg', term_mode='stress', copy_materials=False)
stress_p = problem.evaluate(
'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order),
mode='el_avg', term_mode='stress', copy_materials=False)
stress = stress_1 + stress_p
out['stress'] = Struct(
name='output_data', mode='cell', data=stress, dofs=None)
global_stress.append(stress[0, 0, 0, 0])
global_displacement.append(get_displacement(
problem.ts, np.array([[1., 0, 0]]))[0])
return out
def main(cli_args):
dims = parse_argument_list(cli_args.dims, float)
shape = parse_argument_list(cli_args.shape, int)
centre = parse_argument_list(cli_args.centre, float)
material_parameters = parse_argument_list(cli_args.material_parameters,
float)
order = cli_args.order
ts_vals = cli_args.ts.split(',')
ts = {
't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]),
'n_step' : int(ts_vals[2])}
do_plot = cli_args.plot
### Mesh and regions ###
mesh = gen_block_mesh(
dims, shape, centre, name='block', verbose=False)
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
lbn, rtf = domain.get_mesh_bounding_box()
box_regions = define_box_regions(3, lbn, rtf)
regions = dict([
[r, domain.create_region(r, box_regions[r][0], box_regions[r][1])]
for r in box_regions])
### Fields ###
scalar_field = Field.from_args(
'fu', np.float64, 'scalar', omega, approx_order=order-1)
vector_field = Field.from_args(
'fv', np.float64, 'vector', omega, approx_order=order)
u = FieldVariable('u', 'unknown', vector_field, history=1)
v = FieldVariable('v', 'test', vector_field, primary_var_name='u')
p = FieldVariable('p', 'unknown', scalar_field, history=1)
q = FieldVariable('q', 'test', scalar_field, primary_var_name='p')
### Material ###
coefficient, exponent = material_parameters
m_1 = Material(
'm1', par=[coefficient, exponent],
)
### Boundary conditions ###
x_sym = EssentialBC('x_sym', regions['Left'], {'u.0' : 0.0})
y_sym = EssentialBC('y_sym', regions['Near'], {'u.1' : 0.0})
z_sym = EssentialBC('z_sym', regions['Bottom'], {'u.2' : 0.0})
disp_fun = Function('disp_fun', get_displacement)
displacement = EssentialBC(
'displacement', regions['Right'], {'u.0' : disp_fun})
ebcs = Conditions([x_sym, y_sym, z_sym, displacement])
### Terms and equations ###
integral = Integral('i', order=2*order+1)
term_1 = Term.new(
'dw_tl_he_genyeoh(m1.par, v, u)',
integral, omega, m1=m_1, v=v, u=u)
term_pressure = Term.new(
'dw_tl_bulk_pressure(v, u, p)',
integral, omega, v=v, u=u, p=p)
term_volume_change = Term.new(
'dw_tl_volume(q, u)',
integral, omega, q=q, u=u, term_mode='volume')
term_volume = Term.new(
'dw_volume_integrate(q)',
integral, omega, q=q)
eq_balance = Equation('balance', term_1 + term_pressure)
eq_volume = Equation('volume', term_volume_change - term_volume)
equations = Equations([eq_balance, eq_volume])
### Solvers ###
ls = ScipyDirect({})
nls_status = IndexedStruct()
nls = Newton(
{'i_max' : 20},
lin_solver=ls, status=nls_status
)
### Problem ###
pb = Problem('hyper', equations=equations)
pb.set_bcs(ebcs=ebcs)
pb.set_ics(ics=Conditions([]))
tss = SimpleTimeSteppingSolver(ts, nls=nls, context=pb)
pb.set_solver(tss)
### Solution ###
axial_stress = []
axial_displacement = []
def stress_strain_fun(*args, **kwargs):
return stress_strain(
*args, order=order, global_stress=axial_stress,
global_displacement=axial_displacement, **kwargs)
pb.solve(save_results=True, post_process_hook=stress_strain_fun)
if do_plot:
plot_graphs(
material_parameters, axial_stress, axial_displacement,
undeformed_length=dims[0])
def parse_argument_list(cli_arg, type_fun=None, value_separator=','):
"""
Split the command-line argument into a list of items of given type.
Parameters
----------
cli_arg : str
type_fun : function
A function to be called on each substring of `cli_arg`; default: str.
value_separator : str
"""
if type_fun is None:
type_fun = str
out = [type_fun(value) for value in cli_arg.split(value_separator)]
return out
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument(
'--order', type=int, default=1, help='The approximation order of the '
'displacement field [default: %(default)s]')
parser.add_argument(
'-m', '--material-parameters', default='0.5, 0.9',
help='Material parameters - coefficient and exponent - of a single '
'term of the generalized Yeoh hyperelastic model. '
'[default: %(default)s]')
parser.add_argument(
'--dims', default="1.0, 1.0, 1.0",
help='Dimensions of the block [default: %(default)s]')
parser.add_argument(
'--shape', default='2, 2, 2',
help='Shape (counts of nodes in x, y, z) of the block [default: '
'%(default)s]')
parser.add_argument(
'--centre', default='0.5, 0.5, 0.5',
help='Centre of the block [default: %(default)s]')
parser.add_argument(
'-p', '--plot', action='store_true', default=False,
help='Whether to plot a comparison with analytical formula.')
parser.add_argument(
'-t', '--ts',
type=str, default='0.0,2.0,11',
help='Start time, end time, and number of time steps [default: '
'"%(default)s"]')
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
main(args)
| [
"sfepy.mesh.mesh_generators.gen_block_mesh",
"sfepy.solvers.ts_solvers.SimpleTimeSteppingSolver",
"sfepy.homogenization.utils.define_box_regions",
"sfepy.solvers.nls.Newton",
"sfepy.discrete.Problem",
"sfepy.discrete.Integral",
"sfepy.discrete.fem.Field.from_args",
"sfepy.base.base.Struct",
"sfepy.d... | [((4494, 4520), 'sys.path.append', 'sys.path.append', (['SFEPY_DIR'], {}), '(SFEPY_DIR)\n', (4509, 4520), False, 'import sys\n'), ((5366, 5546), 'numpy.array', 'np.array', (['[(2 * coef * exp * (stretch ** 2 + 2 / stretch - 3) ** (exp - 1) * (stretch -\n stretch ** -2) if stretch ** 2 + 2 / stretch > 3 else 0.0) for stretch in\n stretches]'], {}), '([(2 * coef * exp * (stretch ** 2 + 2 / stretch - 3) ** (exp - 1) *\n (stretch - stretch ** -2) if stretch ** 2 + 2 / stretch > 3 else 0.0) for\n stretch in stretches])\n', (5374, 5546), True, 'import numpy as np\n'), ((6333, 6373), 'numpy.array', 'np.array', (['[sig for sig in global_stress]'], {}), '([sig for sig in global_stress])\n', (6341, 6373), True, 'import numpy as np\n'), ((6518, 6552), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'sharex': '(True)'}), '(nrows=2, sharex=True)\n', (6530, 6552), True, 'import matplotlib.pyplot as plt\n'), ((7050, 7068), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (7066, 7068), True, 'import matplotlib.pyplot as plt\n'), ((7073, 7083), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7081, 7083), True, 'import matplotlib.pyplot as plt\n'), ((7944, 8007), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'strain', 'dofs': 'None'}), "(name='output_data', mode='cell', data=strain, dofs=None)\n", (7950, 8007), False, 'from sfepy.base.base import IndexedStruct, Struct\n'), ((8392, 8455), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'stress', 'dofs': 'None'}), "(name='output_data', mode='cell', data=stress, dofs=None)\n", (8398, 8455), False, 'from sfepy.base.base import IndexedStruct, Struct\n'), ((9179, 9243), 'sfepy.mesh.mesh_generators.gen_block_mesh', 'gen_block_mesh', (['dims', 'shape', 'centre'], {'name': '"""block"""', 'verbose': '(False)'}), "(dims, shape, centre, name='block', verbose=False)\n", (9193, 9243), False, 'from sfepy.mesh.mesh_generators import gen_block_mesh\n'), ((9266, 9290), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""domain"""', 'mesh'], {}), "('domain', mesh)\n", (9274, 9290), False, 'from sfepy.discrete.fem import FEDomain, Field\n'), ((9406, 9437), 'sfepy.homogenization.utils.define_box_regions', 'define_box_regions', (['(3)', 'lbn', 'rtf'], {}), '(3, lbn, rtf)\n', (9424, 9437), False, 'from sfepy.homogenization.utils import define_box_regions\n'), ((9604, 9678), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""fu"""', 'np.float64', '"""scalar"""', 'omega'], {'approx_order': '(order - 1)'}), "('fu', np.float64, 'scalar', omega, approx_order=order - 1)\n", (9619, 9678), False, 'from sfepy.discrete.fem import FEDomain, Field\n'), ((9705, 9775), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""fv"""', 'np.float64', '"""vector"""', 'omega'], {'approx_order': 'order'}), "('fv', np.float64, 'vector', omega, approx_order=order)\n", (9720, 9775), False, 'from sfepy.discrete.fem import FEDomain, Field\n'), ((9794, 9848), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""u"""', '"""unknown"""', 'vector_field'], {'history': '(1)'}), "('u', 'unknown', vector_field, history=1)\n", (9807, 9848), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((9857, 9919), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""v"""', '"""test"""', 'vector_field'], {'primary_var_name': '"""u"""'}), "('v', 'test', vector_field, primary_var_name='u')\n", (9870, 9919), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((9928, 9982), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""p"""', '"""unknown"""', 'scalar_field'], {'history': '(1)'}), "('p', 'unknown', scalar_field, history=1)\n", (9941, 9982), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((9991, 10053), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""q"""', '"""test"""', 'scalar_field'], {'primary_var_name': '"""p"""'}), "('q', 'test', scalar_field, primary_var_name='p')\n", (10004, 10053), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((10135, 10178), 'sfepy.discrete.Material', 'Material', (['"""m1"""'], {'par': '[coefficient, exponent]'}), "('m1', par=[coefficient, exponent])\n", (10143, 10178), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((10239, 10290), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""x_sym"""', "regions['Left']", "{'u.0': 0.0}"], {}), "('x_sym', regions['Left'], {'u.0': 0.0})\n", (10250, 10290), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((10304, 10355), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""y_sym"""', "regions['Near']", "{'u.1': 0.0}"], {}), "('y_sym', regions['Near'], {'u.1': 0.0})\n", (10315, 10355), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((10369, 10422), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""z_sym"""', "regions['Bottom']", "{'u.2': 0.0}"], {}), "('z_sym', regions['Bottom'], {'u.2': 0.0})\n", (10380, 10422), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((10439, 10477), 'sfepy.discrete.Function', 'Function', (['"""disp_fun"""', 'get_displacement'], {}), "('disp_fun', get_displacement)\n", (10447, 10477), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((10497, 10561), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""displacement"""', "regions['Right']", "{'u.0': disp_fun}"], {}), "('displacement', regions['Right'], {'u.0': disp_fun})\n", (10508, 10561), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((10583, 10630), 'sfepy.discrete.conditions.Conditions', 'Conditions', (['[x_sym, y_sym, z_sym, displacement]'], {}), '([x_sym, y_sym, z_sym, displacement])\n', (10593, 10630), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((10679, 10713), 'sfepy.discrete.Integral', 'Integral', (['"""i"""'], {'order': '(2 * order + 1)'}), "('i', order=2 * order + 1)\n", (10687, 10713), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((10724, 10801), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_tl_he_genyeoh(m1.par, v, u)"""', 'integral', 'omega'], {'m1': 'm_1', 'v': 'v', 'u': 'u'}), "('dw_tl_he_genyeoh(m1.par, v, u)', integral, omega, m1=m_1, v=v, u=u)\n", (10732, 10801), False, 'from sfepy.terms import Term\n'), ((10839, 10911), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_tl_bulk_pressure(v, u, p)"""', 'integral', 'omega'], {'v': 'v', 'u': 'u', 'p': 'p'}), "('dw_tl_bulk_pressure(v, u, p)', integral, omega, v=v, u=u, p=p)\n", (10847, 10911), False, 'from sfepy.terms import Term\n'), ((10955, 11032), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_tl_volume(q, u)"""', 'integral', 'omega'], {'q': 'q', 'u': 'u', 'term_mode': '"""volume"""'}), "('dw_tl_volume(q, u)', integral, omega, q=q, u=u, term_mode='volume')\n", (10963, 11032), False, 'from sfepy.terms import Term\n'), ((11068, 11124), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_volume_integrate(q)"""', 'integral', 'omega'], {'q': 'q'}), "('dw_volume_integrate(q)', integral, omega, q=q)\n", (11076, 11124), False, 'from sfepy.terms import Term\n'), ((11160, 11203), 'sfepy.discrete.Equation', 'Equation', (['"""balance"""', '(term_1 + term_pressure)'], {}), "('balance', term_1 + term_pressure)\n", (11168, 11203), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((11220, 11272), 'sfepy.discrete.Equation', 'Equation', (['"""volume"""', '(term_volume_change - term_volume)'], {}), "('volume', term_volume_change - term_volume)\n", (11228, 11272), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((11289, 11323), 'sfepy.discrete.Equations', 'Equations', (['[eq_balance, eq_volume]'], {}), '([eq_balance, eq_volume])\n', (11298, 11323), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((11354, 11369), 'sfepy.solvers.ls.ScipyDirect', 'ScipyDirect', (['{}'], {}), '({})\n', (11365, 11369), False, 'from sfepy.solvers.ls import ScipyDirect\n'), ((11387, 11402), 'sfepy.base.base.IndexedStruct', 'IndexedStruct', ([], {}), '()\n', (11400, 11402), False, 'from sfepy.base.base import IndexedStruct, Struct\n'), ((11413, 11468), 'sfepy.solvers.nls.Newton', 'Newton', (["{'i_max': 20}"], {'lin_solver': 'ls', 'status': 'nls_status'}), "({'i_max': 20}, lin_solver=ls, status=nls_status)\n", (11419, 11468), False, 'from sfepy.solvers.nls import Newton\n'), ((11522, 11559), 'sfepy.discrete.Problem', 'Problem', (['"""hyper"""'], {'equations': 'equations'}), "('hyper', equations=equations)\n", (11529, 11559), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((11631, 11680), 'sfepy.solvers.ts_solvers.SimpleTimeSteppingSolver', 'SimpleTimeSteppingSolver', (['ts'], {'nls': 'nls', 'context': 'pb'}), '(ts, nls=nls, context=pb)\n', (11655, 11680), False, 'from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver\n'), ((12729, 12832), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__', 'formatter_class': 'argparse.RawDescriptionHelpFormatter'}), '(description=__doc__, formatter_class=argparse.\n RawDescriptionHelpFormatter)\n', (12752, 12832), False, 'import argparse\n'), ((6235, 6264), 'numpy.array', 'np.array', (['global_displacement'], {}), '(global_displacement)\n', (6243, 6264), True, 'import numpy as np\n'), ((11605, 11619), 'sfepy.discrete.conditions.Conditions', 'Conditions', (['[]'], {}), '([])\n', (11615, 11619), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((8580, 8603), 'numpy.array', 'np.array', (['[[1.0, 0, 0]]'], {}), '([[1.0, 0, 0]])\n', (8588, 8603), True, 'import numpy as np\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
"""
import sys
sys.path.append('.')
from optparse import OptionParser
from sfepy.base.base import nm, output
from sfepy.discrete.fem import Mesh, FEDomain
from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO,
supported_cell_types)
usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip()
help = {
'scale' : 'scale factor (float or comma-separated list for each axis)'
' [default: %default]',
'center' : 'center of the output mesh (0 for origin or'
' comma-separated list for each axis) applied after scaling'
' [default: %default]',
'refine' : 'uniform refinement level [default: %default]',
'format' : 'output mesh format (overrides filename_out extension)',
'list' : 'list supported readable/writable output mesh formats',
}
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 = OptionParser(usage=usage)
parser.add_option('-s', '--scale', metavar='scale',
action='store', dest='scale',
default=None, help=help['scale'])
parser.add_option('-c', '--center', metavar='center',
action='store', dest='center',
default=None, help=help['center'])
parser.add_option('-r', '--refine', metavar='level',
action='store', type=int, dest='refine',
default=0, help=help['refine'])
parser.add_option('-f', '--format', metavar='format',
action='store', type='string', dest='format',
default=None, help=help['format'])
parser.add_option('-l', '--list', action='store_true',
dest='list', help=help['list'])
(options, args) = 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)
if len(args) != 2:
parser.print_help()
sys.exit(1)
scale = _parse_val_or_vec(options.scale, 'scale', parser)
center = _parse_val_or_vec(options.center, 'center', parser)
filename_in, filename_out = args
mesh = Mesh.from_file(filename_in)
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
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.discrete.fem.meshio.output_mesh_formats",
"sfepy.base.base.nm.diag",
"sfepy.discrete.fem.Mesh.from_file",
"sfepy.base.base.nm.array",
"sfepy.base.base.nm.eye",
"sfepy.discrete.fem.meshio.MeshIO.for_format",
"sfepy.discrete.fem.FEDomain",
"sfepy.base.base.output"
] | [((393, 413), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (408, 413), False, 'import sys\n'), ((1680, 1705), 'optparse.OptionParser', 'OptionParser', ([], {'usage': 'usage'}), '(usage=usage)\n', (1692, 1705), False, 'from optparse import OptionParser\n'), ((3131, 3158), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['filename_in'], {}), '(filename_in)\n', (3145, 3158), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((4102, 4171), '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', (4119, 4171), False, 'from sfepy.discrete.fem.meshio import output_mesh_formats, MeshIO, supported_cell_types\n'), ((4264, 4321), 'sfepy.base.base.output', 'output', (["('writing [%s] %s...' % (cell_types, filename_out))"], {}), "('writing [%s] %s...' % (cell_types, filename_out))\n", (4270, 4321), False, 'from sfepy.base.base import nm, output\n'), ((4362, 4379), 'sfepy.base.base.output', 'output', (['"""...done"""'], {}), "('...done')\n", (4368, 4379), False, 'from sfepy.base.base import nm, output\n'), ((2580, 2622), 'sfepy.base.base.output', 'output', (['"""Supported readable mesh formats:"""'], {}), "('Supported readable mesh formats:')\n", (2586, 2622), False, 'from sfepy.base.base import nm, output\n'), ((2631, 2673), 'sfepy.base.base.output', 'output', (['"""--------------------------------"""'], {}), "('--------------------------------')\n", (2637, 2673), False, 'from sfepy.base.base import nm, output\n'), ((2682, 2706), 'sfepy.discrete.fem.meshio.output_mesh_formats', 'output_mesh_formats', (['"""r"""'], {}), "('r')\n", (2701, 2706), False, 'from sfepy.discrete.fem.meshio import output_mesh_formats, MeshIO, supported_cell_types\n'), ((2715, 2725), 'sfepy.base.base.output', 'output', (['""""""'], {}), "('')\n", (2721, 2725), False, 'from sfepy.base.base import nm, output\n'), ((2734, 2776), 'sfepy.base.base.output', 'output', (['"""Supported writable mesh formats:"""'], {}), "('Supported writable mesh formats:')\n", (2740, 2776), False, 'from sfepy.base.base import nm, output\n'), ((2785, 2827), 'sfepy.base.base.output', 'output', (['"""--------------------------------"""'], {}), "('--------------------------------')\n", (2791, 2827), False, 'from sfepy.base.base import nm, output\n'), ((2836, 2860), 'sfepy.discrete.fem.meshio.output_mesh_formats', 'output_mesh_formats', (['"""w"""'], {}), "('w')\n", (2855, 2860), False, 'from sfepy.discrete.fem.meshio import output_mesh_formats, MeshIO, supported_cell_types\n'), ((2869, 2880), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2877, 2880), False, 'import sys\n'), ((2941, 2952), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2949, 2952), False, 'import sys\n'), ((3701, 3726), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['mesh.name', 'mesh'], {}), '(mesh.name, mesh)\n', (3709, 3726), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((3735, 3826), '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", (3741, 3826), False, 'from sfepy.base.base import nm, output\n'), ((1467, 1510), 'sfepy.base.base.nm.array', 'nm.array', (['option'], {'dtype': 'nm.float64', 'ndmin': '(1)'}), '(option, dtype=nm.float64, ndmin=1)\n', (1475, 1510), False, 'from sfepy.base.base import nm, output\n'), ((3891, 3918), 'sfepy.base.base.output', 'output', (["('refine %d...' % ii)"], {}), "('refine %d...' % ii)\n", (3897, 3918), False, 'from sfepy.base.base import nm, output\n'), ((3968, 4044), '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", (3974, 4044), False, 'from sfepy.base.base import nm, output\n'), ((1539, 1578), 'sfepy.base.base.output', 'output', (["('bad %s! (%s)' % (name, option))"], {}), "('bad %s! (%s)' % (name, option))\n", (1545, 1578), False, 'from sfepy.base.base import nm, output\n'), ((1623, 1634), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1631, 1634), False, 'import sys\n'), ((3231, 3265), 'sfepy.base.base.nm.eye', 'nm.eye', (['mesh.dim'], {'dtype': 'nm.float64'}), '(mesh.dim, dtype=nm.float64)\n', (3237, 3265), False, 'from sfepy.base.base import nm, output\n'), ((3328, 3342), 'sfepy.base.base.nm.diag', 'nm.diag', (['scale'], {}), '(scale)\n', (3335, 3342), False, 'from sfepy.base.base import nm, output\n'), ((3571, 3605), 'sfepy.base.base.nm.eye', 'nm.eye', (['mesh.dim'], {'dtype': 'nm.float64'}), '(mesh.dim, dtype=nm.float64)\n', (3577, 3605), False, 'from sfepy.base.base import nm, output\n')] |
"""
Problem description file handling.
Notes
-----
Short syntax: key is suffixed with '__<number>' to prevent collisions with long
syntax keys -> both cases can be used in a single input.
"""
from __future__ import absolute_import
import re
import numpy as nm
from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct,
output, copy, update_dict_recursively,
import_file, assert_, get_default, basestr)
from sfepy.base.parse_conf import create_bnf
import six
_required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields',
# TODO originaly EBC were required to be specified but in some examples
# (especially 1D) only EPBCs specified is valid
'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs',
'equations',
'region_[0-9]+|regions', 'variable_[0-9]+|variables',
'material_[0-9]+|materials',
'solver_[0-9]+|solvers']
_other = ['epbc_[0-9]+|epbcs',
'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs',
'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options',
'integral_[0-9]+|integrals']
def get_standard_keywords():
return copy(_required), copy(_other)
def tuple_to_conf(name, vals, order):
"""
Convert a configuration tuple `vals` into a Struct named `name`, with
attribute names given in and ordered by `order`.
Items in `order` at indices outside the length of `vals` are ignored.
"""
conf = Struct(name=name)
for ii, key in enumerate(order[:len(vals)]):
setattr(conf, key, vals[ii])
return conf
def transform_variables(adict):
d2 = {}
for ii, (key, conf) in enumerate(six.iteritems(adict)):
if isinstance(conf, tuple):
c2 = tuple_to_conf(key, conf, ['kind', 'field'])
if len(conf) >= 3:
kind = c2.kind.split()[0]
if kind == 'unknown':
c2.order = conf[2]
elif kind == 'test':
c2.dual = conf[2]
elif kind == 'parameter':
if isinstance(conf[2], basestr) or (conf[2] is None):
c2.like = conf[2]
else:
c2.like = None
c2.special = conf[2]
if len(conf) == 4:
c2.history = conf[3]
d2['variable_%s__%d' % (c2.name, ii)] = c2
else:
c2 = transform_to_struct_1(conf)
d2['variable_'+c2.name] = c2
return d2
def transform_conditions(adict, prefix):
d2 = {}
for ii, (key, conf) in enumerate(six.iteritems(adict)):
if isinstance(conf, tuple):
if len(conf) == 2:
c2 = tuple_to_conf(key, conf, ['region', 'dofs'])
else:
c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs'])
d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2
else:
c2 = transform_to_struct_1(conf)
d2['%s_%s' % (prefix, c2.name)] = c2
return d2
def transform_dgebcs(adict):
return transform_conditions(adict, "dgebc")
def transform_ebcs(adict):
return transform_conditions(adict, 'ebc')
def transform_ics(adict):
return transform_conditions(adict, 'ic')
def transform_lcbcs(adict):
d2 = {}
for ii, (key, conf) in enumerate(six.iteritems(adict)):
if isinstance(conf, tuple):
if len(conf) >= 4:
if isinstance(conf[1], dict):
c2 = tuple_to_conf(key, conf, ['region', 'dofs',
'dof_map_fun', 'kind'])
c2.arguments = conf[4:]
else:
c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs',
'dof_map_fun', 'kind'])
c2.arguments = conf[5:]
else:
msg = 'LCBC syntax has to be: region[, times], dofs,' \
' dof_map_fun, kind[, other arguments]'
raise SyntaxError(msg)
d2['lcbc_%s__%d' % (c2.name, ii)] = c2
else:
c2 = transform_to_struct_1(conf)
c2.set_default('dof_map_fun', None)
c2.set_default('arguments', ())
d2['lcbc_%s' % (c2.name)] = c2
return d2
def transform_epbcs(adict, prefix="epbc"):
d2 = {}
for ii, (key, conf) in enumerate(six.iteritems(adict)):
if isinstance(conf, tuple):
if len(conf) == 3:
c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match'])
else:
c2 = tuple_to_conf(key, conf,
['region', 'times', 'dofs', 'match'])
d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2
else:
c2 = transform_to_struct_1(conf)
d2['%s_%s' % (prefix, c2.name)] = c2
return d2
def transform_dgepbcs(adict):
return transform_epbcs(adict, "dgepbc")
def transform_regions(adict):
d2 = {}
for ii, (key, conf) in enumerate(six.iteritems(adict)):
if isinstance(conf, basestr):
c2 = Struct(name=key, select=conf)
d2['region_%s__%d' % (c2.name, ii)] = c2
elif isinstance(conf, tuple):
c2 = tuple_to_conf(key, conf, ['select', 'kind'])
if len(conf) == 3:
c2.parent = conf[2]
if len(conf) == 4:
c2.parent = conf[2]
c2.extra_options = conf[3]
d2['region_%s__%d' % (c2.name, ii)] = c2
else:
c2 = transform_to_struct_1(conf)
d2['region_'+c2.name] = c2
return d2
def transform_integrals(adict):
d2 = {}
for ii, (key, conf) in enumerate(six.iteritems(adict)):
if isinstance(conf, int):
c2 = Struct(name=key, order=conf)
d2['integral_%s__%d' % (c2.name, ii)] = c2
elif isinstance(conf, tuple):
if len(conf) == 2: # Old tuple version with now-ignored 'kind'.
conf = conf[1]
c2 = Struct(name=key, order=conf)
elif len(conf) == 3:
c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights'])
d2['integral_%s__%d' % (c2.name, ii)] = c2
else:
c2 = transform_to_struct_1(conf)
d2['integral_'+c2.name] = c2
return d2
def transform_fields(adict):
dtypes = {'real' : nm.float64, 'complex' : nm.complex128}
d2 = {}
for ii, (key, conf) in enumerate(six.iteritems(adict)):
if isinstance(conf, tuple):
c2 = tuple_to_conf(key, conf,
['dtype', 'shape', 'region', 'approx_order',
'space', 'poly_space_base'])
if c2.dtype in dtypes:
c2.dtype = dtypes[c2.dtype]
d2['field_%s__%d' % (c2.name, ii)] = c2
else:
c2 = transform_to_struct_1(conf)
c2.set_default('dtype', nm.float64)
if c2.dtype in dtypes:
c2.dtype = dtypes[c2.dtype]
d2['field_'+c2.name] = c2
return d2
def transform_materials(adict):
d2 = {}
for ii, (key, conf) in enumerate(six.iteritems(adict)):
if isinstance(conf, basestr):
c2 = Struct(name=key, function=conf)
d2['material_%s__%d' % (c2.name, ii)] = c2
elif isinstance(conf, tuple):
c2 = tuple_to_conf(key, conf,
['values', 'function', 'kind'])
if len(conf) == 4:
c2.flags = conf[3]
d2['material_%s__%d' % (c2.name, ii)] = c2
else:
c2 = transform_to_struct_1(conf)
d2['material_'+conf['name']] = c2
return d2
def transform_solvers(adict):
d2 = {}
for ii, (key, conf) in enumerate(six.iteritems(adict)):
if isinstance(conf, tuple):
c2 = tuple_to_conf(key, conf, ['kind','params'])
for param, val in six.iteritems(c2.params):
setattr(c2, param, val)
delattr(c2, 'params')
d2['solvers_%s__%d' % (c2.name, ii)] = c2
else:
c2 = transform_to_struct_1(conf)
d2['solvers_'+c2.name] = c2
return d2
def transform_functions(adict):
d2 = {}
for ii, (key, conf) in enumerate(six.iteritems(adict)):
if isinstance(conf, tuple):
c2 = tuple_to_conf(key, conf, ['function'])
d2['function_%s__%d' % (c2.name, ii)] = c2
else:
c2 = transform_to_struct_1(conf)
d2['function_'+c2.name] = c2
return d2
def transform_to_struct_1(adict):
return dict_to_struct(adict, flag=(1,))
def transform_to_i_struct_1(adict):
return dict_to_struct(adict, flag=(1,), constructor=IndexedStruct)
def transform_to_struct_01(adict):
return dict_to_struct(adict, flag=(0,1))
def transform_to_struct_10(adict):
return dict_to_struct(adict, flag=(1,0))
transforms = {
'options' : transform_to_i_struct_1,
'solvers' : transform_solvers,
'integrals' : transform_integrals,
'regions' : transform_regions,
'fields' : transform_fields,
'variables' : transform_variables,
'ebcs' : transform_ebcs,
'epbcs' : transform_epbcs,
'dgebcs' : transform_dgebcs,
'dgepbcs' : transform_dgepbcs,
'nbcs' : transform_to_struct_01,
'lcbcs' : transform_lcbcs,
'ics' : transform_ics,
'materials' : transform_materials,
'functions' : transform_functions,
}
def dict_from_string(string, allow_tuple=False, free_word=False):
"""
Parse `string` and return a dictionary that can be used to
construct/override a ProblemConf instance.
"""
if string is None:
return {}
if isinstance(string, dict):
return string
parser = create_bnf(allow_tuple=allow_tuple, free_word=free_word)
out = {}
for r in parser.parseString(string, parseAll=True):
out.update(r)
return out
def dict_from_options(options):
"""
Return a dictionary that can be used to construct/override a ProblemConf
instance based on `options`.
See ``--conf`` and ``--options`` options of the ``simple.py`` script.
"""
override = dict_from_string(options.conf)
if options.app_options:
if not 'options' in override:
override['options'] = {}
override_options = dict_from_string(options.app_options)
override['options'].update(override_options)
return override
##
# 27.10.2005, c
class ProblemConf(Struct):
"""
Problem configuration, corresponding to an input (problem description
file). It validates the input using lists of required and other keywords
that have to/can appear in the input. Default keyword lists can be obtained
by sfepy.base.conf.get_standard_keywords().
ProblemConf instance is used to construct a Problem instance via
Problem.from_conf(conf).
"""
@staticmethod
def from_file(filename, required=None, other=None, verbose=True,
define_args=None, override=None, setup=True):
"""
Loads the problem definition from a file.
The filename can either contain plain definitions, or it can contain
the define() function, in which case it will be called to return the
input definitions.
The job of the define() function is to return a dictionary of
parameters. How the dictionary is constructed is not our business, but
the usual way is to simply have a function define() along these lines
in the input file::
def define():
options = {
'save_eig_vectors' : None,
'eigen_solver' : 'eigen1',
}
region_2 = {
'name' : 'Surface',
'select' : 'nodes of surface',
}
return locals()
Optionally, the define() function can accept additional arguments
that should be defined using the `define_args` tuple or dictionary.
"""
funmod = import_file(filename, package_name=False)
if "define" in funmod.__dict__:
if define_args is None:
define_dict = funmod.__dict__["define"]()
else:
if isinstance(define_args, str):
define_args = dict_from_string(define_args)
if isinstance(define_args, dict):
define_dict = funmod.__dict__["define"](**define_args)
else:
define_dict = funmod.__dict__["define"](*define_args)
else:
define_dict = funmod.__dict__
obj = ProblemConf(define_dict, funmod=funmod, filename=filename,
required=required, other=other, verbose=verbose,
override=override, setup=setup)
return obj
@staticmethod
def from_file_and_options(filename, options, required=None, other=None,
verbose=True, define_args=None, setup=True):
"""
Utility function, a wrapper around ProblemConf.from_file() with
possible override taken from `options`.
"""
override = dict_from_options(options)
obj = ProblemConf.from_file(filename, required=required, other=other,
verbose=verbose, define_args=define_args,
override=override, setup=setup)
return obj
@staticmethod
def from_module(module, required=None, other=None, verbose=True,
override=None, setup=True):
obj = ProblemConf(module.__dict__, module, module.__name__,
required, other, verbose, override, setup=setup)
return obj
@staticmethod
def from_dict(dict_, funmod, required=None, other=None, verbose=True,
override=None, setup=True):
obj = ProblemConf(dict_, funmod, None, required, other, verbose,
override, setup=setup)
return obj
def __init__(self, define_dict, funmod=None, filename=None,
required=None, other=None, verbose=True, override=None,
setup=True):
if override:
if isinstance(override, Struct):
override = override.__dict__
define_dict = update_dict_recursively(define_dict, override, True)
self.__dict__.update(define_dict)
self.verbose = verbose
if setup:
self.setup(funmod=funmod, filename=filename,
required=required, other=other)
def setup(self, define_dict=None, funmod=None, filename=None,
required=None, other=None):
define_dict = get_default(define_dict, self.__dict__)
self._filename = filename
self.validate(required=required, other=other)
self.transform_input_trivial()
self._raw = {}
for key, val in six.iteritems(define_dict):
if isinstance(val, dict):
self._raw[key] = copy(val)
self.transform_input()
self.funmod = funmod
def _validate_helper(self, items, but_nots):
keys = list(self.__dict__.keys())
left_over = keys[:]
if but_nots is not None:
for item in but_nots:
match = re.compile('^' + item + '$').match
for key in keys:
if match(key):
left_over.remove(key)
missing = []
if items is not None:
for item in items:
found = False
match = re.compile('^' + item + '$').match
for key in keys:
if match(key):
found = True
left_over.remove(key)
if not found:
missing.append(item)
return left_over, missing
def validate(self, required=None, other=None):
required_left_over, required_missing \
= self._validate_helper(required, other)
other_left_over, other_missing \
= self._validate_helper(other, required)
assert_(required_left_over == other_left_over)
if other_left_over and self.verbose:
output('left over:', other_left_over)
if required_missing:
raise ValueError('required missing: %s' % required_missing)
return other_missing
def transform_input_trivial(self):
"""Trivial input transformations."""
##
# Unordered inputs.
tr_list = ['([a-zA-Z0-9]+)_[0-9]+']
# Keywords not in 'required', but needed even empty (e.g. for
# running tests).
for key in transforms.keys():
if key not in self.__dict__:
self.__dict__[key] = {}
keys = list(self.__dict__.keys())
for item in tr_list:
match = re.compile(item).match
for key in keys:
obj = match(key)
if obj:
new = obj.group(1) + 's'
result = {key : self.__dict__[key]}
try:
self.__dict__[new].update(result)
except:
self.__dict__[new] = result
del self.__dict__[key]
def transform_input(self):
keys = list(self.__dict__.keys())
for key, transform in six.iteritems(transforms):
if not key in keys: continue
self.__dict__[key] = transform(self.__dict__[key])
def get_raw(self, key=None):
if key is None:
return self._raw
else:
return self._raw[key]
def get_item_by_name(self, key, item_name):
"""
Return item with name `item_name` in configuration group given
by `key`.
"""
val = getattr(self, key)
for item in six.itervalues(val):
if item.name == item_name:
return item
def get_function(self, name):
"""
Get a function object given its name.
It can be either in `ProblemConf.funmod`, or a `ProblemConf`
attribute directly.
Parameters
----------
name : str or function or None
The function name or directly the function.
Returns
-------
fun : function or None
The required function, or None if `name` was `None`.
"""
if name is None:
fun = None
elif callable(name):
import inspect
if not (inspect.isfunction(name) or inspect.ismethod(name)):
msg = '`name` has to have `str` or `function` type! (got %s)'
raise ValueError(msg % type(name))
fun = name
else:
try:
fun = getattr(self.funmod, name)
except AttributeError:
try:
fun = getattr(self, name)
except AttributeError:
raise ValueError('function %s cannot be found!' % name)
return fun
def edit(self, key, newval):
self.__dict__[key] = transforms[key](newval)
def update_conf(self, conf):
"""
Update configuration by values in another problem configuration.
Values that are dictionaries are updated in-place by ``dict.update()``.
Parameters
----------
conf : ProblemConf instance
The other configuration.
"""
for x in conf.__dict__:
his = conf.__dict__[x]
my = getattr(self, x, None)
if isinstance(my, dict) and isinstance(his, dict):
my.update(his)
else:
setattr(self, x, his)
def add_missing(self, conf):
"""
Add missing values from another problem configuration.
Missing keys/values are added also to values that are dictionaries.
Parameters
----------
conf : ProblemConf instance
The other configuration.
"""
for x in conf.__dict__:
his = conf.__dict__[x]
my = getattr(self, x, None)
if isinstance(my, dict) and isinstance(his, dict):
for key in his:
if key not in my:
my[key]=his[key]
elif my is None:
setattr(self, x, his)
| [
"sfepy.base.base.import_file",
"sfepy.base.base.output",
"sfepy.base.base.get_default",
"sfepy.base.parse_conf.create_bnf",
"sfepy.base.base.Struct",
"sfepy.base.base.update_dict_recursively",
"sfepy.base.base.copy",
"sfepy.base.base.dict_to_struct",
"sfepy.base.base.assert_"
] | [((1517, 1534), 'sfepy.base.base.Struct', 'Struct', ([], {'name': 'name'}), '(name=name)\n', (1523, 1534), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((8742, 8774), 'sfepy.base.base.dict_to_struct', 'dict_to_struct', (['adict'], {'flag': '(1,)'}), '(adict, flag=(1,))\n', (8756, 8774), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((8822, 8881), 'sfepy.base.base.dict_to_struct', 'dict_to_struct', (['adict'], {'flag': '(1,)', 'constructor': 'IndexedStruct'}), '(adict, flag=(1,), constructor=IndexedStruct)\n', (8836, 8881), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((8928, 8962), 'sfepy.base.base.dict_to_struct', 'dict_to_struct', (['adict'], {'flag': '(0, 1)'}), '(adict, flag=(0, 1))\n', (8942, 8962), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((9008, 9042), 'sfepy.base.base.dict_to_struct', 'dict_to_struct', (['adict'], {'flag': '(1, 0)'}), '(adict, flag=(1, 0))\n', (9022, 9042), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((9925, 9981), 'sfepy.base.parse_conf.create_bnf', 'create_bnf', ([], {'allow_tuple': 'allow_tuple', 'free_word': 'free_word'}), '(allow_tuple=allow_tuple, free_word=free_word)\n', (9935, 9981), False, 'from sfepy.base.parse_conf import create_bnf\n'), ((1219, 1234), 'sfepy.base.base.copy', 'copy', (['_required'], {}), '(_required)\n', (1223, 1234), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((1236, 1248), 'sfepy.base.base.copy', 'copy', (['_other'], {}), '(_other)\n', (1240, 1248), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((1719, 1739), 'six.iteritems', 'six.iteritems', (['adict'], {}), '(adict)\n', (1732, 1739), False, 'import six\n'), ((2668, 2688), 'six.iteritems', 'six.iteritems', (['adict'], {}), '(adict)\n', (2681, 2688), False, 'import six\n'), ((3402, 3422), 'six.iteritems', 'six.iteritems', (['adict'], {}), '(adict)\n', (3415, 3422), False, 'import six\n'), ((4493, 4513), 'six.iteritems', 'six.iteritems', (['adict'], {}), '(adict)\n', (4506, 4513), False, 'import six\n'), ((5131, 5151), 'six.iteritems', 'six.iteritems', (['adict'], {}), '(adict)\n', (5144, 5151), False, 'import six\n'), ((5816, 5836), 'six.iteritems', 'six.iteritems', (['adict'], {}), '(adict)\n', (5829, 5836), False, 'import six\n'), ((6593, 6613), 'six.iteritems', 'six.iteritems', (['adict'], {}), '(adict)\n', (6606, 6613), False, 'import six\n'), ((7282, 7302), 'six.iteritems', 'six.iteritems', (['adict'], {}), '(adict)\n', (7295, 7302), False, 'import six\n'), ((7913, 7933), 'six.iteritems', 'six.iteritems', (['adict'], {}), '(adict)\n', (7926, 7933), False, 'import six\n'), ((8412, 8432), 'six.iteritems', 'six.iteritems', (['adict'], {}), '(adict)\n', (8425, 8432), False, 'import six\n'), ((12223, 12264), 'sfepy.base.base.import_file', 'import_file', (['filename'], {'package_name': '(False)'}), '(filename, package_name=False)\n', (12234, 12264), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((14918, 14957), 'sfepy.base.base.get_default', 'get_default', (['define_dict', 'self.__dict__'], {}), '(define_dict, self.__dict__)\n', (14929, 14957), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((15135, 15161), 'six.iteritems', 'six.iteritems', (['define_dict'], {}), '(define_dict)\n', (15148, 15161), False, 'import six\n'), ((16377, 16423), 'sfepy.base.base.assert_', 'assert_', (['(required_left_over == other_left_over)'], {}), '(required_left_over == other_left_over)\n', (16384, 16423), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((17649, 17674), 'six.iteritems', 'six.iteritems', (['transforms'], {}), '(transforms)\n', (17662, 17674), False, 'import six\n'), ((18130, 18149), 'six.itervalues', 'six.itervalues', (['val'], {}), '(val)\n', (18144, 18149), False, 'import six\n'), ((5209, 5238), 'sfepy.base.base.Struct', 'Struct', ([], {'name': 'key', 'select': 'conf'}), '(name=key, select=conf)\n', (5215, 5238), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((5890, 5918), 'sfepy.base.base.Struct', 'Struct', ([], {'name': 'key', 'order': 'conf'}), '(name=key, order=conf)\n', (5896, 5918), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((7360, 7391), 'sfepy.base.base.Struct', 'Struct', ([], {'name': 'key', 'function': 'conf'}), '(name=key, function=conf)\n', (7366, 7391), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((8063, 8087), 'six.iteritems', 'six.iteritems', (['c2.params'], {}), '(c2.params)\n', (8076, 8087), False, 'import six\n'), ((14527, 14579), 'sfepy.base.base.update_dict_recursively', 'update_dict_recursively', (['define_dict', 'override', '(True)'], {}), '(define_dict, override, True)\n', (14550, 14579), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((16482, 16519), 'sfepy.base.base.output', 'output', (['"""left over:"""', 'other_left_over'], {}), "('left over:', other_left_over)\n", (16488, 16519), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((15234, 15243), 'sfepy.base.base.copy', 'copy', (['val'], {}), '(val)\n', (15238, 15243), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((17128, 17144), 're.compile', 're.compile', (['item'], {}), '(item)\n', (17138, 17144), False, 'import re\n'), ((6141, 6169), 'sfepy.base.base.Struct', 'Struct', ([], {'name': 'key', 'order': 'conf'}), '(name=key, order=conf)\n', (6147, 6169), False, 'from sfepy.base.base import Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr\n'), ((15516, 15544), 're.compile', 're.compile', (["('^' + item + '$')"], {}), "('^' + item + '$')\n", (15526, 15544), False, 'import re\n'), ((15802, 15830), 're.compile', 're.compile', (["('^' + item + '$')"], {}), "('^' + item + '$')\n", (15812, 15830), False, 'import re\n'), ((18809, 18833), 'inspect.isfunction', 'inspect.isfunction', (['name'], {}), '(name)\n', (18827, 18833), False, 'import inspect\n'), ((18837, 18859), 'inspect.ismethod', 'inspect.ismethod', (['name'], {}), '(name)\n', (18853, 18859), False, 'import inspect\n')] |
"""
Nonlinear solvers.
"""
import time
import numpy as nm
import numpy.linalg as nla
from sfepy.base.base import output, get_default, debug, Struct
from sfepy.base.log import Log, get_logging_conf
from sfepy.solvers.solvers import SolverMeta, NonlinearSolver
def check_tangent_matrix(conf, vec_x0, fun, fun_grad):
"""
Verify the correctness of the tangent matrix as computed by `fun_grad()` by
comparing it with its finite difference approximation evaluated by
repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta.
"""
vec_x = vec_x0.copy()
delta = conf.delta
vec_r = fun(vec_x) # Update state.
mtx_a0 = fun_grad(vec_x)
mtx_a = mtx_a0.tocsc()
mtx_d = mtx_a.copy()
mtx_d.data[:] = 0.0
vec_dx = nm.zeros_like(vec_r)
for ic in range(vec_dx.shape[0]):
vec_dx[ic] = delta
xx = vec_x.copy() - vec_dx
vec_r1 = fun(xx)
vec_dx[ic] = -delta
xx = vec_x.copy() - vec_dx
vec_r2 = fun(xx)
vec_dx[ic] = 0.0;
vec = 0.5 * (vec_r2 - vec_r1) / delta
ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]]
mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir]
vec_r = fun(vec_x) # Restore.
tt = time.clock()
output(mtx_a, '.. analytical')
output(mtx_d, '.. difference')
import sfepy.base.plotutils as plu
plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'],
conf.check)
return time.clock() - tt
def conv_test(conf, it, err, err0):
"""
Nonlinear solver convergence test.
Parameters
----------
conf : Struct instance
The nonlinear solver configuration.
it : int
The current iteration.
err : float
The current iteration error.
err0 : float
The initial error.
Returns
-------
status : int
The convergence status: -1 = no convergence (yet), 0 = solver converged
- tolerances were met, 1 = max. number of iterations reached.
"""
status = -1
if (abs(err0) < conf.macheps):
err_r = 0.0
else:
err_r = err / err0
output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r))
conv_a = err < conf.eps_a
if it > 0:
conv_r = err_r < conf.eps_r
if conv_a and conv_r:
status = 0
elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r):
status = 0
else:
if conv_a:
status = 0
if (status == -1) and (it >= conf.i_max):
status = 1
return status
class Newton(NonlinearSolver):
r"""
Solves a nonlinear system :math:`f(x) = 0` using the Newton method with
backtracking line-search, starting with an initial guess :math:`x^0`.
"""
name = 'nls.newton'
__metaclass__ = SolverMeta
_parameters = [
('i_max', 'int', 1, False,
'The maximum number of iterations.'),
('eps_a', 'float', 1e-10, False,
'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'),
('eps_r', 'float', 1.0, False,
"""The relative tolerance for the residual, i.e. :math:`||f(x^i)|| /
||f(x^0)||`."""),
('eps_mode', "'and' or 'or'", 'and', False,
"""The logical operator to use for combining the absolute and relative
tolerances."""),
('macheps', 'float', nm.finfo(nm.float64).eps, False,
'The float considered to be machine "zero".'),
('lin_red', 'float', 1.0, False,
"""The linear system solution error should be smaller than (`eps_a` *
`lin_red`), otherwise a warning is printed."""),
('lin_precision', 'float or None', None, False,
"""If not None, the linear system solution tolerances are set in each
nonlinear iteration relative to the current residual norm by the
`lin_precision` factor. Ignored for direct linear solvers."""),
('ls_on', 'float', 0.99999, False,
"""Start the backtracking line-search by reducing the step, if
:math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""),
('ls_red', '0.0 < float < 1.0', 0.1, False,
'The step reduction factor in case of correct residual assembling.'),
('ls_red_warp', '0.0 < float < 1.0', 0.001, False,
"""The step reduction factor in case of failed residual assembling
(e.g. the "warp violation" error caused by a negative volume
element resulting from too large deformations)."""),
('ls_min', '0.0 < float < 1.0', 1e-5, False,
'The minimum step reduction factor.'),
('give_up_warp', 'bool', False, False,
'If True, abort on the "warp violation" error.'),
('check', '0, 1 or 2', 0, False,
"""If >= 1, check the tangent matrix using finite differences. If 2,
plot the resulting sparsity patterns."""),
('delta', 'float', 1e-6, False,
r"""If `check >= 1`, the finite difference matrix is taken as
:math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2
\delta}`."""),
('log', 'dict or None', None, False,
"""If not None, log the convergence according to the configuration in
the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``.
Each of the dict items can be None."""),
('is_linear', 'bool', False, False,
'If True, the problem is considered to be linear.'),
]
def __init__(self, conf, **kwargs):
NonlinearSolver.__init__(self, conf, **kwargs)
conf = self.conf
log = get_logging_conf(conf)
conf.log = log = Struct(name='log_conf', **log)
conf.is_any_log = (log.text is not None) or (log.plot is not None)
if conf.is_any_log:
self.log = Log([[r'$||r||$'], ['iteration']],
xlabels=['', 'all iterations'],
ylabels=[r'$||r||$', 'iteration'],
yscales=['log', 'linear'],
is_plot=conf.log.plot is not None,
log_filename=conf.log.text,
formats=[['%.8e'], ['%d']])
else:
self.log = None
def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None,
lin_solver=None, iter_hook=None, status=None):
"""
Nonlinear system solver call.
Solves a nonlinear system :math:`f(x) = 0` using the Newton method with
backtracking line-search, starting with an initial guess :math:`x^0`.
Parameters
----------
vec_x0 : array
The initial guess vector :math:`x_0`.
conf : Struct instance, optional
The solver configuration parameters,
fun : function, optional
The function :math:`f(x)` whose zero is sought - the residual.
fun_grad : function, optional
The gradient of :math:`f(x)` - the tangent matrix.
lin_solver : LinearSolver instance, optional
The linear solver for each nonlinear iteration.
iter_hook : function, optional
User-supplied function to call before each iteration.
status : dict-like, optional
The user-supplied object to hold convergence statistics.
Notes
-----
* The optional parameters except `iter_hook` and `status` need
to be given either here or upon `Newton` construction.
* Setting `conf.is_linear == True` means a pre-assembled and possibly
pre-solved matrix. This is mostly useful for linear time-dependent
problems.
"""
conf = get_default(conf, self.conf)
fun = get_default(fun, self.fun)
fun_grad = get_default(fun_grad, self.fun_grad)
lin_solver = get_default(lin_solver, self.lin_solver)
iter_hook = get_default(iter_hook, self.iter_hook)
status = get_default(status, self.status)
ls_eps_a, ls_eps_r = lin_solver.get_tolerance()
eps_a = get_default(ls_eps_a, 1.0)
eps_r = get_default(ls_eps_r, 1.0)
lin_red = conf.eps_a * conf.lin_red
time_stats = {}
vec_x = vec_x0.copy()
vec_x_last = vec_x0.copy()
vec_dx = None
if self.log is not None:
self.log.plot_vlines(color='r', linewidth=1.0)
err = err0 = -1.0
err_last = -1.0
it = 0
while 1:
if iter_hook is not None:
iter_hook(self, vec_x, it, err, err0)
ls = 1.0
vec_dx0 = vec_dx;
while 1:
tt = time.clock()
try:
vec_r = fun(vec_x)
except ValueError:
if (it == 0) or (ls < conf.ls_min):
output('giving up!')
raise
else:
ok = False
else:
ok = True
time_stats['rezidual'] = time.clock() - tt
if ok:
try:
err = nla.norm(vec_r)
except:
output('infs or nans in the residual:', vec_r)
output(nm.isfinite(vec_r).all())
debug()
if self.log is not None:
self.log(err, it)
if it == 0:
err0 = err;
break
if err < (err_last * conf.ls_on): break
red = conf.ls_red;
output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)'
% (it, err, err_last * conf.ls_on, red * ls))
else: # Failure.
if conf.give_up_warp:
output('giving up!')
break
red = conf.ls_red_warp;
output('rezidual computation failed for iter %d'
' (new ls: %e)!' % (it, red * ls))
if ls < conf.ls_min:
output('linesearch failed, continuing anyway')
break
ls *= red;
vec_dx = ls * vec_dx0;
vec_x = vec_x_last.copy() - vec_dx
# End residual loop.
if self.log is not None:
self.log.plot_vlines([1], color='g', linewidth=0.5)
err_last = err;
vec_x_last = vec_x.copy()
condition = conv_test(conf, it, err, err0)
if condition >= 0:
break
if (not ok) and conf.give_up_warp:
condition = 2
break
tt = time.clock()
if not conf.is_linear:
mtx_a = fun_grad(vec_x)
else:
mtx_a = fun_grad('linear')
time_stats['matrix'] = time.clock() - tt
if conf.check:
tt = time.clock()
wt = check_tangent_matrix(conf, vec_x, fun, fun_grad)
time_stats['check'] = time.clock() - tt - wt
if conf.lin_precision is not None:
if ls_eps_a is not None:
eps_a = max(err * conf.lin_precision, ls_eps_a)
elif ls_eps_r is not None:
eps_r = max(conf.lin_precision, ls_eps_r)
lin_red = max(eps_a, err * eps_r)
if conf.verbose:
output('solving linear system...')
tt = time.clock()
vec_dx = lin_solver(vec_r, x0=vec_x,
eps_a=eps_a, eps_r=eps_r, mtx=mtx_a)
time_stats['solve'] = time.clock() - tt
if conf.verbose:
output('...done')
for kv in time_stats.iteritems():
output('%10s: %7.2f [s]' % kv)
vec_e = mtx_a * vec_dx - vec_r
lerr = nla.norm(vec_e)
if lerr > lin_red:
output('warning: linear system solution precision is lower')
output('then the value set in solver options! (err = %e < %e)'
% (lerr, lin_red))
vec_x -= vec_dx
it += 1
if status is not None:
status['time_stats'] = time_stats
status['err0'] = err0
status['err'] = err
status['n_iter'] = it
status['condition'] = condition
if conf.log.plot is not None:
if self.log is not None:
self.log(save_figure=conf.log.plot)
return vec_x
class ScipyBroyden(NonlinearSolver):
"""
Interface to Broyden and Anderson solvers from ``scipy.optimize``.
"""
name = 'nls.scipy_broyden_like'
__metaclass__ = SolverMeta
_parameters = [
('method', 'str', 'anderson', False,
'The name of the solver in ``scipy.optimize``.'),
('i_max', 'int', 10, False,
'The maximum number of iterations.'),
('alpha', 'float', 0.9, False,
'See ``scipy.optimize``.'),
('M', 'float', 5, False,
'See ``scipy.optimize``.'),
('f_tol', 'float', 1e-6, False,
'See ``scipy.optimize``.'),
('w0', 'float', 0.1, False,
'See ``scipy.optimize``.'),
]
def __init__(self, conf, **kwargs):
NonlinearSolver.__init__(self, conf, **kwargs)
self.set_method(self.conf)
def set_method(self, conf):
import scipy.optimize as so
try:
solver = getattr(so, conf.method)
except AttributeError:
output('scipy solver %s does not exist!' % conf.method)
output('using broyden3 instead')
solver = so.broyden3
self.solver = solver
def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None,
lin_solver=None, iter_hook=None, status=None):
if conf is not None:
self.set_method(conf)
else:
conf = self.conf
fun = get_default(fun, self.fun)
status = get_default(status, self.status)
tt = time.clock()
kwargs = {'iter' : conf.i_max,
'alpha' : conf.alpha,
'verbose' : conf.verbose}
if conf.method == 'broyden_generalized':
kwargs.update({'M' : conf.M})
elif conf.method in ['anderson', 'anderson2']:
kwargs.update({'M' : conf.M, 'w0' : conf.w0})
if conf.method in ['anderson', 'anderson2',
'broyden', 'broyden2' , 'newton_krylov']:
kwargs.update({'f_tol' : conf.f_tol })
vec_x = self.solver(fun, vec_x0, **kwargs)
vec_x = nm.asarray(vec_x)
if status is not None:
status['time_stats'] = time.clock() - tt
return vec_x
class PETScNonlinearSolver(NonlinearSolver):
"""
Interface to PETSc SNES (Scalable Nonlinear Equations Solvers).
The solver supports parallel use with a given MPI communicator (see `comm`
argument of :func:`PETScNonlinearSolver.__init__()`). Returns a (global)
PETSc solution vector instead of a (local) numpy array, when given a PETSc
initial guess vector.
For parallel use, the `fun` and `fun_grad` callbacks should be provided by
:class:`PETScParallelEvaluator
<sfepy.parallel.evaluate.PETScParallelEvaluator>`.
"""
name = 'nls.petsc'
__metaclass__ = SolverMeta
_parameters = [
('method', 'str', 'newtonls', False,
'The SNES type.'),
('i_max', 'int', 10, False,
'The maximum number of iterations.'),
('if_max', 'int', 100, False,
'The maximum number of function evaluations.'),
('eps_a', 'float', 1e-10, False,
'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'),
('eps_r', 'float', 1.0, False,
"""The relative tolerance for the residual, i.e. :math:`||f(x^i)|| /
||f(x^0)||`."""),
('eps_s', 'float', 0.0, False,
"""The convergence tolerance in terms of the norm of the change in
the solution between steps,
i.e. $||delta x|| < \epsilon_s ||x||$"""),
]
def __init__(self, conf, pmtx=None, prhs=None, comm=None, **kwargs):
if comm is None:
try:
import petsc4py
petsc4py.init([])
except ImportError:
msg = 'cannot import petsc4py!'
raise ImportError(msg)
from petsc4py import PETSc as petsc
NonlinearSolver.__init__(self, conf, petsc=petsc,
pmtx=pmtx, prhs=prhs, comm=comm, **kwargs)
def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None,
lin_solver=None, iter_hook=None, status=None,
pmtx=None, prhs=None, comm=None):
conf = self.conf
fun = get_default(fun, self.fun)
fun_grad = get_default(fun_grad, self.fun_grad)
lin_solver = get_default(lin_solver, self.lin_solver)
iter_hook = get_default(iter_hook, self.iter_hook)
status = get_default(status, self.status)
pmtx = get_default(pmtx, self.pmtx)
prhs = get_default(prhs, self.prhs)
comm = get_default(comm, self.comm)
tt = time.clock()
if isinstance(vec_x0, self.petsc.Vec):
psol = vec_x0
else:
psol = pmtx.getVecLeft()
psol[...] = vec_x0
snes = self.petsc.SNES()
snes.create(comm)
snes.setType(conf.method)
ksp = lin_solver.create_ksp()
snes.setKSP(ksp)
ls_conf = lin_solver.conf
ksp.setTolerances(atol=ls_conf.eps_a, rtol=ls_conf.eps_r,
divtol=ls_conf.eps_d, max_it=ls_conf.i_max)
snes.setFunction(fun, prhs)
snes.setJacobian(fun_grad, pmtx)
snes.setTolerances(atol=conf.eps_a, rtol=conf.eps_r,
stol=conf.eps_s, max_it=conf.i_max)
snes.setMaxFunctionEvaluations(conf.if_max)
snes.setFromOptions()
snes.solve(prhs.duplicate(), psol)
if status is not None:
status['time_stats'] = time.clock() - tt
if isinstance(vec_x0, self.petsc.Vec):
sol = psol
else:
sol = psol[...].copy()
return sol
| [
"sfepy.base.log.get_logging_conf",
"sfepy.base.base.get_default",
"sfepy.solvers.solvers.NonlinearSolver.__init__",
"sfepy.base.base.Struct",
"sfepy.base.plotutils.plot_matrix_diff",
"sfepy.base.log.Log",
"sfepy.base.base.debug",
"sfepy.base.base.output"
] | [((772, 792), 'numpy.zeros_like', 'nm.zeros_like', (['vec_r'], {}), '(vec_r)\n', (785, 792), True, 'import numpy as nm\n'), ((1258, 1270), 'time.clock', 'time.clock', ([], {}), '()\n', (1268, 1270), False, 'import time\n'), ((1275, 1305), 'sfepy.base.base.output', 'output', (['mtx_a', '""".. analytical"""'], {}), "(mtx_a, '.. analytical')\n", (1281, 1305), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((1310, 1340), 'sfepy.base.base.output', 'output', (['mtx_d', '""".. difference"""'], {}), "(mtx_d, '.. difference')\n", (1316, 1340), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((1384, 1471), 'sfepy.base.plotutils.plot_matrix_diff', 'plu.plot_matrix_diff', (['mtx_d', 'mtx_a', 'delta', "['difference', 'analytical']", 'conf.check'], {}), "(mtx_d, mtx_a, delta, ['difference', 'analytical'],\n conf.check)\n", (1404, 1471), True, 'import sfepy.base.plotutils as plu\n'), ((2163, 2229), 'sfepy.base.base.output', 'output', (["('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r))"], {}), "('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r))\n", (2169, 2229), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((1505, 1517), 'time.clock', 'time.clock', ([], {}), '()\n', (1515, 1517), False, 'import time\n'), ((5580, 5626), 'sfepy.solvers.solvers.NonlinearSolver.__init__', 'NonlinearSolver.__init__', (['self', 'conf'], {}), '(self, conf, **kwargs)\n', (5604, 5626), False, 'from sfepy.solvers.solvers import SolverMeta, NonlinearSolver\n'), ((5668, 5690), 'sfepy.base.log.get_logging_conf', 'get_logging_conf', (['conf'], {}), '(conf)\n', (5684, 5690), False, 'from sfepy.base.log import Log, get_logging_conf\n'), ((5716, 5746), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""log_conf"""'}), "(name='log_conf', **log)\n", (5722, 5746), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((7742, 7770), 'sfepy.base.base.get_default', 'get_default', (['conf', 'self.conf'], {}), '(conf, self.conf)\n', (7753, 7770), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((7785, 7811), 'sfepy.base.base.get_default', 'get_default', (['fun', 'self.fun'], {}), '(fun, self.fun)\n', (7796, 7811), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((7831, 7867), 'sfepy.base.base.get_default', 'get_default', (['fun_grad', 'self.fun_grad'], {}), '(fun_grad, self.fun_grad)\n', (7842, 7867), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((7889, 7929), 'sfepy.base.base.get_default', 'get_default', (['lin_solver', 'self.lin_solver'], {}), '(lin_solver, self.lin_solver)\n', (7900, 7929), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((7950, 7988), 'sfepy.base.base.get_default', 'get_default', (['iter_hook', 'self.iter_hook'], {}), '(iter_hook, self.iter_hook)\n', (7961, 7988), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((8006, 8038), 'sfepy.base.base.get_default', 'get_default', (['status', 'self.status'], {}), '(status, self.status)\n', (8017, 8038), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((8112, 8138), 'sfepy.base.base.get_default', 'get_default', (['ls_eps_a', '(1.0)'], {}), '(ls_eps_a, 1.0)\n', (8123, 8138), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((8155, 8181), 'sfepy.base.base.get_default', 'get_default', (['ls_eps_r', '(1.0)'], {}), '(ls_eps_r, 1.0)\n', (8166, 8181), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((13476, 13522), 'sfepy.solvers.solvers.NonlinearSolver.__init__', 'NonlinearSolver.__init__', (['self', 'conf'], {}), '(self, conf, **kwargs)\n', (13500, 13522), False, 'from sfepy.solvers.solvers import SolverMeta, NonlinearSolver\n'), ((14145, 14171), 'sfepy.base.base.get_default', 'get_default', (['fun', 'self.fun'], {}), '(fun, self.fun)\n', (14156, 14171), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((14189, 14221), 'sfepy.base.base.get_default', 'get_default', (['status', 'self.status'], {}), '(status, self.status)\n', (14200, 14221), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((14236, 14248), 'time.clock', 'time.clock', ([], {}), '()\n', (14246, 14248), False, 'import time\n'), ((14820, 14837), 'numpy.asarray', 'nm.asarray', (['vec_x'], {}), '(vec_x)\n', (14830, 14837), True, 'import numpy as nm\n'), ((16672, 16768), 'sfepy.solvers.solvers.NonlinearSolver.__init__', 'NonlinearSolver.__init__', (['self', 'conf'], {'petsc': 'petsc', 'pmtx': 'pmtx', 'prhs': 'prhs', 'comm': 'comm'}), '(self, conf, petsc=petsc, pmtx=pmtx, prhs=prhs,\n comm=comm, **kwargs)\n', (16696, 16768), False, 'from sfepy.solvers.solvers import SolverMeta, NonlinearSolver\n'), ((17019, 17045), 'sfepy.base.base.get_default', 'get_default', (['fun', 'self.fun'], {}), '(fun, self.fun)\n', (17030, 17045), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((17065, 17101), 'sfepy.base.base.get_default', 'get_default', (['fun_grad', 'self.fun_grad'], {}), '(fun_grad, self.fun_grad)\n', (17076, 17101), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((17123, 17163), 'sfepy.base.base.get_default', 'get_default', (['lin_solver', 'self.lin_solver'], {}), '(lin_solver, self.lin_solver)\n', (17134, 17163), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((17184, 17222), 'sfepy.base.base.get_default', 'get_default', (['iter_hook', 'self.iter_hook'], {}), '(iter_hook, self.iter_hook)\n', (17195, 17222), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((17240, 17272), 'sfepy.base.base.get_default', 'get_default', (['status', 'self.status'], {}), '(status, self.status)\n', (17251, 17272), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((17288, 17316), 'sfepy.base.base.get_default', 'get_default', (['pmtx', 'self.pmtx'], {}), '(pmtx, self.pmtx)\n', (17299, 17316), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((17332, 17360), 'sfepy.base.base.get_default', 'get_default', (['prhs', 'self.prhs'], {}), '(prhs, self.prhs)\n', (17343, 17360), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((17376, 17404), 'sfepy.base.base.get_default', 'get_default', (['comm', 'self.comm'], {}), '(comm, self.comm)\n', (17387, 17404), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((17419, 17431), 'time.clock', 'time.clock', ([], {}), '()\n', (17429, 17431), False, 'import time\n'), ((5874, 6101), 'sfepy.base.log.Log', 'Log', (["[['$||r||$'], ['iteration']]"], {'xlabels': "['', 'all iterations']", 'ylabels': "['$||r||$', 'iteration']", 'yscales': "['log', 'linear']", 'is_plot': '(conf.log.plot is not None)', 'log_filename': 'conf.log.text', 'formats': "[['%.8e'], ['%d']]"}), "([['$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[\n '$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.\n plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']])\n", (5877, 6101), False, 'from sfepy.base.log import Log, get_logging_conf\n'), ((10844, 10856), 'time.clock', 'time.clock', ([], {}), '()\n', (10854, 10856), False, 'import time\n'), ((11654, 11666), 'time.clock', 'time.clock', ([], {}), '()\n', (11664, 11666), False, 'import time\n'), ((12058, 12073), 'numpy.linalg.norm', 'nla.norm', (['vec_e'], {}), '(vec_e)\n', (12066, 12073), True, 'import numpy.linalg as nla\n'), ((3415, 3435), 'numpy.finfo', 'nm.finfo', (['nm.float64'], {}), '(nm.float64)\n', (3423, 3435), True, 'import numpy as nm\n'), ((8701, 8713), 'time.clock', 'time.clock', ([], {}), '()\n', (8711, 8713), False, 'import time\n'), ((11030, 11042), 'time.clock', 'time.clock', ([], {}), '()\n', (11040, 11042), False, 'import time\n'), ((11097, 11109), 'time.clock', 'time.clock', ([], {}), '()\n', (11107, 11109), False, 'import time\n'), ((11601, 11635), 'sfepy.base.base.output', 'output', (['"""solving linear system..."""'], {}), "('solving linear system...')\n", (11607, 11635), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((11819, 11831), 'time.clock', 'time.clock', ([], {}), '()\n', (11829, 11831), False, 'import time\n'), ((11883, 11900), 'sfepy.base.base.output', 'output', (['"""...done"""'], {}), "('...done')\n", (11889, 11900), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((11964, 11994), 'sfepy.base.base.output', 'output', (["('%10s: %7.2f [s]' % kv)"], {}), "('%10s: %7.2f [s]' % kv)\n", (11970, 11994), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((12121, 12181), 'sfepy.base.base.output', 'output', (['"""warning: linear system solution precision is lower"""'], {}), "('warning: linear system solution precision is lower')\n", (12127, 12181), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((12198, 12283), 'sfepy.base.base.output', 'output', (["('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red))"], {}), "('then the value set in solver options! (err = %e < %e)' % (lerr,\n lin_red))\n", (12204, 12283), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((13730, 13785), 'sfepy.base.base.output', 'output', (["('scipy solver %s does not exist!' % conf.method)"], {}), "('scipy solver %s does not exist!' % conf.method)\n", (13736, 13785), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((13798, 13830), 'sfepy.base.base.output', 'output', (['"""using broyden3 instead"""'], {}), "('using broyden3 instead')\n", (13804, 13830), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((14905, 14917), 'time.clock', 'time.clock', ([], {}), '()\n', (14915, 14917), False, 'import time\n'), ((16481, 16498), 'petsc4py.init', 'petsc4py.init', (['[]'], {}), '([])\n', (16494, 16498), False, 'import petsc4py\n'), ((18313, 18325), 'time.clock', 'time.clock', ([], {}), '()\n', (18323, 18325), False, 'import time\n'), ((9099, 9111), 'time.clock', 'time.clock', ([], {}), '()\n', (9109, 9111), False, 'import time\n'), ((9705, 9812), 'sfepy.base.base.output', 'output', (["('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last *\n conf.ls_on, red * ls))"], {}), "('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, \n err_last * conf.ls_on, red * ls))\n", (9711, 9812), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((10050, 10135), 'sfepy.base.base.output', 'output', (["('rezidual computation failed for iter %d (new ls: %e)!' % (it, red * ls))"], {}), "('rezidual computation failed for iter %d (new ls: %e)!' % (it, red * ls)\n )\n", (10056, 10135), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((10219, 10265), 'sfepy.base.base.output', 'output', (['"""linesearch failed, continuing anyway"""'], {}), "('linesearch failed, continuing anyway')\n", (10225, 10265), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((9195, 9210), 'numpy.linalg.norm', 'nla.norm', (['vec_r'], {}), '(vec_r)\n', (9203, 9210), True, 'import numpy.linalg as nla\n'), ((9934, 9954), 'sfepy.base.base.output', 'output', (['"""giving up!"""'], {}), "('giving up!')\n", (9940, 9954), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((11218, 11230), 'time.clock', 'time.clock', ([], {}), '()\n', (11228, 11230), False, 'import time\n'), ((8891, 8911), 'sfepy.base.base.output', 'output', (['"""giving up!"""'], {}), "('giving up!')\n", (8897, 8911), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((9263, 9309), 'sfepy.base.base.output', 'output', (['"""infs or nans in the residual:"""', 'vec_r'], {}), "('infs or nans in the residual:', vec_r)\n", (9269, 9309), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((9391, 9398), 'sfepy.base.base.debug', 'debug', ([], {}), '()\n', (9396, 9398), False, 'from sfepy.base.base import output, get_default, debug, Struct\n'), ((9341, 9359), 'numpy.isfinite', 'nm.isfinite', (['vec_r'], {}), '(vec_r)\n', (9352, 9359), True, 'import numpy as nm\n')] |
from __future__ import absolute_import
from sfepy import data_dir
import six
filename_mesh = data_dir + '/meshes/3d/special/cube_cylinder.mesh'
if 0:
from sfepy.discrete.fem.utils import refine_mesh
refinement_level = 1
filename_mesh = refine_mesh(filename_mesh, refinement_level)
material_2 = {
'name' : 'coef',
'values' : {'val' : 1.0},
}
field_1 = {
'name' : 'temperature',
'dtype' : 'real',
'shape' : (1,),
'region' : 'Omega',
'approx_order' : 1,
}
variables = {
't' : ('unknown field', 'temperature', 0),
's' : ('test field', 'temperature', 't'),
}
regions = {
'Omega' : 'all',
'Gamma_Left' : ('vertices in (x < 0.0001)', 'facet'),
'Gamma_Right' : ('vertices in (x > 0.999)', 'facet'),
}
ebcs = {
't1' : ('Gamma_Left', {'t.0' : 2.0}),
't2' : ('Gamma_Right', {'t.0' : -2.0}),
}
integral_1 = {
'name' : 'i',
'order' : 1,
}
equations = {
'Temperature' : """dw_laplace.i.Omega(coef.val, s, t) = 0"""
}
class DiagPC(object):
"""
Diagonal (Jacobi) preconditioner.
Equivalent to setting `'precond' : 'jacobi'`.
"""
def setUp(self, pc):
A = pc.getOperators()[0]
self.idiag = 1.0 / A.getDiagonal()
def apply(self, pc, x, y):
y.pointwiseMult(x, self.idiag)
def setup_petsc_precond(mtx, problem):
return DiagPC()
solvers = {
'd00' : ('ls.scipy_direct',
{'method' : 'umfpack',
'warn' : True,}
),
'd01' : ('ls.scipy_direct',
{'method' : 'superlu',
'warn' : True,}
),
'd10' : ('ls.mumps', {}),
'i00' : ('ls.pyamg',
{'method' : 'ruge_stuben_solver',
'accel' : 'cg',
'eps_r' : 1e-12,
'method:max_levels' : 5,
'solve:cycle' : 'V',}
),
'i01' : ('ls.pyamg',
{'method' : 'smoothed_aggregation_solver',
'accel' : 'cg',
'eps_r' : 1e-12,}
),
'i02' : ('ls.pyamg_krylov',
{'method' : 'cg',
'eps_r' : 1e-12,
'i_max' : 1000,}
),
'i10' : ('ls.petsc',
{'method' : 'cg', # ksp_type
'precond' : 'none', # pc_type
'eps_a' : 1e-12, # abstol
'eps_r' : 1e-12, # rtol
'i_max' : 1000,} # maxits
),
'i11' : ('ls.petsc',
{'method' : 'cg', # ksp_type
'precond' : 'python', # just for output (unused)
'setup_precond' : setup_petsc_precond, # user-defined pc
'eps_a' : 1e-12, # abstol
'eps_r' : 1e-12, # rtol
'i_max' : 1000,} # maxits
),
'i12' : ('ls.petsc',
{'method' : 'cg', # ksp_type
'precond' : 'jacobi', # pc_type
'eps_a' : 1e-12, # abstol
'eps_r' : 1e-12, # rtol
'i_max' : 1000,} # maxits
),
'i13' : ('ls.petsc',
{'method' : 'cg', # ksp_type
'precond' : 'icc', # pc_type
'eps_a' : 1e-12, # abstol
'eps_r' : 1e-12, # rtol
'i_max' : 1000,} # maxits
),
'i20' : ('ls.scipy_iterative',
{'method' : 'cg',
'i_max' : 1000,
'eps_r' : 1e-12,}
),
'i21' : ('ls.scipy_iterative',
{'method' : 'bicgstab',
'i_max' : 1000,
'eps_r' : 1e-12,}
),
'i22' : ('ls.scipy_iterative',
{'method' : 'qmr',
'i_max' : 1000,
'eps_r' : 1e-12,}
),
'newton' : ('nls.newton', {
'i_max' : 1,
'eps_a' : 1e-10,
}),
}
options = {
'nls' : 'newton',
}
from sfepy.base.testing import TestCommon
output_name = 'test_linear_solvers_%s.vtk'
class Test(TestCommon):
can_fail = ['ls.pyamg', 'ls.pyamg_krylov', 'ls.petsc', 'ls.mumps',]
@staticmethod
def from_conf(conf, options):
from sfepy.discrete import Problem
problem = Problem.from_conf(conf)
problem.time_update()
test = Test(problem=problem, conf=conf, options=options)
return test
def _list_linear_solvers(self, confs):
d = []
for key, val in six.iteritems(confs):
if val.kind.find('ls.') == 0:
d.append(val)
d.sort(key=lambda a: a.name)
return d
def test_solvers(self):
from sfepy.base.base import IndexedStruct
import os.path as op
solver_confs = self._list_linear_solvers(self.problem.solver_confs)
ok = True
tt = []
for solver_conf in solver_confs:
method = solver_conf.get('method', '')
precond = solver_conf.get('precond', '')
name = ' '.join((solver_conf.name, solver_conf.kind,
method, precond)).rstrip()
self.report(name)
self.report('matrix size:', self.problem.mtx_a.shape)
self.report(' nnz:', self.problem.mtx_a.nnz)
status = IndexedStruct()
try:
self.problem.init_solvers(status=status,
ls_conf=solver_conf,
force=True)
state = self.problem.solve()
failed = status.nls_status.condition != 0
except Exception as aux:
failed = True
status = None
exc = aux
ok = ok and ((not failed) or (solver_conf.kind in self.can_fail))
if status is not None:
status = status.nls_status
for kv in six.iteritems(status.time_stats):
self.report('%10s: %7.2f [s]' % kv)
self.report('condition: %d, err0: %.3e, err: %.3e'
% (status.condition, status.err0, status.err))
tt.append([name,
status.time_stats['solve'],
status.ls_n_iter,
status.err])
aux = name.replace(' ', '_')
fname = op.join(self.options.out_dir,
op.split(self.conf.output_name)[1]) % aux
self.problem.save_state(fname, state)
else:
self.report('solver failed:')
self.report(exc)
tt.append([name, -1, 1e10, 1e10])
tt.sort(key=lambda a: a[1])
self.report('solution times / numbers of iterations (residual norms):')
for row in tt:
self.report('%.2f [s] / % 4d' % (row[1], row[2]),
'(%.3e)' % row[3], ':', row[0])
return ok
def test_ls_reuse(self):
import numpy as nm
from sfepy.solvers import Solver
from sfepy.discrete.state import State
self.problem.init_solvers(ls_conf=self.problem.solver_confs['d00'])
nls = self.problem.get_nls()
state0 = State(self.problem.equations.variables)
state0.apply_ebc()
vec0 = state0.get_reduced()
self.problem.update_materials()
rhs = nls.fun(vec0)
mtx = nls.fun_grad(vec0)
ok = True
for name in ['i12', 'i01']:
solver_conf = self.problem.solver_confs[name]
method = solver_conf.get('method', '')
precond = solver_conf.get('precond', '')
name = ' '.join((solver_conf.name, solver_conf.kind,
method, precond)).rstrip()
self.report(name)
try:
ls = Solver.any_from_conf(solver_conf)
except:
self.report('skipped!')
continue
conf = ls.conf.copy()
conf.force_reuse = True
sol00 = ls(rhs, mtx=mtx, conf=conf)
digest00 = ls.mtx_digest
sol0 = ls(rhs, mtx=mtx)
digest0 = ls.mtx_digest
sol1 = ls(rhs, mtx=2*mtx, conf=conf)
digest1 = ls.mtx_digest
sol2 = ls(rhs, mtx=2*mtx)
digest2 = ls.mtx_digest
ls(rhs, mtx=2*mtx)
digest3 = ls.mtx_digest
_ok = digest00 != digest0
self.report(digest00, '!=', digest0, ':', _ok); ok = ok and _ok
_ok = digest0 == digest1
self.report(digest0, '==', digest1, ':', _ok); ok = ok and _ok
_ok = digest1 != digest2
self.report(digest1, '!=', digest2, ':', _ok); ok = ok and _ok
_ok = digest2[1] == digest3[1]
self.report(digest2[1], '==', digest3[1], ':', _ok); ok = ok and _ok
_ok = nm.allclose(sol00, sol0, atol=1e-12, rtol=0.0)
self.report('sol00 == sol0:', _ok); ok = ok and _ok
_ok = nm.allclose(sol0, sol1, atol=1e-12, rtol=0.0)
self.report('sol0 == sol1:', _ok); ok = ok and _ok
_ok = nm.allclose(sol0, 2 * sol2, atol=1e-12, rtol=0.0)
self.report('sol0 == 2 * sol2:', _ok); ok = ok and _ok
return ok
| [
"sfepy.discrete.Problem.from_conf",
"sfepy.discrete.fem.utils.refine_mesh",
"sfepy.solvers.Solver.any_from_conf",
"sfepy.discrete.state.State",
"sfepy.base.base.IndexedStruct"
] | [((250, 294), 'sfepy.discrete.fem.utils.refine_mesh', 'refine_mesh', (['filename_mesh', 'refinement_level'], {}), '(filename_mesh, refinement_level)\n', (261, 294), False, 'from sfepy.discrete.fem.utils import refine_mesh\n'), ((4007, 4030), 'sfepy.discrete.Problem.from_conf', 'Problem.from_conf', (['conf'], {}), '(conf)\n', (4024, 4030), False, 'from sfepy.discrete import Problem\n'), ((4230, 4250), 'six.iteritems', 'six.iteritems', (['confs'], {}), '(confs)\n', (4243, 4250), False, 'import six\n'), ((6997, 7036), 'sfepy.discrete.state.State', 'State', (['self.problem.equations.variables'], {}), '(self.problem.equations.variables)\n', (7002, 7036), False, 'from sfepy.discrete.state import State\n'), ((5046, 5061), 'sfepy.base.base.IndexedStruct', 'IndexedStruct', ([], {}), '()\n', (5059, 5061), False, 'from sfepy.base.base import IndexedStruct\n'), ((8668, 8714), 'numpy.allclose', 'nm.allclose', (['sol00', 'sol0'], {'atol': '(1e-12)', 'rtol': '(0.0)'}), '(sol00, sol0, atol=1e-12, rtol=0.0)\n', (8679, 8714), True, 'import numpy as nm\n'), ((8797, 8842), 'numpy.allclose', 'nm.allclose', (['sol0', 'sol1'], {'atol': '(1e-12)', 'rtol': '(0.0)'}), '(sol0, sol1, atol=1e-12, rtol=0.0)\n', (8808, 8842), True, 'import numpy as nm\n'), ((8924, 8973), 'numpy.allclose', 'nm.allclose', (['sol0', '(2 * sol2)'], {'atol': '(1e-12)', 'rtol': '(0.0)'}), '(sol0, 2 * sol2, atol=1e-12, rtol=0.0)\n', (8935, 8973), True, 'import numpy as nm\n'), ((5663, 5695), 'six.iteritems', 'six.iteritems', (['status.time_stats'], {}), '(status.time_stats)\n', (5676, 5695), False, 'import six\n'), ((7609, 7642), 'sfepy.solvers.Solver.any_from_conf', 'Solver.any_from_conf', (['solver_conf'], {}), '(solver_conf)\n', (7629, 7642), False, 'from sfepy.solvers import Solver\n'), ((6200, 6231), 'os.path.split', 'op.split', (['self.conf.output_name'], {}), '(self.conf.output_name)\n', (6208, 6231), True, 'import os.path as op\n')] |
from __future__ import absolute_import
import numpy as nm
from sfepy.base.base import output, assert_, get_default, Struct
from sfepy.homogenization.coefs_base import CorrSolution, \
TCorrectorsViaPressureEVP, CorrMiniApp
from sfepy.solvers.ts import TimeStepper
from six.moves import range
class PressureRHSVector( CorrMiniApp ):
def __call__( self, problem = None, data = None ):
problem = get_default( problem, self.problem )
problem.select_variables( self.variables )
problem.set_equations( self.equations )
problem.select_bcs(ebc_names = self.ebcs, epbc_names = self.epbcs,
lcbc_names=self.get('lcbcs', []))
state = problem.create_state()
state.apply_ebc()
eqs = problem.equations
eqs.set_variables_from_state(state.vec)
vec = eqs.create_stripped_state_vector()
eqs.time_update_materials(problem.get_timestepper())
eqs.evaluate(mode='weak', dw_mode='vector', asm_obj=vec)
return vec
class TCorrectorsRSViaPressureEVP( TCorrectorsViaPressureEVP ):
def __call__( self, problem = None, data = None ):
"""data: corrs_rs, evp"""
problem = get_default( problem, self.problem )
self.init_solvers(problem)
ts = problem.get_timestepper()
corrs, evp = [data[ii] for ii in self.requires]
assert_( evp.ebcs == self.ebcs )
assert_( evp.epbcs == self.epbcs )
dim = problem.get_dim()
self.setup_equations(self.equations)
solve = self.compute_correctors
states = nm.zeros((dim, dim), dtype=nm.object)
clist = []
for ir in range( dim ):
for ic in range( dim ):
states[ir,ic] = solve(evp, -1.0, corrs.states[ir,ic], ts)
clist.append((ir, ic))
corr_sol = CorrSolution(name=self.name,
states=states,
n_step=ts.n_step,
components=clist)
self.save(corr_sol, problem, ts)
return corr_sol
class TCorrectorsPressureViaPressureEVP( TCorrectorsViaPressureEVP ):
def __call__( self, problem = None, data = None, save_hook = None ):
"""data: corrs_pressure, evp, optionally vec_g"""
problem = get_default( problem, self.problem )
self.init_solvers(problem)
ts = problem.get_timestepper()
corrs, evp = [data[ii] for ii in self.requires[:2]]
if len(self.requires) == 3:
vec_g = data[self.requires[2]]
else:
vec_g = None
assert_( evp.ebcs == self.ebcs )
assert_( evp.epbcs == self.epbcs )
self.setup_equations(self.equations)
solve = self.compute_correctors
state = solve(evp, 1.0, corrs.state, ts, vec_g=vec_g)
corr_sol = CorrSolution(name=self.name,
state=state,
n_step=ts.n_step)
self.save(corr_sol, problem, ts)
return corr_sol
| [
"sfepy.homogenization.coefs_base.CorrSolution",
"sfepy.base.base.get_default",
"sfepy.base.base.assert_"
] | [((416, 450), 'sfepy.base.base.get_default', 'get_default', (['problem', 'self.problem'], {}), '(problem, self.problem)\n', (427, 450), False, 'from sfepy.base.base import output, assert_, get_default, Struct\n'), ((1204, 1238), 'sfepy.base.base.get_default', 'get_default', (['problem', 'self.problem'], {}), '(problem, self.problem)\n', (1215, 1238), False, 'from sfepy.base.base import output, assert_, get_default, Struct\n'), ((1381, 1411), 'sfepy.base.base.assert_', 'assert_', (['(evp.ebcs == self.ebcs)'], {}), '(evp.ebcs == self.ebcs)\n', (1388, 1411), False, 'from sfepy.base.base import output, assert_, get_default, Struct\n'), ((1422, 1454), 'sfepy.base.base.assert_', 'assert_', (['(evp.epbcs == self.epbcs)'], {}), '(evp.epbcs == self.epbcs)\n', (1429, 1454), False, 'from sfepy.base.base import output, assert_, get_default, Struct\n'), ((1594, 1631), 'numpy.zeros', 'nm.zeros', (['(dim, dim)'], {'dtype': 'nm.object'}), '((dim, dim), dtype=nm.object)\n', (1602, 1631), True, 'import numpy as nm\n'), ((1669, 1679), 'six.moves.range', 'range', (['dim'], {}), '(dim)\n', (1674, 1679), False, 'from six.moves import range\n'), ((1852, 1931), 'sfepy.homogenization.coefs_base.CorrSolution', 'CorrSolution', ([], {'name': 'self.name', 'states': 'states', 'n_step': 'ts.n_step', 'components': 'clist'}), '(name=self.name, states=states, n_step=ts.n_step, components=clist)\n', (1864, 1931), False, 'from sfepy.homogenization.coefs_base import CorrSolution, TCorrectorsViaPressureEVP, CorrMiniApp\n'), ((2317, 2351), 'sfepy.base.base.get_default', 'get_default', (['problem', 'self.problem'], {}), '(problem, self.problem)\n', (2328, 2351), False, 'from sfepy.base.base import output, assert_, get_default, Struct\n'), ((2616, 2646), 'sfepy.base.base.assert_', 'assert_', (['(evp.ebcs == self.ebcs)'], {}), '(evp.ebcs == self.ebcs)\n', (2623, 2646), False, 'from sfepy.base.base import output, assert_, get_default, Struct\n'), ((2657, 2689), 'sfepy.base.base.assert_', 'assert_', (['(evp.epbcs == self.epbcs)'], {}), '(evp.epbcs == self.epbcs)\n', (2664, 2689), False, 'from sfepy.base.base import output, assert_, get_default, Struct\n'), ((2861, 2920), 'sfepy.homogenization.coefs_base.CorrSolution', 'CorrSolution', ([], {'name': 'self.name', 'state': 'state', 'n_step': 'ts.n_step'}), '(name=self.name, state=state, n_step=ts.n_step)\n', (2873, 2920), False, 'from sfepy.homogenization.coefs_base import CorrSolution, TCorrectorsViaPressureEVP, CorrMiniApp\n'), ((1705, 1715), 'six.moves.range', 'range', (['dim'], {}), '(dim)\n', (1710, 1715), False, 'from six.moves import range\n')] |
"""
Quantum oscillator.
See :ref:`quantum-quantum_common`.
"""
from __future__ import absolute_import
from sfepy.linalg import norm_l2_along_axis
from examples.quantum.quantum_common import common
def get_exact(n_eigs, box_size, dim):
if dim == 2:
eigs = [1] + [2]*2 + [3]*3 + [4]*4 + [5]*5 + [6]*6
elif dim == 3:
eigs = [float(1)/2 + x for x in [1] + [2]*3 + [3]*6 + [4]*10]
return eigs
def fun_v(ts, coor, mode=None, **kwargs):
if not mode == 'qp': return
out = {}
C = 0.5
val = C * norm_l2_along_axis(coor, axis=1, squared=True)
val.shape = (val.shape[0], 1, 1)
out['V'] = val
return out
def define(n_eigs=20, tau=0.0):
l = common(fun_v, get_exact=get_exact, n_eigs=n_eigs, tau=tau)
return l
| [
"sfepy.linalg.norm_l2_along_axis"
] | [((696, 754), 'examples.quantum.quantum_common.common', 'common', (['fun_v'], {'get_exact': 'get_exact', 'n_eigs': 'n_eigs', 'tau': 'tau'}), '(fun_v, get_exact=get_exact, n_eigs=n_eigs, tau=tau)\n', (702, 754), False, 'from examples.quantum.quantum_common import common\n'), ((536, 582), 'sfepy.linalg.norm_l2_along_axis', 'norm_l2_along_axis', (['coor'], {'axis': '(1)', 'squared': '(True)'}), '(coor, axis=1, squared=True)\n', (554, 582), False, 'from sfepy.linalg import norm_l2_along_axis\n')] |
"""
Notes
-----
Important attributes of continuous (order > 0) :class:`Field` and
:class:`SurfaceField` instances:
- `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]`
- `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]`
where `conn` is the mesh vertex connectivity, `econn` is the
region-local field connectivity.
"""
import time
import numpy as nm
from sfepy.base.base import output, assert_
import fea
from sfepy.discrete.fem.utils import prepare_remap
from sfepy.discrete.common.dof_info import expand_nodes_to_dofs
from sfepy.discrete.fem.global_interp import get_ref_coors
from sfepy.discrete.fem.facets import get_facet_dof_permutations
from sfepy.discrete.fem.fields_base import (FEField, VolumeField, SurfaceField,
H1Mixin)
from sfepy.discrete.fem.extmods.bases import evaluate_in_rc
class H1NodalMixin(H1Mixin):
def _setup_facet_orientations(self):
order = self.approx_order
self.node_desc = self.interp.describe_nodes()
edge_nodes = self.node_desc.edge_nodes
if edge_nodes is not None:
n_fp = self.gel.edges.shape[1]
self.edge_dof_perms = get_facet_dof_permutations(n_fp, self.igs,
order)
face_nodes = self.node_desc.face_nodes
if face_nodes is not None:
n_fp = self.gel.faces.shape[1]
self.face_dof_perms = get_facet_dof_permutations(n_fp, self.igs,
order)
def _setup_edge_dofs(self):
"""
Setup edge DOF connectivity.
"""
if self.node_desc.edge is None:
return 0, None, None
return self._setup_facet_dofs(1, self.node_desc.edge,
self.edge_dof_perms,
self.n_vertex_dof)
def _setup_face_dofs(self):
"""
Setup face DOF connectivity.
"""
if self.node_desc.face is None:
return 0, None, None
return self._setup_facet_dofs(self.domain.shape.tdim - 1,
self.node_desc.face,
self.face_dof_perms,
self.n_vertex_dof + self.n_edge_dof)
def _setup_facet_dofs(self, dim, facet_desc, facet_perms, offset):
"""
Helper function to setup facet DOF connectivity, works for both
edges and faces.
"""
facet_desc = nm.array(facet_desc)
n_dof_per_facet = facet_desc.shape[1]
cmesh = self.domain.cmesh
facets = self.region.entities[dim]
ii = nm.arange(facets.shape[0], dtype=nm.int32)
all_dofs = offset + expand_nodes_to_dofs(ii, n_dof_per_facet)
# Prepare global facet id remapping to field-local numbering.
remap = prepare_remap(facets, cmesh.num[dim])
cconn = self.region.domain.cmesh.get_conn(self.region.tdim, dim)
offs = cconn.offsets
n_f = self.gel.edges.shape[0] if dim == 1 else self.gel.faces.shape[0]
oris = cmesh.get_orientations(dim)
for ig, ap in self.aps.iteritems():
gcells = self.region.get_cells(ig, offset=False)
n_el = gcells.shape[0]
indices = cconn.indices[offs[gcells[0]]:offs[gcells[-1]+1]]
facets_of_cells = remap[indices]
ori = oris[offs[gcells[0]]:offs[gcells[-1]+1]]
perms = facet_perms[ig][ori]
# Define global facet dof numbers.
gdofs = offset + expand_nodes_to_dofs(facets_of_cells,
n_dof_per_facet)
# Elements of facets.
iel = nm.arange(n_el, dtype=nm.int32).repeat(n_f)
ies = nm.tile(nm.arange(n_f, dtype=nm.int32), n_el)
# DOF columns in econn for each facet.
iep = facet_desc[ies]
iaux = nm.arange(gdofs.shape[0], dtype=nm.int32)
ap.econn[iel[:, None], iep] = gdofs[iaux[:, None], perms]
n_dof = n_dof_per_facet * facets.shape[0]
assert_(n_dof == nm.prod(all_dofs.shape))
return n_dof, all_dofs, remap
def _setup_bubble_dofs(self):
"""
Setup bubble DOF connectivity.
"""
if self.node_desc.bubble is None:
return 0, None, None
offset = self.n_vertex_dof + self.n_edge_dof + self.n_face_dof
n_dof = 0
n_dof_per_cell = self.node_desc.bubble.shape[0]
all_dofs = {}
remaps = {}
for ig, ap in self.aps.iteritems():
ii = self.region.get_cells(ig)
n_cell = ii.shape[0]
nd = n_dof_per_cell * n_cell
group = self.domain.groups[ig]
remaps[ig] = prepare_remap(ii, group.shape.n_el)
aux = nm.arange(offset + n_dof, offset + n_dof + nd,
dtype=nm.int32)
aux.shape = (n_cell, n_dof_per_cell)
iep = self.node_desc.bubble[0]
ap.econn[:,iep:] = aux
all_dofs[ig] = aux
n_dof += nd
return n_dof, all_dofs, remaps
def set_dofs(self, fun=0.0, region=None, dpn=None, warn=None):
"""
Set the values of DOFs in a given region using a function of space
coordinates or value `fun`.
"""
if region is None:
region = self.region
if dpn is None:
dpn = self.n_components
aux = self.get_dofs_in_region(region, clean=True, warn=warn)
nods = nm.unique(nm.hstack(aux))
if callable(fun):
vals = fun(self.get_coor(nods))
elif nm.isscalar(fun):
vals = nm.repeat([fun], nods.shape[0] * dpn)
elif isinstance(fun, nm.ndarray):
assert_(len(fun) == dpn)
vals = nm.repeat(fun, nods.shape[0])
else:
raise ValueError('unknown function/value type! (%s)' % type(fun))
return nods, vals
def evaluate_at(self, coors, source_vals, strategy='kdtree',
close_limit=0.1, cache=None, ret_cells=False,
ret_status=False, ret_ref_coors=False, verbose=True):
"""
Evaluate source DOF values corresponding to the field in the given
coordinates using the field interpolation.
Parameters
----------
coors : array
The coordinates the source values should be interpolated into.
source_vals : array
The source DOF values corresponding to the field.
strategy : str, optional
The strategy for finding the elements that contain the
coordinates. Only 'kdtree' is supported for the moment.
close_limit : float, optional
The maximum limit distance of a point from the closest
element allowed for extrapolation.
cache : Struct, optional
To speed up a sequence of evaluations, the field mesh, the inverse
connectivity of the field mesh and the KDTree instance can
be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and
`cache.kdtree`. Optionally, the cache can also contain the
reference element coordinates as `cache.ref_coors`,
`cache.cells` and `cache.status`, if the evaluation occurs
in the same coordinates repeatedly. In that case the KDTree
related data are ignored.
ret_cells : bool, optional
If True, return also the cell indices the coordinates are in.
ret_status : bool, optional
If True, return also the status for each point: 0 is
success, 1 is extrapolation within `close_limit`, 2 is
extrapolation outside `close_limit`, 3 is failure.
ret_ref_coors : bool, optional
If True, return also the found reference element coordinates.
verbose : bool
If False, reduce verbosity.
Returns
-------
vals : array
The interpolated values.
cells : array
The cell indices, if `ret_cells` or `ret_status` are True.
status : array
The status, if `ret_status` is True.
"""
output('evaluating in %d points...' % coors.shape[0], verbose=verbose)
ref_coors, cells, status = get_ref_coors(self, coors,
strategy=strategy,
close_limit=close_limit,
cache=cache,
verbose=verbose)
tt = time.clock()
vertex_coorss, nodess, orders, mtx_is = [], [], [], []
conns = []
for ap in self.aps.itervalues():
ps = ap.interp.poly_spaces['v']
vertex_coorss.append(ps.geometry.coors)
nodess.append(ps.nodes)
mtx_is.append(ps.get_mtx_i())
orders.append(ps.order)
conns.append(ap.econn)
orders = nm.array(orders, dtype=nm.int32)
# Interpolate to the reference coordinates.
vals = nm.empty((coors.shape[0], source_vals.shape[1]),
dtype=source_vals.dtype)
evaluate_in_rc(vals, ref_coors, cells, status, source_vals,
conns, vertex_coorss, nodess, orders, mtx_is,
1e-15)
output('interpolation: %f s' % (time.clock()-tt),verbose=verbose)
output('...done',verbose=verbose)
if ret_ref_coors:
return vals, ref_coors, cells, status
elif ret_status:
return vals, cells, status
elif ret_cells:
return vals, cells
else:
return vals
class H1NodalVolumeField(H1NodalMixin, VolumeField):
family_name = 'volume_H1_lagrange'
def interp_v_vals_to_n_vals(self, vec):
"""
Interpolate a function defined by vertex DOF values using the FE
geometry base (P1 or Q1) into the extra nodes, i.e. define the
extra DOF values.
"""
if not self.node_desc.has_extra_nodes():
enod_vol_val = vec.copy()
else:
dim = vec.shape[1]
enod_vol_val = nm.zeros((self.n_nod, dim), dtype=nm.float64)
for ig, ap in self.aps.iteritems():
group = self.domain.groups[ig]
econn = ap.econn
coors = ap.interp.poly_spaces['v'].node_coors
ginterp = ap.interp.gel.interp
bf = ginterp.poly_spaces['v'].eval_base(coors)
bf = bf[:,0,:].copy()
evec = nm.dot(bf, vec[group.conn])
enod_vol_val[econn] = nm.swapaxes(evec, 0, 1)
return enod_vol_val
def set_basis(self, maps, methods):
"""
This function along with eval_basis supports the general term IntFE.
It sets parameters and basis functions at reference element
according to its method (val, grad, div, etc).
Parameters
----------
maps : class
It provides information about mapping between reference and real
element. Quadrature points stored in maps.qp_coor are used here.
method : list of string
It stores methods for variable evaluation. At first position, there
is one of val, grad, or div.
self.bfref : numpy.array of shape = (n_qp, n_basis) + basis_shape
An array that stores basis functions evaluated at quadrature
points. Here n_qp is number of quadrature points, n_basis is
number of basis functions, and basis_shape is a shape of basis
function, i.e. (1,) for scalar-valued, (dim,) for vector-valued,
(dim, dim) for matrix-valued, etc.
Returns
-------
self.bfref : numpy.array
It stores a basis functions at quadrature points of shape according
to proceeded methods.
self.n_basis : int
number of basis functions
"""
self.eval_method = methods
def get_grad(maps, shape):
bfref0 = eval_base(maps.qp_coor, diff=True).swapaxes(1, 2)
if shape == (1,): # scalar variable
bfref = bfref0
elif len(shape) == 1: # vector variable
vec_shape = nm.array(bfref0.shape + shape)
vec_shape[1] *= shape[0]
bfref = nm.zeros(vec_shape)
for ii in nm.arange(shape[0]):
slc = slice(ii*bfref0.shape[1], (ii+1)*bfref0.shape[1])
bfref[:, slc, ii] = bfref0
else: # higher-order tensors variable
msg = "Evaluation of basis has not been implemented \
for higher-order tensors yet."
raise NotImplementedError(msg)
return bfref
def get_val(maps, shape):
bfref0 = eval_base(maps.qp_coor, diff=False).swapaxes(1, 2)
if self.shape == (1,): # scalar variable
bfref = bfref0
elif len(shape) == 1:
vec_shape = nm.array(bfref0.shape)
vec_shape[1:3] *= shape[0]
bfref = nm.zeros(vec_shape)
for ii in nm.arange(shape[0]):
slc = slice(ii*bfref0.shape[1], (ii+1)*bfref0.shape[1])
bfref[:, slc] = bfref0
else: # higher-order tensors variable
msg = "Evaluation of basis has not been implemented \
for higher-order tensors yet."
raise NotImplementedError(msg)
return bfref
eval_base = self.interp.poly_spaces['v'].eval_base
if self.eval_method[0] == 'val':
bfref = get_val(maps, self.shape)
elif self.eval_method[0] == 'grad':
bfref = get_grad(maps, self.shape)
elif self.eval_method[0] == 'div':
bfref = get_grad(maps, self.shape)
else:
raise NotImplementedError("The method '%s' is not implemented" \
% (self.eval_method))
self.bfref = bfref
self.n_basis = self.bfref.shape[1]
def eval_basis(self, maps):
"""
It returns basis functions evaluated at quadrature points and mapped
at reference element according to real element.
"""
if self.eval_method == ['grad']:
val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0))
return val
elif self.eval_method == ['val']:
return self.bfref
elif self.eval_method == ['div']:
val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0))
val = nm.atleast_3d(nm.einsum('ijkk', val))
return val
elif self.eval_method == ['grad', 'sym', 'Man']:
val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0))
from sfepy.terms.terms_general import proceed_methods
val = proceed_methods(val, self.eval_method[1:])
return val
else:
msg = "Improper method '%s' for evaluation of basis functions" \
% (self.eval_method)
raise NotImplementedError(msg)
class H1DiscontinuousField(H1NodalMixin, VolumeField):
family_name = 'volume_H1_lagrange_discontinuous'
def _setup_approximations(self):
self.aps = {}
self.aps_by_name = {}
for ig in self.igs:
name = self.interp.name + '_%s_ig%d' % (self.region.name, ig)
ap = fea.DiscontinuousApproximation(name, self.interp,
self.region, ig)
self.aps[ig] = ap
self.aps_by_name[ap.name] = ap
def _setup_global_base(self):
"""
Setup global DOF/base function indices and connectivity of the field.
"""
self._setup_facet_orientations()
self._init_econn()
n_dof = 0
all_dofs = {}
remaps = {}
for ig, ap in self.aps.iteritems():
ii = self.region.get_cells(ig)
nd = nm.prod(ap.econn.shape)
group = self.domain.groups[ig]
remaps[ig] = prepare_remap(ii, group.shape.n_el)
aux = nm.arange(n_dof, n_dof + nd, dtype=nm.int32)
aux.shape = ap.econn.shape
ap.econn[:] = aux
all_dofs[ig] = aux
n_dof += nd
self.n_nod = n_dof
self.n_bubble_dof = n_dof
self.bubble_dofs = all_dofs
self.bubble_remaps = remaps
self.n_vertex_dof = self.n_edge_dof = self.n_face_dof = 0
self._setup_esurface()
def extend_dofs(self, dofs, fill_value=None):
"""
Extend DOFs to the whole domain using the `fill_value`, or the
smallest value in `dofs` if `fill_value` is None.
"""
if self.approx_order != 0:
dofs = self.average_to_vertices(dofs)
new_dofs = FEField.extend_dofs(self, dofs)
return new_dofs
def remove_extra_dofs(self, dofs):
"""
Remove DOFs defined in higher order nodes (order > 1).
"""
if self.approx_order != 0:
dofs = self.average_to_vertices(dofs)
new_dofs = FEField.remove_extra_dofs(self, dofs)
return new_dofs
def average_to_vertices(self, dofs):
"""
Average DOFs of the discontinuous field into the field region
vertices.
"""
data_qp, integral = self.interp_to_qp(dofs)
vertex_dofs = self.average_qp_to_vertices(data_qp, integral)
return vertex_dofs
class H1NodalSurfaceField(H1NodalMixin, SurfaceField):
"""
A field defined on a surface region.
"""
family_name = 'surface_H1_lagrange'
def interp_v_vals_to_n_vals(self, vec):
"""
Interpolate a function defined by vertex DOF values using the FE
surface geometry base (P1 or Q1) into the extra nodes, i.e. define the
extra DOF values.
"""
if not self.node_desc.has_extra_nodes():
enod_vol_val = vec.copy()
else:
msg = 'surface nodal fields do not support higher order nodes yet!'
raise NotImplementedError(msg)
return enod_vol_val
| [
"sfepy.discrete.fem.fields_base.FEField.remove_extra_dofs",
"sfepy.discrete.fem.fields_base.FEField.extend_dofs",
"sfepy.discrete.fem.extmods.bases.evaluate_in_rc",
"sfepy.discrete.common.dof_info.expand_nodes_to_dofs",
"sfepy.discrete.fem.global_interp.get_ref_coors",
"sfepy.base.base.output",
"sfepy.d... | [((2552, 2572), 'numpy.array', 'nm.array', (['facet_desc'], {}), '(facet_desc)\n', (2560, 2572), True, 'import numpy as nm\n'), ((2711, 2753), 'numpy.arange', 'nm.arange', (['facets.shape[0]'], {'dtype': 'nm.int32'}), '(facets.shape[0], dtype=nm.int32)\n', (2720, 2753), True, 'import numpy as nm\n'), ((2911, 2948), 'sfepy.discrete.fem.utils.prepare_remap', 'prepare_remap', (['facets', 'cmesh.num[dim]'], {}), '(facets, cmesh.num[dim])\n', (2924, 2948), False, 'from sfepy.discrete.fem.utils import prepare_remap\n'), ((8295, 8365), 'sfepy.base.base.output', 'output', (["('evaluating in %d points...' % coors.shape[0])"], {'verbose': 'verbose'}), "('evaluating in %d points...' % coors.shape[0], verbose=verbose)\n", (8301, 8365), False, 'from sfepy.base.base import output, assert_\n'), ((8402, 8506), 'sfepy.discrete.fem.global_interp.get_ref_coors', 'get_ref_coors', (['self', 'coors'], {'strategy': 'strategy', 'close_limit': 'close_limit', 'cache': 'cache', 'verbose': 'verbose'}), '(self, coors, strategy=strategy, close_limit=close_limit,\n cache=cache, verbose=verbose)\n', (8415, 8506), False, 'from sfepy.discrete.fem.global_interp import get_ref_coors\n'), ((8713, 8725), 'time.clock', 'time.clock', ([], {}), '()\n', (8723, 8725), False, 'import time\n'), ((9114, 9146), 'numpy.array', 'nm.array', (['orders'], {'dtype': 'nm.int32'}), '(orders, dtype=nm.int32)\n', (9122, 9146), True, 'import numpy as nm\n'), ((9215, 9288), 'numpy.empty', 'nm.empty', (['(coors.shape[0], source_vals.shape[1])'], {'dtype': 'source_vals.dtype'}), '((coors.shape[0], source_vals.shape[1]), dtype=source_vals.dtype)\n', (9223, 9288), True, 'import numpy as nm\n'), ((9322, 9438), 'sfepy.discrete.fem.extmods.bases.evaluate_in_rc', 'evaluate_in_rc', (['vals', 'ref_coors', 'cells', 'status', 'source_vals', 'conns', 'vertex_coorss', 'nodess', 'orders', 'mtx_is', '(1e-15)'], {}), '(vals, ref_coors, cells, status, source_vals, conns,\n vertex_coorss, nodess, orders, mtx_is, 1e-15)\n', (9336, 9438), False, 'from sfepy.discrete.fem.extmods.bases import evaluate_in_rc\n'), ((9564, 9598), 'sfepy.base.base.output', 'output', (['"""...done"""'], {'verbose': 'verbose'}), "('...done', verbose=verbose)\n", (9570, 9598), False, 'from sfepy.base.base import output, assert_\n'), ((17089, 17120), 'sfepy.discrete.fem.fields_base.FEField.extend_dofs', 'FEField.extend_dofs', (['self', 'dofs'], {}), '(self, dofs)\n', (17108, 17120), False, 'from sfepy.discrete.fem.fields_base import FEField, VolumeField, SurfaceField, H1Mixin\n'), ((17378, 17415), 'sfepy.discrete.fem.fields_base.FEField.remove_extra_dofs', 'FEField.remove_extra_dofs', (['self', 'dofs'], {}), '(self, dofs)\n', (17403, 17415), False, 'from sfepy.discrete.fem.fields_base import FEField, VolumeField, SurfaceField, H1Mixin\n'), ((1183, 1232), 'sfepy.discrete.fem.facets.get_facet_dof_permutations', 'get_facet_dof_permutations', (['n_fp', 'self.igs', 'order'], {}), '(n_fp, self.igs, order)\n', (1209, 1232), False, 'from sfepy.discrete.fem.facets import get_facet_dof_permutations\n'), ((1454, 1503), 'sfepy.discrete.fem.facets.get_facet_dof_permutations', 'get_facet_dof_permutations', (['n_fp', 'self.igs', 'order'], {}), '(n_fp, self.igs, order)\n', (1480, 1503), False, 'from sfepy.discrete.fem.facets import get_facet_dof_permutations\n'), ((2782, 2823), 'sfepy.discrete.common.dof_info.expand_nodes_to_dofs', 'expand_nodes_to_dofs', (['ii', 'n_dof_per_facet'], {}), '(ii, n_dof_per_facet)\n', (2802, 2823), False, 'from sfepy.discrete.common.dof_info import expand_nodes_to_dofs\n'), ((3984, 4025), 'numpy.arange', 'nm.arange', (['gdofs.shape[0]'], {'dtype': 'nm.int32'}), '(gdofs.shape[0], dtype=nm.int32)\n', (3993, 4025), True, 'import numpy as nm\n'), ((4827, 4862), 'sfepy.discrete.fem.utils.prepare_remap', 'prepare_remap', (['ii', 'group.shape.n_el'], {}), '(ii, group.shape.n_el)\n', (4840, 4862), False, 'from sfepy.discrete.fem.utils import prepare_remap\n'), ((4882, 4944), 'numpy.arange', 'nm.arange', (['(offset + n_dof)', '(offset + n_dof + nd)'], {'dtype': 'nm.int32'}), '(offset + n_dof, offset + n_dof + nd, dtype=nm.int32)\n', (4891, 4944), True, 'import numpy as nm\n'), ((5615, 5629), 'numpy.hstack', 'nm.hstack', (['aux'], {}), '(aux)\n', (5624, 5629), True, 'import numpy as nm\n'), ((5716, 5732), 'numpy.isscalar', 'nm.isscalar', (['fun'], {}), '(fun)\n', (5727, 5732), True, 'import numpy as nm\n'), ((10327, 10372), 'numpy.zeros', 'nm.zeros', (['(self.n_nod, dim)'], {'dtype': 'nm.float64'}), '((self.n_nod, dim), dtype=nm.float64)\n', (10335, 10372), True, 'import numpy as nm\n'), ((14557, 14609), 'numpy.tensordot', 'nm.tensordot', (['self.bfref', 'maps.inv_jac'], {'axes': '(-1, 0)'}), '(self.bfref, maps.inv_jac, axes=(-1, 0))\n', (14569, 14609), True, 'import numpy as nm\n'), ((15668, 15734), 'fea.DiscontinuousApproximation', 'fea.DiscontinuousApproximation', (['name', 'self.interp', 'self.region', 'ig'], {}), '(name, self.interp, self.region, ig)\n', (15698, 15734), False, 'import fea\n'), ((16227, 16250), 'numpy.prod', 'nm.prod', (['ap.econn.shape'], {}), '(ap.econn.shape)\n', (16234, 16250), True, 'import numpy as nm\n'), ((16320, 16355), 'sfepy.discrete.fem.utils.prepare_remap', 'prepare_remap', (['ii', 'group.shape.n_el'], {}), '(ii, group.shape.n_el)\n', (16333, 16355), False, 'from sfepy.discrete.fem.utils import prepare_remap\n'), ((16375, 16419), 'numpy.arange', 'nm.arange', (['n_dof', '(n_dof + nd)'], {'dtype': 'nm.int32'}), '(n_dof, n_dof + nd, dtype=nm.int32)\n', (16384, 16419), True, 'import numpy as nm\n'), ((3612, 3666), 'sfepy.discrete.common.dof_info.expand_nodes_to_dofs', 'expand_nodes_to_dofs', (['facets_of_cells', 'n_dof_per_facet'], {}), '(facets_of_cells, n_dof_per_facet)\n', (3632, 3666), False, 'from sfepy.discrete.common.dof_info import expand_nodes_to_dofs\n'), ((3840, 3870), 'numpy.arange', 'nm.arange', (['n_f'], {'dtype': 'nm.int32'}), '(n_f, dtype=nm.int32)\n', (3849, 3870), True, 'import numpy as nm\n'), ((4172, 4195), 'numpy.prod', 'nm.prod', (['all_dofs.shape'], {}), '(all_dofs.shape)\n', (4179, 4195), True, 'import numpy as nm\n'), ((5753, 5790), 'numpy.repeat', 'nm.repeat', (['[fun]', '(nods.shape[0] * dpn)'], {}), '([fun], nods.shape[0] * dpn)\n', (5762, 5790), True, 'import numpy as nm\n'), ((10737, 10764), 'numpy.dot', 'nm.dot', (['bf', 'vec[group.conn]'], {}), '(bf, vec[group.conn])\n', (10743, 10764), True, 'import numpy as nm\n'), ((10803, 10826), 'numpy.swapaxes', 'nm.swapaxes', (['evec', '(0)', '(1)'], {}), '(evec, 0, 1)\n', (10814, 10826), True, 'import numpy as nm\n'), ((3770, 3801), 'numpy.arange', 'nm.arange', (['n_el'], {'dtype': 'nm.int32'}), '(n_el, dtype=nm.int32)\n', (3779, 3801), True, 'import numpy as nm\n'), ((5890, 5919), 'numpy.repeat', 'nm.repeat', (['fun', 'nods.shape[0]'], {}), '(fun, nods.shape[0])\n', (5899, 5919), True, 'import numpy as nm\n'), ((9521, 9533), 'time.clock', 'time.clock', ([], {}), '()\n', (9531, 9533), False, 'import time\n'), ((12453, 12483), 'numpy.array', 'nm.array', (['(bfref0.shape + shape)'], {}), '(bfref0.shape + shape)\n', (12461, 12483), True, 'import numpy as nm\n'), ((12549, 12568), 'numpy.zeros', 'nm.zeros', (['vec_shape'], {}), '(vec_shape)\n', (12557, 12568), True, 'import numpy as nm\n'), ((12595, 12614), 'numpy.arange', 'nm.arange', (['shape[0]'], {}), '(shape[0])\n', (12604, 12614), True, 'import numpy as nm\n'), ((13236, 13258), 'numpy.array', 'nm.array', (['bfref0.shape'], {}), '(bfref0.shape)\n', (13244, 13258), True, 'import numpy as nm\n'), ((13326, 13345), 'numpy.zeros', 'nm.zeros', (['vec_shape'], {}), '(vec_shape)\n', (13334, 13345), True, 'import numpy as nm\n'), ((13372, 13391), 'numpy.arange', 'nm.arange', (['shape[0]'], {}), '(shape[0])\n', (13381, 13391), True, 'import numpy as nm\n'), ((14767, 14819), 'numpy.tensordot', 'nm.tensordot', (['self.bfref', 'maps.inv_jac'], {'axes': '(-1, 0)'}), '(self.bfref, maps.inv_jac, axes=(-1, 0))\n', (14779, 14819), True, 'import numpy as nm\n'), ((14852, 14874), 'numpy.einsum', 'nm.einsum', (['"""ijkk"""', 'val'], {}), "('ijkk', val)\n", (14861, 14874), True, 'import numpy as nm\n'), ((14975, 15027), 'numpy.tensordot', 'nm.tensordot', (['self.bfref', 'maps.inv_jac'], {'axes': '(-1, 0)'}), '(self.bfref, maps.inv_jac, axes=(-1, 0))\n', (14987, 15027), True, 'import numpy as nm\n'), ((15112, 15154), 'sfepy.terms.terms_general.proceed_methods', 'proceed_methods', (['val', 'self.eval_method[1:]'], {}), '(val, self.eval_method[1:])\n', (15127, 15154), False, 'from sfepy.terms.terms_general import proceed_methods\n')] |
#!/usr/bin/env python
import sys
sys.path.append('.')
from optparse import OptionParser
from sfepy.base.base import nm, output
from sfepy.fem import Mesh
from sfepy.fem.meshio import io_table, supported_capabilities
usage = """%prog [options] filename_in filename_out
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
"""
help = {
'scale' : 'scale factor [default: %default]',
'format' : 'output mesh format (overrides filename_out extension)',
'list' : 'list supported writable output mesh formats',
}
def output_writable_meshes():
output('Supported writable mesh formats are:')
for key, val in supported_capabilities.iteritems():
if 'w' in val:
output(key)
def main():
parser = OptionParser(usage=usage)
parser.add_option("-s", "--scale", metavar='scale',
action="store", dest="scale",
default=None, help=help['scale'])
parser.add_option("-f", "--format", metavar='format',
action="store", type='string', dest="format",
default=None, help=help['format'])
parser.add_option("-l", "--list", action="store_true",
dest="list", help=help['list'])
(options, args) = parser.parse_args()
if options.list:
output_writable_meshes()
sys.exit(0)
if len(args) != 2:
parser.print_help()
sys.exit(1)
scale = options.scale
if scale is not None:
try:
try:
scale = float(scale)
except ValueError:
scale = [float(ii) for ii in scale.split(',')]
scale = nm.array(scale, dtype=nm.float64, ndmin=1)
except:
output('bad scale! (%s)' % scale)
parser.print_help()
sys.exit(1)
filename_in, filename_out = args
mesh = Mesh.from_file(filename_in)
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)
io = 'auto'
if options.format:
try:
io = io_table[options.format](filename_out)
except KeyError:
output('unknown output mesh format! (%s)' % options.format)
output_writable_meshes()
sys.exit(1)
if 'w' not in supported_capabilities[options.format]:
output('write support not implemented for output mesh format! (%s)'
% options.format)
output_writable_meshes()
sys.exit(1)
output('writing %s...' % filename_out)
mesh.write(filename_out, io=io)
output('...done')
if __name__ == '__main__':
main()
| [
"sfepy.base.base.output",
"sfepy.base.base.nm.array",
"sfepy.base.base.nm.diag",
"sfepy.fem.meshio.supported_capabilities.iteritems",
"sfepy.base.base.nm.eye",
"sfepy.fem.Mesh.from_file"
] | [((33, 53), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (48, 53), False, 'import sys\n'), ((773, 819), 'sfepy.base.base.output', 'output', (['"""Supported writable mesh formats are:"""'], {}), "('Supported writable mesh formats are:')\n", (779, 819), False, 'from sfepy.base.base import nm, output\n'), ((840, 874), 'sfepy.fem.meshio.supported_capabilities.iteritems', 'supported_capabilities.iteritems', ([], {}), '()\n', (872, 874), False, 'from sfepy.fem.meshio import io_table, supported_capabilities\n'), ((949, 974), 'optparse.OptionParser', 'OptionParser', ([], {'usage': 'usage'}), '(usage=usage)\n', (961, 974), False, 'from optparse import OptionParser\n'), ((2086, 2113), 'sfepy.fem.Mesh.from_file', 'Mesh.from_file', (['filename_in'], {}), '(filename_in)\n', (2100, 2113), False, 'from sfepy.fem import Mesh\n'), ((2927, 2965), 'sfepy.base.base.output', 'output', (["('writing %s...' % filename_out)"], {}), "('writing %s...' % filename_out)\n", (2933, 2965), False, 'from sfepy.base.base import nm, output\n'), ((3006, 3023), 'sfepy.base.base.output', 'output', (['"""...done"""'], {}), "('...done')\n", (3012, 3023), False, 'from sfepy.base.base import nm, output\n'), ((1541, 1552), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (1549, 1552), False, 'import sys\n'), ((1613, 1624), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1621, 1624), False, 'import sys\n'), ((911, 922), 'sfepy.base.base.output', 'output', (['key'], {}), '(key)\n', (917, 922), False, 'from sfepy.base.base import nm, output\n'), ((1863, 1905), 'sfepy.base.base.nm.array', 'nm.array', (['scale'], {'dtype': 'nm.float64', 'ndmin': '(1)'}), '(scale, dtype=nm.float64, ndmin=1)\n', (1871, 1905), False, 'from sfepy.base.base import nm, output\n'), ((2755, 2844), 'sfepy.base.base.output', 'output', (["('write support not implemented for output mesh format! (%s)' % options.format)"], {}), "('write support not implemented for output mesh format! (%s)' %\n options.format)\n", (2761, 2844), False, 'from sfepy.base.base import nm, output\n'), ((2910, 2921), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2918, 2921), False, 'import sys\n'), ((1934, 1967), 'sfepy.base.base.output', 'output', (["('bad scale! (%s)' % scale)"], {}), "('bad scale! (%s)' % scale)\n", (1940, 1967), False, 'from sfepy.base.base import nm, output\n'), ((2012, 2023), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2020, 2023), False, 'import sys\n'), ((2186, 2220), 'sfepy.base.base.nm.eye', 'nm.eye', (['mesh.dim'], {'dtype': 'nm.float64'}), '(mesh.dim, dtype=nm.float64)\n', (2192, 2220), False, 'from sfepy.base.base import nm, output\n'), ((2283, 2297), 'sfepy.base.base.nm.diag', 'nm.diag', (['scale'], {}), '(scale)\n', (2290, 2297), False, 'from sfepy.base.base import nm, output\n'), ((2547, 2606), 'sfepy.base.base.output', 'output', (["('unknown output mesh format! (%s)' % options.format)"], {}), "('unknown output mesh format! (%s)' % options.format)\n", (2553, 2606), False, 'from sfepy.base.base import nm, output\n'), ((2656, 2667), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2664, 2667), False, 'import sys\n')] |
#!/usr/bin/env python
# This code was adapted from http://sfepy.org/doc-devel/mat_optim.html.
"""
Compare various elastic materials w.r.t. uniaxial tension/compression test.
Requires Matplotlib.
"""
from __future__ import absolute_import
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import sys
import six
sys.path.append('.')
from sfepy.base.base import output
from sfepy.base.conf import ProblemConf, get_standard_keywords
from sfepy.discrete import Problem
from sfepy.base.plotutils import plt
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import numpy as np
from functools import partial
def define( K=8.333, mu_nh=3.846, mu_mr=1.923, kappa=1.923, lam=5.769, mu=3.846 ):
"""Define the problem to solve."""
from sfepy.discrete.fem.meshio import UserMeshIO
from sfepy.mesh.mesh_generators import gen_block_mesh
from sfepy.mechanics.matcoefs import stiffness_from_lame
def mesh_hook(mesh, mode):
"""
Generate the block mesh.
"""
if mode == 'read':
mesh = gen_block_mesh([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3',
verbose=False)
return mesh
elif mode == 'write':
pass
filename_mesh = UserMeshIO(mesh_hook)
options = {
'nls' : 'newton',
'ls' : 'ls',
'ts' : 'ts',
'save_times' : 'all',
}
functions = {
'linear_pressure' : (linear_pressure,),
'empty' : (lambda ts, coor, mode, region, ig: None,),
}
fields = {
'displacement' : ('real', 3, 'Omega', 1),
}
# Coefficients are chosen so that the tangent stiffness is the same for all
# material for zero strains.
materials = {
'solid' : ({
'K' : K, # bulk modulus
'mu_nh' : mu_nh, # shear modulus of neoHookean term
'mu_mr' : mu_mr, # shear modulus of Mooney-Rivlin term
'kappa' : kappa, # second modulus of Mooney-Rivlin term
# elasticity for LE term
'D' : stiffness_from_lame(dim=3, lam=lam, mu=mu),
},),
'load' : 'empty',
}
variables = {
'u' : ('unknown field', 'displacement', 0),
'v' : ('test field', 'displacement', 'u'),
}
regions = {
'Omega' : 'all',
'Bottom' : ('vertices in (z < 0.1)', 'facet'),
'Top' : ('vertices in (z > 2.9)', 'facet'),
}
ebcs = {
'fixb' : ('Bottom', {'u.all' : 0.0}),
'fixt' : ('Top', {'u.[0,1]' : 0.0}),
}
integrals = {
'i' : 1,
'isurf' : 2,
}
equations = {
'linear' : """dw_lin_elastic.i.Omega(solid.D, v, u)
= dw_surface_ltr.isurf.Top(load.val, v)""",
'neo-Hookean' : """dw_tl_he_neohook.i.Omega(solid.mu_nh, v, u)
+ dw_tl_bulk_penalty.i.Omega(solid.K, v, u)
= dw_surface_ltr.isurf.Top(load.val, v)""",
'Mooney-Rivlin' : """dw_tl_he_neohook.i.Omega(solid.mu_mr, v, u)
+ dw_tl_he_mooney_rivlin.i.Omega(solid.kappa, v, u)
+ dw_tl_bulk_penalty.i.Omega(solid.K, v, u)
= dw_surface_ltr.isurf.Top(load.val, v)""",
}
solvers = {
'ls' : ('ls.scipy_direct', {}),
'newton' : ('nls.newton', {
'i_max' : 5,
'eps_a' : 1e-10,
'eps_r' : 1.0,
}),
'ts' : ('ts.simple', {
't0' : 0,
't1' : 1,
'dt' : None,
'n_step' : 26, # has precedence over dt!
'verbose' : 1,
}),
}
return locals()
##
# Pressure tractions.
def linear_pressure(ts, coor, mode=None, coef=1, **kwargs):
if mode == 'qp':
val = np.tile(coef * ts.step, (coor.shape[0], 1, 1))
return {'val' : val}
def store_top_u(displacements):
"""Function _store() will be called at the end of each loading step. Top
displacements will be stored into `displacements`."""
def _store(problem, ts, state):
top = problem.domain.regions['Top']
top_u = problem.get_variables()['u'].get_state_in_region(top)
displacements.append(np.mean(top_u[:,-1]))
return _store
def solve_branch(problem, branch_function, material_type):
eq = problem.conf.equations[material_type]
problem.set_equations({material_type : eq})
load = problem.get_materials()['load']
load.set_function(branch_function)
out = []
problem.solve(save_results=False, step_hook=store_top_u(out))
displacements = np.array(out, dtype=np.float64)
return displacements
helps = {
'no_plot' : 'do not show plot window',
}
def plot_mesh(pb):
# plot mesh for macro problem
coors = pb.domain.mesh.coors
graph = pb.domain.mesh.get_conn(pb.domain.mesh.descs[0])
fig2 = plt.figure(figsize=(5,6))
ax = fig2.add_subplot(111, projection='3d')
for e in range(graph.shape[0]):
tupleList = coors[graph[e,:],:]
vertices = [[0, 1, 2, 3], [4, 5, 6, 7],
[0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]
verts = [[tupleList[vertices[ix][iy]] for iy in range(len(vertices[0]))]
for ix in range(len(vertices))]
pc3d = Poly3DCollection(verts=verts, facecolors='white',
edgecolors='black', linewidths=1, alpha=0.5)
ax.add_collection3d(pc3d)
ax.set_xlim3d(-1.2, 1.2)
ax.set_ylim3d(-1.2, 1.2)
ax.set_zlim3d(-0.01, 3.2)
ax.set_title('3D plot of macro system')
plt.show(fig2)
return None
def one_simulation(material_type, define_args, coef_tension=0.25, coef_compression=-0.25,
plot_mesh_bool=False, return_load=False):
#parser = ArgumentParser(description=__doc__,
# formatter_class=RawDescriptionHelpFormatter)
#parser.add_argument('--version', action='version', version='%(prog)s')
#options = parser.parse_args()
output.set_output(filename='sfepy_log.txt', quiet=True)
required, other = get_standard_keywords()
# Use this file as the input file.
conf = ProblemConf.from_file(__file__, required, other,
define_args=define_args)
# Create problem instance, but do not set equations.
problem = Problem.from_conf(conf, init_equations=False)
if plot_mesh_bool:
plot_mesh(problem)
# Solve the problem. Output is ignored, results stored by using the
# step_hook.
linear_tension = partial(linear_pressure, coef=coef_tension)
u_t = solve_branch(problem, linear_tension, material_type)
linear_compression = partial(linear_pressure, coef=coef_compression)
u_c = solve_branch(problem, linear_compression, material_type)
# Get pressure load by calling linear_*() for each time step.
ts = problem.get_timestepper()
load_t = np.array([linear_tension(ts, np.array([[0.0]]), 'qp')['val']
for aux in ts.iter_from(0)],
dtype=np.float64).squeeze()
load_c = np.array([linear_compression(ts, np.array([[0.0]]), 'qp')['val']
for aux in ts.iter_from(0)],
dtype=np.float64).squeeze()
# Join the branches.
displacements = np.r_[u_c[::-1], u_t]
load = np.r_[load_c[::-1], load_t]
if return_load:
return displacements, load
else:
return displacements
def one_simulation_linear(theta, plot_mesh_bool=False, return_load=False):
material_type = 'linear'
theta = np.array(theta).reshape((-1, ))
define_args = {'lam':theta[0], 'mu':theta[1]} # bulk modulus
return one_simulation(material_type=material_type, plot_mesh_bool=plot_mesh_bool,
define_args=define_args, return_load=return_load)
def one_simulation_neo_hookean(theta, plot_mesh_bool=False, return_load=False):
material_type = 'neo-Hookean'
theta = np.array(theta).reshape((-1, ))
define_args = {'mu_nh':theta[0]} # bulk modulus
return one_simulation(material_type=material_type, plot_mesh_bool=plot_mesh_bool,
define_args=define_args, return_load=return_load)
def one_simulation_mooney_rivlin(theta, plot_mesh_bool=False, return_load=False):
material_type = 'Mooney-Rivlin'
theta = np.array(theta).reshape((-1, ))
define_args = {'mu_mr':theta[0], 'kappa':theta[1]} # bulk modulus
return one_simulation(material_type=material_type, plot_mesh_bool=plot_mesh_bool,
define_args=define_args, return_load=return_load)
def one_simulation_linear_v2(theta, plot_mesh_bool=False, return_load=False):
material_type = 'linear'
theta = np.array(theta).reshape((-1, ))
define_args = {'lam':theta[0], 'mu':theta[1]} # bulk modulus
return one_simulation(material_type=material_type, plot_mesh_bool=plot_mesh_bool,
define_args=define_args, return_load=return_load, coef_tension=0.15/5)
def one_simulation_neo_hookean_v2(theta, plot_mesh_bool=False, return_load=False):
material_type = 'neo-Hookean'
theta = np.array(theta).reshape((-1, ))
define_args = {'mu_nh':theta[0]} # bulk modulus
return one_simulation(material_type=material_type, plot_mesh_bool=plot_mesh_bool,
define_args=define_args, return_load=return_load, coef_tension=0.15/5)
def one_simulation_mooney_rivlin_v2(theta, plot_mesh_bool=False, return_load=False):
material_type = 'Mooney-Rivlin'
theta = np.array(theta).reshape((-1, ))
define_args = {'mu_mr':theta[0], 'kappa':theta[1]} # bulk modulus
return one_simulation(material_type=material_type, plot_mesh_bool=plot_mesh_bool,
define_args=define_args, return_load=return_load, coef_tension=0.15/5)
| [
"sfepy.base.conf.get_standard_keywords",
"sfepy.base.base.output.set_output",
"sfepy.discrete.Problem.from_conf",
"sfepy.base.conf.ProblemConf.from_file",
"sfepy.discrete.fem.meshio.UserMeshIO",
"sfepy.mesh.mesh_generators.gen_block_mesh",
"sfepy.base.plotutils.plt.show",
"sfepy.mechanics.matcoefs.sti... | [((327, 347), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (342, 347), False, 'import sys\n'), ((1326, 1347), 'sfepy.discrete.fem.meshio.UserMeshIO', 'UserMeshIO', (['mesh_hook'], {}), '(mesh_hook)\n', (1336, 1347), False, 'from sfepy.discrete.fem.meshio import UserMeshIO\n'), ((4671, 4702), 'numpy.array', 'np.array', (['out'], {'dtype': 'np.float64'}), '(out, dtype=np.float64)\n', (4679, 4702), True, 'import numpy as np\n'), ((4960, 4986), 'sfepy.base.plotutils.plt.figure', 'plt.figure', ([], {'figsize': '(5, 6)'}), '(figsize=(5, 6))\n', (4970, 4986), False, 'from sfepy.base.plotutils import plt\n'), ((5706, 5720), 'sfepy.base.plotutils.plt.show', 'plt.show', (['fig2'], {}), '(fig2)\n', (5714, 5720), False, 'from sfepy.base.plotutils import plt\n'), ((6123, 6178), 'sfepy.base.base.output.set_output', 'output.set_output', ([], {'filename': '"""sfepy_log.txt"""', 'quiet': '(True)'}), "(filename='sfepy_log.txt', quiet=True)\n", (6140, 6178), False, 'from sfepy.base.base import output\n'), ((6202, 6225), 'sfepy.base.conf.get_standard_keywords', 'get_standard_keywords', ([], {}), '()\n', (6223, 6225), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((6276, 6349), 'sfepy.base.conf.ProblemConf.from_file', 'ProblemConf.from_file', (['__file__', 'required', 'other'], {'define_args': 'define_args'}), '(__file__, required, other, define_args=define_args)\n', (6297, 6349), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((6431, 6476), 'sfepy.discrete.Problem.from_conf', 'Problem.from_conf', (['conf'], {'init_equations': '(False)'}), '(conf, init_equations=False)\n', (6448, 6476), False, 'from sfepy.discrete import Problem\n'), ((6638, 6681), 'functools.partial', 'partial', (['linear_pressure'], {'coef': 'coef_tension'}), '(linear_pressure, coef=coef_tension)\n', (6645, 6681), False, 'from functools import partial\n'), ((6770, 6817), 'functools.partial', 'partial', (['linear_pressure'], {'coef': 'coef_compression'}), '(linear_pressure, coef=coef_compression)\n', (6777, 6817), False, 'from functools import partial\n'), ((3867, 3913), 'numpy.tile', 'np.tile', (['(coef * ts.step)', '(coor.shape[0], 1, 1)'], {}), '(coef * ts.step, (coor.shape[0], 1, 1))\n', (3874, 3913), True, 'import numpy as np\n'), ((5400, 5498), 'mpl_toolkits.mplot3d.art3d.Poly3DCollection', 'Poly3DCollection', ([], {'verts': 'verts', 'facecolors': '"""white"""', 'edgecolors': '"""black"""', 'linewidths': '(1)', 'alpha': '(0.5)'}), "(verts=verts, facecolors='white', edgecolors='black',\n linewidths=1, alpha=0.5)\n", (5416, 5498), False, 'from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection\n'), ((1122, 1198), 'sfepy.mesh.mesh_generators.gen_block_mesh', 'gen_block_mesh', (['[2, 2, 3]', '[2, 2, 4]', '[0, 0, 1.5]'], {'name': '"""el3"""', 'verbose': '(False)'}), "([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3', verbose=False)\n", (1136, 1198), False, 'from sfepy.mesh.mesh_generators import gen_block_mesh\n'), ((4291, 4312), 'numpy.mean', 'np.mean', (['top_u[:, -1]'], {}), '(top_u[:, -1])\n', (4298, 4312), True, 'import numpy as np\n'), ((7652, 7667), 'numpy.array', 'np.array', (['theta'], {}), '(theta)\n', (7660, 7667), True, 'import numpy as np\n'), ((8020, 8035), 'numpy.array', 'np.array', (['theta'], {}), '(theta)\n', (8028, 8035), True, 'import numpy as np\n'), ((8379, 8394), 'numpy.array', 'np.array', (['theta'], {}), '(theta)\n', (8387, 8394), True, 'import numpy as np\n'), ((8745, 8760), 'numpy.array', 'np.array', (['theta'], {}), '(theta)\n', (8753, 8760), True, 'import numpy as np\n'), ((9137, 9152), 'numpy.array', 'np.array', (['theta'], {}), '(theta)\n', (9145, 9152), True, 'import numpy as np\n'), ((9520, 9535), 'numpy.array', 'np.array', (['theta'], {}), '(theta)\n', (9528, 9535), True, 'import numpy as np\n'), ((2120, 2162), 'sfepy.mechanics.matcoefs.stiffness_from_lame', 'stiffness_from_lame', ([], {'dim': '(3)', 'lam': 'lam', 'mu': 'mu'}), '(dim=3, lam=lam, mu=mu)\n', (2139, 2162), False, 'from sfepy.mechanics.matcoefs import stiffness_from_lame\n'), ((7029, 7046), 'numpy.array', 'np.array', (['[[0.0]]'], {}), '([[0.0]])\n', (7037, 7046), True, 'import numpy as np\n'), ((7204, 7221), 'numpy.array', 'np.array', (['[[0.0]]'], {}), '([[0.0]])\n', (7212, 7221), True, 'import numpy as np\n')] |
import numpy as nm
from sfepy.base.base import output, get_default, assert_, Struct
def get_print_info(n_step):
if n_step > 1:
n_digit = int(nm.log10(n_step - 1) + 1)
else:
n_digit = 1
format = '%%%dd of %%%dd' % (n_digit, n_digit)
suffix = '%%0%dd' % n_digit
return n_digit, format, suffix
class TimeStepper(Struct):
"""
Time stepper class.
"""
@staticmethod
def from_conf(conf):
return TimeStepper(conf.t0, conf.t1, dt=conf.dt, n_step=conf.n_step,
is_quasistatic=conf.quasistatic)
def __init__(self, t0, t1, dt=None, n_step=None, step=None,
is_quasistatic=False):
self.set_from_data(t0, t1, dt=dt, n_step=n_step, step=step)
self.is_quasistatic = is_quasistatic
self.step_start_time = None
def _get_n_step(self, t0, t1, dt):
n_step = int(round(nm.floor(((t1 - t0) / dt) + 0.5) + 1.0))
return n_step
def set_from_data(self, t0, t1, dt=None, n_step=None, step=None):
self.t0, self.t1 = t0, t1
dt = get_default(dt, t1 - t0)
self.n_step = get_default(n_step,
self._get_n_step(self.t0, self.t1, dt))
if self.n_step > 1:
self.times, self.dt = nm.linspace(self.t0, self.t1, self.n_step,
endpoint=True, retstep=True)
else:
self.times = nm.array((self.t0,), dtype=nm.float64)
self.dt = self.t1 - self.t0
self.n_digit, self.format, self.suffix = get_print_info(self.n_step)
self.set_step(step)
def set_from_ts(self, ts, step=None):
step = get_default(step, ts.step)
self.set_from_data(ts.t0, ts.t1, ts.dt, ts.n_step, step=step)
def get_state(self):
return {'step' : self.step}
def set_state(self, step=0, **kwargs):
self.set_step(step=step)
def set_substep_time(self, sub_dt):
self.step_start_time = self.time
self.time += sub_dt
def restore_step_time(self):
if self.step_start_time is not None:
self.time = self.step_start_time
self.step_start_time = None
def advance(self):
if self.step < (self.n_step - 1):
self.step += 1
self.time = self.times[self.step]
self.normalize_time()
def __iter__(self):
"""ts.step, ts.time is consistent with step, time returned here
ts.nt is normalized time in [0, 1]"""
return self.iter_from(0)
def iter_from(self, step):
self.set_step(step=step)
for time in self.times[step:]:
yield self.step, self.time
self.advance()
def normalize_time(self):
self.nt = (self.time - self.t0) / (self.t1 - self.t0)
def set_step(self, step=0, nt=0.0):
nm1 = self.n_step - 1
if step is None:
step = int(round(nt * nm1))
if step < 0:
step = self.n_step + step
if (step >= self.n_step) or (step < 0):
output('time step must be in [%d, %d]' % (-nm1, nm1) )
raise ValueError
self.step = step
self.time = self.times[step]
self.normalize_time()
def __eq__(self, other):
if type(other) == type(self):
return (abs(self.t0 == other.t0) < 1e-15) and \
(abs(self.t1 == other.t1) < 1e-15) and \
(self.n_step == other.n_step)
else:
raise ValueError
class VariableTimeStepper(TimeStepper):
"""
Time stepper class with a variable time step.
"""
@staticmethod
def from_conf(conf):
return VariableTimeStepper(conf.t0, conf.t1, dt=conf.dt,
n_step=conf.n_step,
is_quasistatic=conf.quasistatic)
def set_from_data(self, t0, t1, dt=None, n_step=None, step=None):
self.t0, self.t1 = t0, t1
self.dtime = self.t1 - self.t0
dt = get_default(dt, self.dtime)
self.n_step0 = get_default(n_step,
self._get_n_step(self.t0, self.t1, dt))
if self.n_step0 > 1:
self.dt = self.dtime / (self.n_step0 - 1)
else:
self.dt = self.dtime
self.dt0 = self.dt
self.n_digit, self.format, self.suffix = get_print_info(5)
self.set_step(step)
def set_from_ts(self, ts, step=None):
self.set_from_data(ts.t0, ts.t1, ts.dt, ts.n_step0, step=0)
def get_state(self):
return {'step' : self.step, 'dts' : self.dts, 'times' : self.times}
def set_state(self, step=0, dts=None, times=None, **kwargs):
assert_(len(dts) == len(times) == (step + 1))
self.step = step
self.dts = dts
self.times = times
self.dt = self.dts[-1]
self.time = self.times[-1]
self.normalize_time()
def set_n_digit_from_min_dt(self, dt):
n_step = self._get_n_step(self.t0, self.t1, dt)
self.n_digit, self.format, self.suffix = get_print_info(n_step)
def set_step(self, step=0, nt=0.0):
if step is None:
step = 0
if (step > 0) and (step != self.step):
msg = 'cannot set step != self.step or 0 in VariableTimeStepper!'
raise ValueError(msg)
if step == 0:
self.step = 0
self.time = self.t0
self.nt = 0.0
self.dts = [self.dt]
self.times = [self.time]
self.n_step = 1
def get_default_time_step(self):
return self.dt0
def set_time_step(self, dt, update_time=False):
self.dt = dt
if update_time:
self.time = self.times[self.step - 1] + self.dt
self.times[self.step] = self.time
self.normalize_time()
def advance(self):
self.step += 1
self.time += self.dt
self.normalize_time()
self.times.append(self.time)
self.dts.append(self.dt)
self.n_step = self.step + 1
def iter_from(self, step):
self.set_step(step=step)
return self.iter_from_current()
def iter_from_current(self):
"""
ts.step, ts.time is consistent with step, time returned here
ts.nt is normalized time in [0, 1].
"""
while 1:
yield self.step, self.time
if self.nt >= 1.0:
break
self.advance()
def __iter__(self):
self.set_step(0)
return self.iter_from_current()
| [
"sfepy.base.base.output",
"sfepy.base.base.get_default"
] | [((1084, 1108), 'sfepy.base.base.get_default', 'get_default', (['dt', '(t1 - t0)'], {}), '(dt, t1 - t0)\n', (1095, 1108), False, 'from sfepy.base.base import output, get_default, assert_, Struct\n'), ((1689, 1715), 'sfepy.base.base.get_default', 'get_default', (['step', 'ts.step'], {}), '(step, ts.step)\n', (1700, 1715), False, 'from sfepy.base.base import output, get_default, assert_, Struct\n'), ((4024, 4051), 'sfepy.base.base.get_default', 'get_default', (['dt', 'self.dtime'], {}), '(dt, self.dtime)\n', (4035, 4051), False, 'from sfepy.base.base import output, get_default, assert_, Struct\n'), ((1288, 1359), 'numpy.linspace', 'nm.linspace', (['self.t0', 'self.t1', 'self.n_step'], {'endpoint': '(True)', 'retstep': '(True)'}), '(self.t0, self.t1, self.n_step, endpoint=True, retstep=True)\n', (1299, 1359), True, 'import numpy as nm\n'), ((1445, 1483), 'numpy.array', 'nm.array', (['(self.t0,)'], {'dtype': 'nm.float64'}), '((self.t0,), dtype=nm.float64)\n', (1453, 1483), True, 'import numpy as nm\n'), ((3069, 3122), 'sfepy.base.base.output', 'output', (["('time step must be in [%d, %d]' % (-nm1, nm1))"], {}), "('time step must be in [%d, %d]' % (-nm1, nm1))\n", (3075, 3122), False, 'from sfepy.base.base import output, get_default, assert_, Struct\n'), ((155, 175), 'numpy.log10', 'nm.log10', (['(n_step - 1)'], {}), '(n_step - 1)\n', (163, 175), True, 'import numpy as nm\n'), ((902, 932), 'numpy.floor', 'nm.floor', (['((t1 - t0) / dt + 0.5)'], {}), '((t1 - t0) / dt + 0.5)\n', (910, 932), True, 'import numpy as nm\n')] |
r"""
Elastic contact sphere simulating an indentation test.
Find :math:`\ul{u}` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
+ \int_{\Gamma} \ul{v} \cdot f(d(\ul{u})) \ul{n}(\ul{u})
= 0 \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl} + \delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;.
Notes
-----
Even though the material is linear elastic and small deformations are used, the
problem is highly nonlinear due to contacts with the sphere. See also
elastic_contact_planes.py example.
"""
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/3d/cube_medium_hexa.mesh'
k = 1e5 # Elastic sphere stiffness for positive penetration.
f0 = 1e-2 # Force at zero penetration.
options = {
'nls' : 'newton',
'ls' : 'ls',
'output_format': 'vtk',
}
fields = {
'displacement': ('real', 3, 'Omega', 1),
}
materials = {
'solid' : ({
'lam' : 5.769,
'mu' : 3.846,
},),
'cs' : ({
'f' : [k, f0],
'.c' : [0.0, 0.0, 1.2],
'.r' : 0.8,
},),
}
variables = {
'u' : ('unknown field', 'displacement', 0),
'v' : ('test field', 'displacement', 'u'),
}
regions = {
'Omega' : 'all',
'Bottom' : ('vertices in (z < -0.499)', 'facet'),
'Top' : ('vertices in (z > 0.499)', 'facet'),
}
ebcs = {
'fixed' : ('Bottom', {'u.all' : 0.0}),
}
equations = {
'elasticity' :
"""dw_lin_elastic_iso.2.Omega(solid.lam, solid.mu, v, u)
+ dw_contact_sphere.2.Top(cs.f, cs.c, cs.r, v, u)
= 0""",
}
solvers = {
'ls' : ('ls.scipy_direct', {}),
'newton' : ('nls.newton', {
'i_max' : 20,
'eps_a' : 1e-1,
'ls_on' : 2.0,
'problem' : 'nonlinear',
'check' : 0,
'delta' : 1e-6,
}),
}
def main():
import os
import numpy as nm
import matplotlib.pyplot as plt
from sfepy.discrete.fem import MeshIO
import sfepy.linalg as la
from sfepy.mechanics.contact_bodies import ContactSphere, plot_points
conf_dir = os.path.dirname(__file__)
io = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir)
bb = io.read_bounding_box()
outline = [vv for vv in la.combine(zip(*bb))]
ax = plot_points(None, nm.array(outline), 'r*')
csc = materials['cs'][0]
cs = ContactSphere(csc['.c'], csc['.r'])
pps = (bb[1] - bb[0]) * nm.random.rand(5000, 3) + bb[0]
mask = cs.mask_points(pps, 0.0)
ax = plot_points(ax, cs.centre[None, :], 'b*', ms=30)
ax = plot_points(ax, pps[mask], 'kv')
ax = plot_points(ax, pps[~mask], 'r.')
plt.show()
if __name__ == '__main__':
main()
| [
"sfepy.discrete.fem.MeshIO.any_from_filename",
"sfepy.mechanics.contact_bodies.plot_points",
"sfepy.mechanics.contact_bodies.ContactSphere"
] | [((2053, 2078), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2068, 2078), False, 'import os\n'), ((2088, 2148), 'sfepy.discrete.fem.MeshIO.any_from_filename', 'MeshIO.any_from_filename', (['filename_mesh'], {'prefix_dir': 'conf_dir'}), '(filename_mesh, prefix_dir=conf_dir)\n', (2112, 2148), False, 'from sfepy.discrete.fem import MeshIO\n'), ((2322, 2357), 'sfepy.mechanics.contact_bodies.ContactSphere', 'ContactSphere', (["csc['.c']", "csc['.r']"], {}), "(csc['.c'], csc['.r'])\n", (2335, 2357), False, 'from sfepy.mechanics.contact_bodies import ContactSphere, plot_points\n'), ((2465, 2513), 'sfepy.mechanics.contact_bodies.plot_points', 'plot_points', (['ax', 'cs.centre[None, :]', '"""b*"""'], {'ms': '(30)'}), "(ax, cs.centre[None, :], 'b*', ms=30)\n", (2476, 2513), False, 'from sfepy.mechanics.contact_bodies import ContactSphere, plot_points\n'), ((2523, 2555), 'sfepy.mechanics.contact_bodies.plot_points', 'plot_points', (['ax', 'pps[mask]', '"""kv"""'], {}), "(ax, pps[mask], 'kv')\n", (2534, 2555), False, 'from sfepy.mechanics.contact_bodies import ContactSphere, plot_points\n'), ((2565, 2598), 'sfepy.mechanics.contact_bodies.plot_points', 'plot_points', (['ax', 'pps[~mask]', '"""r."""'], {}), "(ax, pps[~mask], 'r.')\n", (2576, 2598), False, 'from sfepy.mechanics.contact_bodies import ContactSphere, plot_points\n'), ((2604, 2614), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2612, 2614), True, 'import matplotlib.pyplot as plt\n'), ((2259, 2276), 'numpy.array', 'nm.array', (['outline'], {}), '(outline)\n', (2267, 2276), True, 'import numpy as nm\n'), ((2387, 2410), 'numpy.random.rand', 'nm.random.rand', (['(5000)', '(3)'], {}), '(5000, 3)\n', (2401, 2410), True, 'import numpy as nm\n')] |
"""
Global interpolation functions.
"""
import time
import numpy as nm
from sfepy.base.base import output, get_default_attr
from sfepy.discrete.fem.mesh import make_inverse_connectivity
from sfepy.discrete.fem.extmods.bases import find_ref_coors
def get_ref_coors(field, coors, strategy='kdtree', close_limit=0.1, cache=None,
verbose=True):
"""
Get reference element coordinates and elements corresponding to given
physical coordinates.
Parameters
----------
field : Field instance
The field defining the approximation.
coors : array
The physical coordinates.
strategy : str, optional
The strategy for finding the elements that contain the
coordinates. Only 'kdtree' is supported for the moment.
close_limit : float, optional
The maximum limit distance of a point from the closest
element allowed for extrapolation.
cache : Struct, optional
To speed up a sequence of evaluations, the field mesh, the inverse
connectivity of the field mesh and the KDTree instance can be cached as
`cache.mesh`, `cache.offsets`, `cache.iconn` and
`cache.kdtree`. Optionally, the cache can also contain the reference
element coordinates as `cache.ref_coors`, `cache.cells` and
`cache.status`, if the evaluation occurs in the same coordinates
repeatedly. In that case the KDTree related data are ignored.
verbose : bool
If False, reduce verbosity.
Returns
-------
ref_coors : array
The reference coordinates.
cells : array
The cell indices corresponding to the reference coordinates.
status : array
The status: 0 is success, 1 is extrapolation within `close_limit`, 2 is
extrapolation outside `close_limit`, 3 is failure.
"""
ref_coors = get_default_attr(cache, 'ref_coors', None)
if ref_coors is None:
mesh = get_default_attr(cache, 'mesh', None)
if mesh is None:
mesh = field.create_mesh(extra_nodes=False)
scoors = mesh.coors
output('reference field: %d vertices' % scoors.shape[0],
verbose=verbose)
iconn = get_default_attr(cache, 'iconn', None)
if iconn is None:
offsets, iconn = make_inverse_connectivity(mesh.conns,
mesh.n_nod,
ret_offsets=True)
ii = nm.where(offsets[1:] == offsets[:-1])[0]
if len(ii):
raise ValueError('some vertices not in any element! (%s)'
% ii)
else:
offsets = cache.offsets
if strategy == 'kdtree':
kdtree = get_default_attr(cache, 'kdtree', None)
if kdtree is None:
from scipy.spatial import cKDTree as KDTree
tt = time.clock()
kdtree = KDTree(scoors)
output('kdtree: %f s' % (time.clock()-tt), verbose=verbose)
tt = time.clock()
ics = kdtree.query(coors)[1]
output('kdtree query: %f s' % (time.clock()-tt), verbose=verbose)
tt = time.clock()
ics = nm.asarray(ics, dtype=nm.int32)
vertex_coorss, nodess, mtx_is = [], [], []
conns = []
for ig, ap in field.aps.iteritems():
ps = ap.interp.gel.interp.poly_spaces['v']
vertex_coorss.append(ps.geometry.coors)
nodess.append(ps.nodes)
mtx_is.append(ps.get_mtx_i())
conns.append(mesh.conns[ig].copy())
# Get reference element coordinates corresponding to
# destination coordinates.
ref_coors = nm.empty_like(coors)
cells = nm.empty((coors.shape[0], 2), dtype=nm.int32)
status = nm.empty((coors.shape[0],), dtype=nm.int32)
find_ref_coors(ref_coors, cells, status, coors,
ics, offsets, iconn,
scoors, conns,
vertex_coorss, nodess, mtx_is,
1, close_limit, 1e-15, 100, 1e-8)
output('ref. coordinates: %f s' % (time.clock()-tt),
verbose=verbose)
elif strategy == 'crawl':
raise NotImplementedError
else:
raise ValueError('unknown search strategy! (%s)' % strategy)
else:
ref_coors = cache.ref_coors
cells = cache.cells
status = cache.status
return ref_coors, cells, status
| [
"sfepy.base.base.output",
"sfepy.discrete.fem.extmods.bases.find_ref_coors",
"sfepy.base.base.get_default_attr",
"sfepy.discrete.fem.mesh.make_inverse_connectivity"
] | [((1856, 1898), 'sfepy.base.base.get_default_attr', 'get_default_attr', (['cache', '"""ref_coors"""', 'None'], {}), "(cache, 'ref_coors', None)\n", (1872, 1898), False, 'from sfepy.base.base import output, get_default_attr\n'), ((1940, 1977), 'sfepy.base.base.get_default_attr', 'get_default_attr', (['cache', '"""mesh"""', 'None'], {}), "(cache, 'mesh', None)\n", (1956, 1977), False, 'from sfepy.base.base import output, get_default_attr\n'), ((2096, 2169), 'sfepy.base.base.output', 'output', (["('reference field: %d vertices' % scoors.shape[0])"], {'verbose': 'verbose'}), "('reference field: %d vertices' % scoors.shape[0], verbose=verbose)\n", (2102, 2169), False, 'from sfepy.base.base import output, get_default_attr\n'), ((2202, 2240), 'sfepy.base.base.get_default_attr', 'get_default_attr', (['cache', '"""iconn"""', 'None'], {}), "(cache, 'iconn', None)\n", (2218, 2240), False, 'from sfepy.base.base import output, get_default_attr\n'), ((2296, 2363), 'sfepy.discrete.fem.mesh.make_inverse_connectivity', 'make_inverse_connectivity', (['mesh.conns', 'mesh.n_nod'], {'ret_offsets': '(True)'}), '(mesh.conns, mesh.n_nod, ret_offsets=True)\n', (2321, 2363), False, 'from sfepy.discrete.fem.mesh import make_inverse_connectivity\n'), ((2776, 2815), 'sfepy.base.base.get_default_attr', 'get_default_attr', (['cache', '"""kdtree"""', 'None'], {}), "(cache, 'kdtree', None)\n", (2792, 2815), False, 'from sfepy.base.base import output, get_default_attr\n'), ((3076, 3088), 'time.clock', 'time.clock', ([], {}), '()\n', (3086, 3088), False, 'import time\n'), ((3226, 3238), 'time.clock', 'time.clock', ([], {}), '()\n', (3236, 3238), False, 'import time\n'), ((3257, 3288), 'numpy.asarray', 'nm.asarray', (['ics'], {'dtype': 'nm.int32'}), '(ics, dtype=nm.int32)\n', (3267, 3288), True, 'import numpy as nm\n'), ((3801, 3821), 'numpy.empty_like', 'nm.empty_like', (['coors'], {}), '(coors)\n', (3814, 3821), True, 'import numpy as nm\n'), ((3842, 3887), 'numpy.empty', 'nm.empty', (['(coors.shape[0], 2)'], {'dtype': 'nm.int32'}), '((coors.shape[0], 2), dtype=nm.int32)\n', (3850, 3887), True, 'import numpy as nm\n'), ((3909, 3952), 'numpy.empty', 'nm.empty', (['(coors.shape[0],)'], {'dtype': 'nm.int32'}), '((coors.shape[0],), dtype=nm.int32)\n', (3917, 3952), True, 'import numpy as nm\n'), ((3966, 4119), 'sfepy.discrete.fem.extmods.bases.find_ref_coors', 'find_ref_coors', (['ref_coors', 'cells', 'status', 'coors', 'ics', 'offsets', 'iconn', 'scoors', 'conns', 'vertex_coorss', 'nodess', 'mtx_is', '(1)', 'close_limit', '(1e-15)', '(100)', '(1e-08)'], {}), '(ref_coors, cells, status, coors, ics, offsets, iconn, scoors,\n conns, vertex_coorss, nodess, mtx_is, 1, close_limit, 1e-15, 100, 1e-08)\n', (3980, 4119), False, 'from sfepy.discrete.fem.extmods.bases import find_ref_coors\n'), ((2492, 2529), 'numpy.where', 'nm.where', (['(offsets[1:] == offsets[:-1])'], {}), '(offsets[1:] == offsets[:-1])\n', (2500, 2529), True, 'import numpy as nm\n'), ((2929, 2941), 'time.clock', 'time.clock', ([], {}), '()\n', (2939, 2941), False, 'import time\n'), ((2967, 2981), 'scipy.spatial.cKDTree', 'KDTree', (['scoors'], {}), '(scoors)\n', (2973, 2981), True, 'from scipy.spatial import cKDTree as KDTree\n'), ((3173, 3185), 'time.clock', 'time.clock', ([], {}), '()\n', (3183, 3185), False, 'import time\n'), ((4258, 4270), 'time.clock', 'time.clock', ([], {}), '()\n', (4268, 4270), False, 'import time\n'), ((3023, 3035), 'time.clock', 'time.clock', ([], {}), '()\n', (3033, 3035), False, 'import time\n')] |
"""
Biot problem with the non-penetration BC on the Walls boundary region.
The non-penetration condition is enforced weakly using the Lagrange
multiplier approach. There is also a rigid body movement constraint
imposed on the Outlet region using the linear combination boundary
conditions.
"""
from biot_npbc import cinc_simple, define_regions, get_pars
def define():
from sfepy import data_dir
filename = data_dir + '/meshes/3d/cylinder.mesh'
output_dir = 'output'
return define_input(filename, output_dir)
def post_process(out, pb, state, extend=False):
from sfepy.base.base import Struct
dvel = pb.evaluate('de_diffusion_velocity.2.Omega( m.K, p )')
out['dvel'] = Struct(name='output_data', var_name='p',
mode='cell', data=dvel, dofs=None)
stress = pb.evaluate('de_cauchy_stress.2.Omega( m.D, u )')
out['cauchy_stress'] = Struct(name='output_data', var_name='u',
mode='cell', data=stress, dofs=None)
return out
def define_input(filename, output_dir):
filename_mesh = filename
options = {
'output_dir' : output_dir,
'output_format' : 'vtk',
'post_process_hook' : 'post_process',
## 'file_per_var' : True,
'ls' : 'ls',
'nls' : 'newton',
}
functions = {
'cinc_simple0' : (lambda coors, domain:
cinc_simple(coors, 0),),
'cinc_simple1' : (lambda coors, domain:
cinc_simple(coors, 1),),
'cinc_simple2' : (lambda coors, domain:
cinc_simple(coors, 2),),
'get_pars' : (lambda ts, coors, mode=None, region=None, ig=None:
get_pars(ts, coors, mode, region, ig,
output_dir=output_dir),),
}
regions, dim = define_regions(filename_mesh)
fields = {
'displacement': ('real', 'vector', 'Omega', 1),
'pressure': ('real', 'scalar', 'Omega', 1),
'multiplier': ('real', 'scalar', ('Walls', 'surface'), 1),
}
variables = {
'u' : ('unknown field', 'displacement', 0),
'v' : ('test field', 'displacement', 'u'),
'p' : ('unknown field', 'pressure', 1),
'q' : ('test field', 'pressure', 'p'),
'ul' : ('unknown field', 'multiplier', 2),
'vl' : ('test field', 'multiplier', 'ul'),
}
ebcs = {
'inlet' : ('Inlet', {'p.0' : 1.0, 'u.all' : 0.0}),
'outlet' : ('Outlet', {'p.0' : -1.0}),
}
lcbcs = {
'rigid' : ('Outlet', {'u.all' : 'rigid'}),
}
materials = {
'm' : 'get_pars',
}
equations = {
'eq_1' :
"""dw_lin_elastic.2.Omega( m.D, v, u )
- dw_biot.2.Omega( m.alpha, v, p )
+ dw_non_penetration.2.Walls( v, ul )
= 0""",
'eq_2' :
"""dw_biot.2.Omega( m.alpha, u, q )
+ dw_diffusion.2.Omega( m.K, q, p )
= 0""",
'eq_3' :
"""dw_non_penetration.2.Walls( u, vl )
= 0""",
}
solvers = {
'ls' : ('ls.scipy_direct', {}),
'newton' : ('nls.newton', {}),
}
return locals()
| [
"sfepy.base.base.Struct"
] | [((699, 774), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'var_name': '"""p"""', 'mode': '"""cell"""', 'data': 'dvel', 'dofs': 'None'}), "(name='output_data', var_name='p', mode='cell', data=dvel, dofs=None)\n", (705, 774), False, 'from sfepy.base.base import Struct\n'), ((891, 968), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'var_name': '"""u"""', 'mode': '"""cell"""', 'data': 'stress', 'dofs': 'None'}), "(name='output_data', var_name='u', mode='cell', data=stress, dofs=None)\n", (897, 968), False, 'from sfepy.base.base import Struct\n'), ((1838, 1867), 'biot_npbc.define_regions', 'define_regions', (['filename_mesh'], {}), '(filename_mesh)\n', (1852, 1867), False, 'from biot_npbc import cinc_simple, define_regions, get_pars\n'), ((1400, 1421), 'biot_npbc.cinc_simple', 'cinc_simple', (['coors', '(0)'], {}), '(coors, 0)\n', (1411, 1421), False, 'from biot_npbc import cinc_simple, define_regions, get_pars\n'), ((1499, 1520), 'biot_npbc.cinc_simple', 'cinc_simple', (['coors', '(1)'], {}), '(coors, 1)\n', (1510, 1520), False, 'from biot_npbc import cinc_simple, define_regions, get_pars\n'), ((1598, 1619), 'biot_npbc.cinc_simple', 'cinc_simple', (['coors', '(2)'], {}), '(coors, 2)\n', (1609, 1619), False, 'from biot_npbc import cinc_simple, define_regions, get_pars\n'), ((1718, 1778), 'biot_npbc.get_pars', 'get_pars', (['ts', 'coors', 'mode', 'region', 'ig'], {'output_dir': 'output_dir'}), '(ts, coors, mode, region, ig, output_dir=output_dir)\n', (1726, 1778), False, 'from biot_npbc import cinc_simple, define_regions, get_pars\n')] |
r"""
Thermo-elasticity with a given temperature distribution.
Uses `dw_biot` term with an isotropic coefficient for thermo-elastic coupling.
For given body temperature :math:`T` and background temperature
:math:`T_0` find :math:`\ul{u}` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} (T - T_0)\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;, \\
\alpha_{ij} = (3 \lambda + 2 \mu) \alpha \delta_{ij}
and :math:`\alpha` is the thermal expansion coefficient.
"""
from __future__ import absolute_import
import numpy as np
from sfepy.base.base import Struct
from sfepy.mechanics.matcoefs import stiffness_from_lame
from sfepy.mechanics.tensors import get_von_mises_stress
from sfepy import data_dir
# Material parameters.
lam = 10.0
mu = 5.0
thermal_expandability = 1.25e-5
T0 = 20.0 # Background temperature.
filename_mesh = data_dir + '/meshes/3d/block.mesh'
def get_temperature_load(ts, coors, region=None):
"""
Temperature load depends on the `x` coordinate.
"""
x = coors[:, 0]
return (x - x.min())**2 - T0
def post_process(out, pb, state, extend=False):
"""
Compute derived quantities: strain, stresses. Store also the loading
temperature.
"""
ev = pb.evaluate
strain = ev('ev_cauchy_strain.2.Omega( u )', mode='el_avg')
out['cauchy_strain'] = Struct(name='output_data',
mode='cell', data=strain,
dofs=None)
e_stress = ev('ev_cauchy_stress.2.Omega( solid.D, u )', mode='el_avg')
out['elastic_stress'] = Struct(name='output_data',
mode='cell', data=e_stress,
dofs=None)
t_stress = ev('ev_biot_stress.2.Omega( solid.alpha, T )', mode='el_avg')
out['thermal_stress'] = Struct(name='output_data',
mode='cell', data=t_stress,
dofs=None)
out['total_stress'] = Struct(name='output_data',
mode='cell', data=e_stress + t_stress,
dofs=None)
out['von_mises_stress'] = aux = out['total_stress'].copy()
vms = get_von_mises_stress(aux.data.squeeze())
vms.shape = (vms.shape[0], 1, 1, 1)
out['von_mises_stress'].data = vms
val = pb.get_variables()['T']()
val.shape = (val.shape[0], 1)
out['T'] = Struct(name='output_data',
mode='vertex', data=val + T0,
dofs=None)
return out
options = {
'post_process_hook' : 'post_process',
'nls' : 'newton',
'ls' : 'ls',
}
functions = {
'get_temperature_load' : (get_temperature_load,),
}
regions = {
'Omega' : 'all',
'Left' : ('vertices in (x < -4.99)', 'facet'),
}
fields = {
'displacement': ('real', 3, 'Omega', 1),
'temperature': ('real', 1, 'Omega', 1),
}
variables = {
'u' : ('unknown field', 'displacement', 0),
'v' : ('test field', 'displacement', 'u'),
'T' : ('parameter field', 'temperature',
{'setter' : 'get_temperature_load'}),
}
ebcs = {
'fix_u' : ('Left', {'u.all' : 0.0}),
}
eye_sym = np.array([[1], [1], [1], [0], [0], [0]], dtype=np.float64)
materials = {
'solid' : ({
'D' : stiffness_from_lame(3, lam=lam, mu=mu),
'alpha' : (3.0 * lam + 2.0 * mu) * thermal_expandability * eye_sym
},),
}
equations = {
'balance_of_forces' :
"""dw_lin_elastic.2.Omega( solid.D, v, u )
- dw_biot.2.Omega( solid.alpha, v, T )
= 0""",
}
solvers = {
'ls' : ('ls.scipy_direct', {}),
'newton' : ('nls.newton', {
'i_max' : 1,
'eps_a' : 1e-10,
}),
}
| [
"sfepy.base.base.Struct",
"sfepy.mechanics.matcoefs.stiffness_from_lame"
] | [((3335, 3393), 'numpy.array', 'np.array', (['[[1], [1], [1], [0], [0], [0]]'], {'dtype': 'np.float64'}), '([[1], [1], [1], [0], [0], [0]], dtype=np.float64)\n', (3343, 3393), True, 'import numpy as np\n'), ((1516, 1579), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'strain', 'dofs': 'None'}), "(name='output_data', mode='cell', data=strain, dofs=None)\n", (1522, 1579), False, 'from sfepy.base.base import Struct\n'), ((1752, 1817), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'e_stress', 'dofs': 'None'}), "(name='output_data', mode='cell', data=e_stress, dofs=None)\n", (1758, 1817), False, 'from sfepy.base.base import Struct\n'), ((1994, 2059), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 't_stress', 'dofs': 'None'}), "(name='output_data', mode='cell', data=t_stress, dofs=None)\n", (2000, 2059), False, 'from sfepy.base.base import Struct\n'), ((2157, 2233), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': '(e_stress + t_stress)', 'dofs': 'None'}), "(name='output_data', mode='cell', data=e_stress + t_stress, dofs=None)\n", (2163, 2233), False, 'from sfepy.base.base import Struct\n'), ((2580, 2647), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""vertex"""', 'data': '(val + T0)', 'dofs': 'None'}), "(name='output_data', mode='vertex', data=val + T0, dofs=None)\n", (2586, 2647), False, 'from sfepy.base.base import Struct\n'), ((3439, 3477), 'sfepy.mechanics.matcoefs.stiffness_from_lame', 'stiffness_from_lame', (['(3)'], {'lam': 'lam', 'mu': 'mu'}), '(3, lam=lam, mu=mu)\n', (3458, 3477), False, 'from sfepy.mechanics.matcoefs import stiffness_from_lame\n')] |
import numpy as nm
from sfepy.linalg import dot_sequences
from sfepy.terms.terms import Term, terms
class PiezoCouplingTerm(Term):
r"""
Piezoelectric coupling term. Can be evaluated.
:Definition:
.. math::
\int_{\Omega} g_{kij}\ e_{ij}(\ul{v}) \nabla_k p \mbox{ , }
\int_{\Omega} g_{kij}\ e_{ij}(\ul{u}) \nabla_k q
:Arguments 1:
- material : :math:`g_{kij}`
- virtual : :math:`\ul{v}`
- state : :math:`p`
:Arguments 2:
- material : :math:`g_{kij}`
- state : :math:`\ul{u}`
- virtual : :math:`q`
:Arguments 3:
- material : :math:`g_{kij}`
- parameter_v : :math:`\ul{u}`
- parameter_s : :math:`p`
"""
name = 'dw_piezo_coupling'
arg_types = (('material', 'virtual', 'state'),
('material', 'state', 'virtual'),
('material', 'parameter_v', 'parameter_s'))
arg_shapes = {'material' : 'D, S',
'virtual/grad' : ('D', None), 'state/grad' : 1,
'virtual/div' : (1, None), 'state/div' : 'D',
'parameter_v' : 'D', 'parameter_s' : 1}
modes = ('grad', 'div', 'eval')
def get_fargs(self, mat, vvar, svar,
mode=None, term_mode=None, diff_var=None, **kwargs):
if self.mode == 'grad':
qp_var, qp_name = svar, 'grad'
else:
qp_var, qp_name = vvar, 'cauchy_strain'
vvg, _ = self.get_mapping(vvar)
if mode == 'weak':
aux = nm.array([0], ndmin=4, dtype=nm.float64)
if diff_var is None:
# grad or strain according to mode.
val_qp = self.get(qp_var, qp_name)
fmode = 0
else:
val_qp = aux
fmode = 1
if self.mode == 'grad':
strain, grad = aux, val_qp
else:
strain, grad = val_qp, aux
fmode += 2
return strain, grad, mat, vvg, fmode
elif mode == 'eval':
strain = self.get(vvar, 'cauchy_strain')
grad = self.get(svar, 'grad')
return strain, grad, mat, vvg
else:
raise ValueError('unsupported evaluation mode in %s! (%s)'
% (self.name, mode))
def get_eval_shape(self, mat, 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_piezo_coupling,
'div' : terms.dw_piezo_coupling,
'eval' : terms.d_piezo_coupling,
}[self.mode]
class PiezoStressTerm(Term):
r"""
Evaluate piezoelectric stress tensor.
It is given in the usual vector form exploiting symmetry: in 3D it has 6
components with the indices ordered as :math:`[11, 22, 33, 12, 13, 23]`, in
2D it has 3 components with the indices ordered as :math:`[11, 22, 12]`.
Supports 'eval', 'el_avg' and 'qp' evaluation modes.
:Definition:
.. math::
\int_{\Omega} g_{kij} \nabla_k p
:Arguments:
- material : :math:`g_{kij}`
- parameter : :math:`p`
"""
name = 'ev_piezo_stress'
arg_types = ('material', 'parameter')
arg_shapes = {'material' : 'D, S', 'parameter' : '1'}
@staticmethod
def function(out, val_qp, vg, fmode):
if fmode == 2:
out[:] = val_qp
status = 0
else:
status = vg.integrate(out, val_qp, fmode)
return status
def get_fargs(self, mat, parameter,
mode=None, term_mode=None, diff_var=None, **kwargs):
vg, _ = self.get_mapping(parameter)
grad = self.get(parameter, 'grad')
val_qp = dot_sequences(mat, grad, mode='ATB')
fmode = {'eval' : 0, 'el_avg' : 1, 'qp' : 2}.get(mode, 1)
return val_qp, vg, fmode
def get_eval_shape(self, mat, 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 * (dim + 1) / 2, 1), parameter.dtype
| [
"sfepy.linalg.dot_sequences"
] | [((3897, 3933), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['mat', 'grad'], {'mode': '"""ATB"""'}), "(mat, grad, mode='ATB')\n", (3910, 3933), False, 'from sfepy.linalg import dot_sequences\n'), ((1536, 1576), 'numpy.array', 'nm.array', (['[0]'], {'ndmin': '(4)', 'dtype': 'nm.float64'}), '([0], ndmin=4, dtype=nm.float64)\n', (1544, 1576), True, 'import numpy as nm\n')] |
# -*- coding: utf-8
r"""
Homogenization of the Darcy flow in a thin porous layer.
The reference cell is composed of the matrix representing the dual porosity
and of two disconnected channels representing the primary porosity,
see paper [1].
[1] <NAME>, <NAME>: Modeling Tissue Perfusion Using a Homogenized
Model with Layer-wise Decomposition. IFAC Proceedings Volumes 45(2), 2012,
pages 1029-1034.
https://doi.org/10.3182/20120215-3-AT-3016.00182
"""
from __future__ import absolute_import
from sfepy.discrete.fem.periodic import match_x_plane, match_y_plane
import sfepy.homogenization.coefs_base as cb
import numpy as nm
from sfepy import data_dir
import six
from six.moves import range
def get_mats(pk, ph, pe, dim):
m1 = nm.eye(dim, dtype=nm.float64) * pk
m1[-1, -1] = pk / ph
m2 = nm.eye(dim, dtype=nm.float64) * pk
m2[-1, -1] = pk / ph ** 2
return m1, m2
def recovery_perf(pb, corrs, macro):
from sfepy.homogenization.recovery import compute_p_from_macro
from sfepy.base.base import Struct
slev = ''
micro_nnod = pb.domain.mesh.n_nod
centre_Y = nm.sum(pb.domain.mesh.coors, axis=0) / micro_nnod
nodes_Y = {}
channels = {}
for k in six.iterkeys(macro):
if 'press' in k:
channels[k[-1]] = 1
channels = list(channels.keys())
varnames = ['pM']
for ch in channels:
nodes_Y[ch] = pb.domain.regions['Y' + ch].vertices
varnames.append('p' + ch)
pvars = pb.create_variables(varnames)
press = {}
# matrix
press['M'] = \
corrs['corrs_%s_gamma_p' % pb_def['name']]['pM'] * macro['g_p'] + \
corrs['corrs_%s_gamma_m' % pb_def['name']]['pM'] * macro['g_m']
out = {}
# channels
for ch in channels:
press_mac = macro['press' + ch][0, 0]
press_mac_grad = macro['pressg' + ch]
nnod = corrs['corrs_%s_pi%s' % (pb_def['name'], ch)]\
['p%s_0' % ch].shape[0]
press_mic = nm.zeros((nnod, 1))
for key, val in \
six.iteritems(corrs['corrs_%s_pi%s' % (pb_def['name'], ch)]):
kk = int(key[-1])
press_mic += val * press_mac_grad[kk, 0]
for key in six.iterkeys(corrs):
if ('_gamma_' + ch in key):
kk = int(key[-1]) - 1
press_mic += corrs[key]['p' + ch] * macro['g' + ch][kk]
press_mic += \
compute_p_from_macro(press_mac_grad[nm.newaxis,nm.newaxis, :, :],
micro_coors[nodes_Y[ch]], 0,
centre=centre_Y, extdim=-1).reshape((nnod, 1))
press[ch] = press_mac + eps0 * press_mic
out[slev + 'p' + ch] = Struct(name='output_data',
mode='vertex',
data=press[ch],
var_name='p' + ch,
dofs=None)
pvars['p' + ch].set_data(press_mic)
dvel = pb.evaluate('ev_diffusion_velocity.iV.Y%s(mat1%s.k, p%s)'
% (ch, ch, ch),
var_dict={'p' + ch: pvars['p' + ch]},
mode='el_avg')
out[slev + 'w' + ch] = Struct(name='output_data',
mode='cell',
data=dvel,
var_name='w' + ch,
dofs=None)
press['M'] += corrs['corrs_%s_eta%s' % (pb_def['name'], ch)]['pM']\
* press_mac
pvars['pM'].set_data(press['M'])
dvel = pb.evaluate('%e * ev_diffusion_velocity.iV.YM(mat1M.k, pM)' % eps0,
var_dict={'pM': pvars['pM']}, mode='el_avg')
out[slev + 'pM'] = Struct(name='output_data',
mode='vertex',
dat=press['M'],
var_name='pM',
dofs=None)
out[slev + 'wM'] = Struct(name='output_data',
mode='cell',
data=dvel,
var_name='wM',
dofs=None)
return out
geoms = {
'2_4': ['2_4_Q1', '2', 5],
'3_8': ['3_8_Q1', '4', 5],
'3_4': ['3_4_P1', '3', 3],
}
pb_def = {
'name': '3d_2ch',
'mesh_filename': data_dir + '/meshes/3d/perfusion_micro3d.mesh',
'dim': 3,
'geom': geoms['3_4'],
'eps0': 1.0e-2,
'param_h': 1.0,
'param_kappa_m': 0.1,
'matrix_mat_el_grp': 3,
'channels': {
'A': {
'mat_el_grp': 1,
'fix_nd_grp': (4, 1),
'io_nd_grp': [1, 2, 3],
'param_kappa_ch': 1.0,
},
'B': {
'mat_el_grp': 2,
'fix_nd_grp': (14, 11),
'io_nd_grp': [11, 12, 13],
'param_kappa_ch': 2.0,
},
},
}
filename_mesh = pb_def['mesh_filename']
eps0 = pb_def['eps0']
param_h = pb_def['param_h']
# integrals
integrals = {
'iV': 2,
'iS': 2,
}
functions = {
'match_x_plane': (match_x_plane,),
'match_y_plane': (match_y_plane,),
}
aux = []
for ch, val in six.iteritems(pb_def['channels']):
aux.append('r.bYM' + ch)
# basic regions
regions = {
'Y': 'all',
'YM': 'cells of group %d' % pb_def['matrix_mat_el_grp'],
# periodic boundaries
'Pl': ('vertices in (x < 0.001)', 'facet'),
'Pr': ('vertices in (x > 0.999)', 'facet'),
'PlYM': ('r.Pl *v r.YM', 'facet'),
'PrYM': ('r.Pr *v r.YM', 'facet'),
'bYMp': ('r.bYp *v r.YM', 'facet', 'YM'),
'bYMm': ('r.bYm *v r.YM', 'facet', 'YM'),
'bYMpm': ('r.bYMp +v r.bYMm', 'facet', 'YM'),
}
# matrix/channel boundaries
regions.update({
'bYMchs': (' +v '.join(aux), 'facet', 'YM'),
'YMmchs': 'r.YM -v r.bYMchs',
})
# boundary conditions Gamma+/-
ebcs = {
'gamma_pm_bYMchs': ('bYMchs', {'pM.0': 0.0}),
'gamma_pm_YMmchs': ('YMmchs', {'pM.0': 1.0}),
}
# periodic boundary conditions - matrix, X-direction
epbcs = {'periodic_xYM': (['PlYM', 'PrYM'], {'pM.0': 'pM.0'}, 'match_x_plane')}
lcbcs = {}
all_periodicYM = ['periodic_%sYM' % ii for ii in ['x', 'y'][:pb_def['dim']-1]]
all_periodicY = {}
if pb_def['dim'] == 2:
regions.update({
'bYm': ('vertices in (y < 0.001)', 'facet'),
'bYp': ('vertices in (y > 0.999)', 'facet'),
})
if pb_def['dim'] == 3:
regions.update({
'Pn': ('vertices in (y < 0.001)', 'facet'),
'Pf': ('vertices in (y > 0.999)', 'facet'),
'PnYM': ('r.Pn *v r.YM', 'facet'),
'PfYM': ('r.Pf *v r.YM', 'facet'),
'bYm': ('vertices in (z < 0.001)', 'facet'),
'bYp': ('vertices in (z > 0.999)', 'facet'),
})
# periodic boundary conditions - matrix, Y-direction
epbcs.update({
'periodic_yYM': (['PnYM', 'PfYM'], {'pM.0': 'pM.0'}, 'match_y_plane'),
})
reg_io = {}
ebcs_eta = {}
ebcs_gamma = {}
# generate regions, ebcs, epbcs
for ch, val in six.iteritems(pb_def['channels']):
all_periodicY[ch] = ['periodic_%sY%s' % (ii, ch)
for ii in ['x', 'y'][:pb_def['dim']-1]]
# channels: YA, fixedYA, bYMA (matrix/channel boundaries)
regions.update({
'Y' + ch: 'cells of group %d' % val['mat_el_grp'],
'bYM' + ch: ('r.YM *v r.Y' + ch, 'facet', 'YM'),
'PlY' + ch: ('r.Pl *v r.Y' + ch, 'facet'),
'PrY' + ch: ('r.Pr *v r.Y' + ch, 'facet'),
})
if 'fix_nd_grp' in val:
regions.update({
'fixedY' + ch: ('vertices of group %d' % val['fix_nd_grp'][0],
'vertex'),
})
ebcs_eta[ch] = []
for ch2, val2 in six.iteritems(pb_def['channels']):
aux = 'eta%s_bYM%s' % (ch, ch2)
if ch2 == ch:
ebcs.update({aux: ('bYM' + ch2, {'pM.0': 1.0})})
else:
ebcs.update({aux: ('bYM' + ch2, {'pM.0': 0.0})})
ebcs_eta[ch].append(aux)
# boundary conditions
# periodic boundary conditions - channels, X-direction
epbcs.update({
'periodic_xY' + ch: (['PlY' + ch, 'PrY' + ch],
{'p%s.0' % ch: 'p%s.0' % ch},
'match_x_plane'),
})
if pb_def['dim'] == 3:
regions.update({
'PnY' + ch: ('r.Pn *v r.Y' + ch, 'facet'),
'PfY' + ch: ('r.Pf *v r.Y' + ch, 'facet'),
})
# periodic boundary conditions - channels, Y-direction
epbcs.update({
'periodic_yY' + ch: (['PnY' + ch, 'PfY' + ch],
{'p%s.0' % ch: 'p%s.0' % ch},
'match_y_plane'),
})
reg_io[ch] = []
aux_bY = []
# channel: inputs/outputs
for i_io in range(len(val['io_nd_grp'])):
io = '%s_%d' % (ch, i_io+1)
# regions
aux = val['io_nd_grp'][i_io]
if 'fix_nd_grp' in val and val['fix_nd_grp'][1] == aux:
regions.update({
'bY%s' % io: ('vertices of group %d +v r.fixedY%s' % (aux, ch),
'facet', 'Y%s' % ch),
})
else:
regions.update({
'bY%s' % io: ('vertices of group %d' % aux,
'facet', 'Y%s' % ch),
})
aux_bY.append('r.bY%s' % io)
reg_io[ch].append('bY%s' % io)
regions.update({
'bY' + ch: (' +v '.join(aux_bY), 'facet', 'Y' + ch),
})
# channel: inputs/outputs
for i_io in range(len(val['io_nd_grp'])):
io = '%s_%d' % (ch, i_io + 1)
ion = '%s_n%d' % (ch, i_io + 1)
regions.update({
'bY%s' % ion: ('r.bY%s -v r.bY%s' % (ch, io), 'facet', 'Y%s' % ch),
})
# boundary conditions
aux = 'fix_p%s_bY%s' % (ch, ion)
ebcs.update({
aux: ('bY%s' % ion, {'p%s.0' % ch: 0.0}),
})
lcbcs.update({
'imv' + ch: ('Y' + ch, {'ls%s.all' % ch: None}, None,
'integral_mean_value')
})
matk1, matk2 = get_mats(pb_def['param_kappa_m'], param_h, eps0, pb_def['dim'])
materials = {
'mat1M': ({'k': matk1},),
'mat2M': ({'k': matk2},),
}
fields = {
'corrector_M': ('real', 'scalar', 'YM', 1),
'vel_M': ('real', 'vector', 'YM', 1),
'vol_all': ('real', 'scalar', 'Y', 1),
}
variables = {
'pM': ('unknown field', 'corrector_M'),
'qM': ('test field', 'corrector_M', 'pM'),
'Pi_M': ('parameter field', 'corrector_M', '(set-to-None)'),
'corr_M': ('parameter field', 'corrector_M', '(set-to-None)'),
'corr1_M': ('parameter field', 'corrector_M', '(set-to-None)'),
'corr2_M': ('parameter field', 'corrector_M', '(set-to-None)'),
'wM': ('parameter field', 'vel_M', '(set-to-None)'),
'vol_all': ('parameter field', 'vol_all', '(set-to-None)'),
}
# generate regions for channel inputs/outputs
for ch, val in six.iteritems(pb_def['channels']):
matk1, matk2 = get_mats(val['param_kappa_ch'], param_h,
eps0, pb_def['dim'])
materials.update({
'mat1' + ch: ({'k': matk1},),
'mat2' + ch: ({'k': matk2},),
})
fields.update({
'corrector_' + ch: ('real', 'scalar', 'Y' + ch, 1),
'vel_' + ch: ('real', 'vector', 'Y' + ch, 1),
})
variables.update({
'p' + ch: ('unknown field', 'corrector_' + ch),
'q' + ch: ('test field', 'corrector_' + ch, 'p' + ch),
'Pi_' + ch: ('parameter field', 'corrector_' + ch, '(set-to-None)'),
'corr1_' + ch: ('parameter field', 'corrector_' + ch, '(set-to-None)'),
'corr2_' + ch: ('parameter field', 'corrector_' + ch, '(set-to-None)'),
'w' + ch: ('unknown field', 'vel_' + ch),
# lagrange mutltipliers - integral mean value
'ls' + ch: ('unknown field', 'corrector_' + ch),
'lv' + ch: ('test field', 'corrector_' + ch, 'ls' + ch),
})
options = {
'coefs': 'coefs',
'requirements': 'requirements',
'ls': 'ls', # linear solver to use
'volumes': {
'total': {
'variables': ['vol_all'],
'expression': """ev_volume.iV.Y(vol_all)""",
},
'one': {
'value': 1.0,
}
},
'output_dir': './output',
'file_per_var': True,
'coefs_filename': 'coefs_perf_' + pb_def['name'],
'coefs_info': {'eps0': eps0},
'recovery_hook': 'recovery_perf',
'multiprocessing': False,
}
for ipm in ['p', 'm']:
options['volumes'].update({
'bYM' + ipm: {
'variables': ['pM'],
'expression': "ev_volume.iS.bYM%s(pM)" % ipm,
},
'bY' + ipm: {
'variables': ['vol_all'],
'expression': "ev_volume.iS.bY%s(vol_all)" % ipm,
}
})
for ch in six.iterkeys(reg_io):
for ireg in reg_io[ch]:
options['volumes'].update({
ireg: {
'variables': ['p' + ch],
'expression': "ev_volume.iS.%s(p%s)" % (ireg, ch),
}
})
coefs = {
'vol_bYMpm': {
'regions': ['bYMp', 'bYMm'],
'expression': 'ev_volume.iS.%s(pM)',
'class': cb.VolumeFractions,
},
'filenames': {},
}
requirements = {
'corrs_one_YM': {
'variable': ['pM'],
'ebcs': ['gamma_pm_YMmchs', 'gamma_pm_bYMchs'],
'epbcs': [],
'save_name': 'corrs_one_YM',
'class': cb.CorrSetBCS,
},
}
for ipm in ['p', 'm']:
requirements.update({
'corrs_gamma_' + ipm: {
'requires': [],
'ebcs': ['gamma_pm_bYMchs'],
'epbcs': all_periodicYM,
'equations': {
'eq_gamma_pm': """dw_diffusion.iV.YM(mat2M.k, qM, pM) =
%e * dw_integrate.iS.bYM%s(qM)"""
% (1.0/param_h, ipm),
},
'class': cb.CorrOne,
'save_name': 'corrs_%s_gamma_%s' % (pb_def['name'], ipm),
},
})
for ipm2 in ['p', 'm']:
coefs.update({
'H' + ipm + ipm2: { # test+
'requires': ['corrs_gamma_' + ipm],
'set_variables': [('corr_M', 'corrs_gamma_' + ipm, 'pM')],
'expression': 'ev_integrate.iS.bYM%s(corr_M)' % ipm2,
'set_volume': 'bYp',
'class': cb.CoefOne,
},
})
def get_channel(keys, bn):
for ii in keys:
if bn in ii:
return ii[(ii.rfind(bn) + len(bn)):]
return None
def set_corrpis(variables, ir, ic, mode, **kwargs):
ch = get_channel(list(kwargs.keys()), 'pis_')
pis = kwargs['pis_' + ch]
corrs_pi = kwargs['corrs_pi' + ch]
if mode == 'row':
val = pis.states[ir]['p' + ch] + corrs_pi.states[ir]['p' + ch]
variables['corr1_' + ch].set_data(val)
elif mode == 'col':
val = pis.states[ic]['p' + ch] + corrs_pi.states[ic]['p' + ch]
variables['corr2_' + ch].set_data(val)
def set_corr_S(variables, ir, *args, **kwargs):
ch = get_channel(list(kwargs.keys()), 'pis_')
io = get_channel(list(kwargs.keys()), 'corrs_gamma_')
pis = kwargs['pis_' + ch]
corrs_gamma = kwargs['corrs_gamma_' + io]
pi = pis.states[ir]['p' + ch]
val = corrs_gamma.state['p' + ch]
variables['corr1_' + ch].set_data(pi)
variables['corr2_' + ch].set_data(val)
def set_corr_cc(variables, ir, *args, **kwargs):
ch = get_channel(list(kwargs.keys()), 'pis_')
pis = kwargs['pis_' + ch]
corrs_pi = kwargs['corrs_pi' + ch]
pi = pis.states[ir]['p' + ch]
pi = pi - nm.mean(pi)
val = pi + corrs_pi.states[ir]['p' + ch]
variables['corr1_' + ch].set_data(val)
for ch, val in six.iteritems(pb_def['channels']):
coefs.update({
'G' + ch: { # test+
'requires': ['corrs_one' + ch, 'corrs_eta' + ch],
'set_variables': [('corr1_M', 'corrs_one' + ch, 'pM'),
('corr2_M', 'corrs_eta' + ch, 'pM')],
'expression': 'dw_diffusion.iV.YM(mat2M.k, corr1_M, corr2_M)',
'class': cb.CoefOne,
},
'K' + ch: { # test+
'requires': ['pis_' + ch, 'corrs_pi' + ch],
'set_variables': set_corrpis,
'expression': 'dw_diffusion.iV.Y%s(mat2%s.k, corr1_%s, corr2_%s)'\
% ((ch,) * 4),
'dim': pb_def['dim'] - 1,
'class': cb.CoefDimDim,
},
})
requirements.update({
'pis_' + ch: {
'variables': ['p' + ch],
'class': cb.ShapeDim,
},
'corrs_one' + ch: {
'variable': ['pM'],
'ebcs': ebcs_eta[ch],
'epbcs': [],
'save_name': 'corrs_%s_one%s' % (pb_def['name'], ch),
'class': cb.CorrSetBCS,
},
'corrs_eta' + ch: {
'ebcs': ebcs_eta[ch],
'epbcs': all_periodicYM,
'equations': {
'eq_eta': 'dw_diffusion.iV.YM(mat2M.k, qM, pM) = 0',
},
'class': cb.CorrOne,
'save_name': 'corrs_%s_eta%s' % (pb_def['name'], ch),
},
'corrs_pi' + ch: {
'requires': ['pis_' + ch],
'set_variables': [('Pi_' + ch, 'pis_' + ch, 'p' + ch)],
'ebcs': [],
'epbcs': all_periodicY[ch],
'lcbcs': ['imv' + ch],
'equations': {
'eq_pi': """dw_diffusion.iV.Y%s(mat2%s.k, q%s, p%s)
+ dw_dot.iV.Y%s(q%s, ls%s)
= - dw_diffusion.iV.Y%s(mat2%s.k, q%s, Pi_%s)"""
% ((ch,) * 11),
'eq_imv': 'dw_dot.iV.Y%s(lv%s, p%s) = 0' % ((ch,) * 3),
},
'dim': pb_def['dim'] - 1,
'class': cb.CorrDim,
'save_name': 'corrs_%s_pi%s' % (pb_def['name'], ch),
},
})
for ipm in ['p', 'm']:
coefs.update({
'E' + ipm + ch: { # test+
'requires': ['corrs_eta' + ch],
'set_variables': [('corr_M', 'corrs_eta' + ch, 'pM')],
'expression': 'ev_integrate.iS.bYM%s(corr_M)' % ipm,
'set_volume': 'bYp',
'class': cb.CoefOne,
},
'F' + ipm + ch: { # test+
'requires': ['corrs_one' + ch, 'corrs_gamma_' + ipm],
'set_variables': [('corr1_M', 'corrs_one' + ch, 'pM'),
('corr2_M', 'corrs_gamma_' + ipm, 'pM')],
'expression': """dw_diffusion.iV.YM(mat2M.k, corr1_M, corr2_M)
- %e * ev_integrate.iS.bYM%s(corr1_M)"""\
% (1.0/param_h, ipm),
'class': cb.CoefOne,
},
})
for i_io in range(len(val['io_nd_grp'])):
io = '%s_%d' % (ch, i_io + 1)
coefs.update({
'S' + io: { # [Rohan1] (4.28), test+
'requires': ['corrs_gamma_' + io, 'pis_' + ch],
'set_variables': set_corr_S,
'expression': 'dw_diffusion.iV.Y%s(mat2%s.k,corr1_%s,corr2_%s)'
% ((ch,) * 4),
'dim': pb_def['dim'] - 1,
'class': cb.CoefDim,
},
'P' + io: { # test+
'requires': ['pis_' + ch, 'corrs_pi' + ch],
'set_variables': set_corr_cc,
'expression': 'ev_integrate.iS.bY%s(corr1_%s)'\
% (io, ch),
'set_volume': 'bYp',
'dim': pb_def['dim'] - 1,
'class': cb.CoefDim,
},
'S_test' + io: {
'requires': ['corrs_pi' + ch],
'set_variables': [('corr1_' + ch, 'corrs_pi' + ch, 'p' + ch)],
'expression': '%e * ev_integrate.iS.bY%s(corr1_%s)'\
% (1.0 / param_h, io, ch),
'dim': pb_def['dim'] - 1,
'class': cb.CoefDim,
},
})
requirements.update({
'corrs_gamma_' + io: {
'requires': [],
'variables': ['p' + ch, 'q' + ch],
'ebcs': [],
'epbcs': all_periodicY[ch],
'lcbcs': ['imv' + ch],
'equations': {
'eq_gamma': """dw_diffusion.iV.Y%s(mat2%s.k, q%s, p%s)
+ dw_dot.iV.Y%s(q%s, ls%s)
= %e * dw_integrate.iS.bY%s(q%s)"""
% ((ch,) * 7 + (1.0/param_h, io, ch)),
'eq_imv': 'dw_dot.iV.Y%s(lv%s, p%s) = 0'
% ((ch,) * 3),
},
'class': cb.CorrOne,
'save_name': 'corrs_%s_gamma_%s' % (pb_def['name'], io),
},
})
for i_io2 in range(len(val['io_nd_grp'])):
io2 = '%s_%d' % (ch, i_io2 + 1)
io12 = '%s_%d' % (io, i_io2 + 1)
coefs.update({
'R' + io12: { # test+
'requires': ['corrs_gamma_' + io2],
'set_variables': [('corr1_' + ch, 'corrs_gamma_' + io2,
'p' + ch)],
'expression': 'ev_integrate.iS.bY%s(corr1_%s)'\
% (io, ch),
'set_volume': 'bYp',
'class': cb.CoefOne,
},
})
solvers = {
'ls': ('ls.scipy_direct', {}),
'newton': ('nls.newton', {
'i_max': 1,
})
}
| [
"sfepy.homogenization.recovery.compute_p_from_macro",
"sfepy.base.base.Struct"
] | [((5156, 5189), 'six.iteritems', 'six.iteritems', (["pb_def['channels']"], {}), "(pb_def['channels'])\n", (5169, 5189), False, 'import six\n'), ((6949, 6982), 'six.iteritems', 'six.iteritems', (["pb_def['channels']"], {}), "(pb_def['channels'])\n", (6962, 6982), False, 'import six\n'), ((10860, 10893), 'six.iteritems', 'six.iteritems', (["pb_def['channels']"], {}), "(pb_def['channels'])\n", (10873, 10893), False, 'import six\n'), ((12725, 12745), 'six.iterkeys', 'six.iterkeys', (['reg_io'], {}), '(reg_io)\n', (12737, 12745), False, 'import six\n'), ((15620, 15653), 'six.iteritems', 'six.iteritems', (["pb_def['channels']"], {}), "(pb_def['channels'])\n", (15633, 15653), False, 'import six\n'), ((1200, 1219), 'six.iterkeys', 'six.iterkeys', (['macro'], {}), '(macro)\n', (1212, 1219), False, 'import six\n'), ((3753, 3840), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""vertex"""', 'dat': "press['M']", 'var_name': '"""pM"""', 'dofs': 'None'}), "(name='output_data', mode='vertex', dat=press['M'], var_name='pM',\n dofs=None)\n", (3759, 3840), False, 'from sfepy.base.base import Struct\n'), ((3981, 4057), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'dvel', 'var_name': '"""wM"""', 'dofs': 'None'}), "(name='output_data', mode='cell', data=dvel, var_name='wM', dofs=None)\n", (3987, 4057), False, 'from sfepy.base.base import Struct\n'), ((7635, 7668), 'six.iteritems', 'six.iteritems', (["pb_def['channels']"], {}), "(pb_def['channels'])\n", (7648, 7668), False, 'import six\n'), ((733, 762), 'numpy.eye', 'nm.eye', (['dim'], {'dtype': 'nm.float64'}), '(dim, dtype=nm.float64)\n', (739, 762), True, 'import numpy as nm\n'), ((802, 831), 'numpy.eye', 'nm.eye', (['dim'], {'dtype': 'nm.float64'}), '(dim, dtype=nm.float64)\n', (808, 831), True, 'import numpy as nm\n'), ((1101, 1137), 'numpy.sum', 'nm.sum', (['pb.domain.mesh.coors'], {'axis': '(0)'}), '(pb.domain.mesh.coors, axis=0)\n', (1107, 1137), True, 'import numpy as nm\n'), ((1958, 1977), 'numpy.zeros', 'nm.zeros', (['(nnod, 1)'], {}), '((nnod, 1))\n', (1966, 1977), True, 'import numpy as nm\n'), ((2014, 2074), 'six.iteritems', 'six.iteritems', (["corrs['corrs_%s_pi%s' % (pb_def['name'], ch)]"], {}), "(corrs['corrs_%s_pi%s' % (pb_def['name'], ch)])\n", (2027, 2074), False, 'import six\n'), ((2179, 2198), 'six.iterkeys', 'six.iterkeys', (['corrs'], {}), '(corrs)\n', (2191, 2198), False, 'import six\n'), ((2670, 2761), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""vertex"""', 'data': 'press[ch]', 'var_name': "('p' + ch)", 'dofs': 'None'}), "(name='output_data', mode='vertex', data=press[ch], var_name='p' + ch,\n dofs=None)\n", (2676, 2761), False, 'from sfepy.base.base import Struct\n'), ((3210, 3295), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'dvel', 'var_name': "('w' + ch)", 'dofs': 'None'}), "(name='output_data', mode='cell', data=dvel, var_name='w' + ch, dofs=None\n )\n", (3216, 3295), False, 'from sfepy.base.base import Struct\n'), ((15503, 15514), 'numpy.mean', 'nm.mean', (['pi'], {}), '(pi)\n', (15510, 15514), True, 'import numpy as nm\n'), ((2384, 2511), 'sfepy.homogenization.recovery.compute_p_from_macro', 'compute_p_from_macro', (['press_mac_grad[nm.newaxis, nm.newaxis, :, :]', 'micro_coors[nodes_Y[ch]]', '(0)'], {'centre': 'centre_Y', 'extdim': '(-1)'}), '(press_mac_grad[nm.newaxis, nm.newaxis, :, :],\n micro_coors[nodes_Y[ch]], 0, centre=centre_Y, extdim=-1)\n', (2404, 2511), False, 'from sfepy.homogenization.recovery import compute_p_from_macro\n')] |
#!/usr/bin/env python
# This code was adapted from http://sfepy.org/doc-devel/mat_optim.html.
from __future__ import print_function
from __future__ import absolute_import
import sys
sys.path.append('.')
import matplotlib as mlp
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import numpy as np
from sfepy.base.base import Struct, output
from sfepy.base.log import Log
from sfepy import data_dir
class MaterialSimulator(object):
@staticmethod
def create_app(filename, is_homog=False, **kwargs):
from sfepy.base.conf import ProblemConf, get_standard_keywords
from sfepy.homogenization.homogen_app import HomogenizationApp
from sfepy.applications import PDESolverApp
required, other = get_standard_keywords()
if is_homog:
required.remove('equations')
conf = ProblemConf.from_file(filename, required, other,
define_args=kwargs)
options = Struct(output_filename_trunk=None,
save_ebc=False,
save_ebc_nodes=False,
save_regions=False,
save_regions_as_groups=False,
save_field_meshes=False,
solve_not=False,
)
output.set_output(filename='sfepy_log.txt', quiet=True)
if is_homog:
app = HomogenizationApp(conf, options, 'material_opt_micro:')
else:
app = PDESolverApp(conf, options, 'material_opt_macro:')
app.conf.opt_data = {}
opts = conf.options
if hasattr(opts, 'parametric_hook'): # Parametric study.
parametric_hook = conf.get_function(opts.parametric_hook)
app.parametrize(parametric_hook)
return app
def __init__(self, macro_fn, micro_fn, phis, plot_meshes_bool=False):
self.macro_app = self.create_app(macro_fn, is_homog=False, is_opt=True)
self.micro_app = self.create_app(micro_fn, is_homog=True, is_opt=True)
self.phis = phis
self.plot_meshes_bool = plot_meshes_bool
@staticmethod
def rotate_mat(D, angle):
s = np.sin(angle)
c = np.cos(angle)
s2 = s**2
c2 = c**2
sc = s * c
T = np.array([[c2, 0, s2, 0, 2*sc,0],
[0, 1, 0, 0, 0, 0],
[s2, 0, c2, 0, -2*sc, 0],
[0, 0, 0, c, 0, -s],
[-sc, 0, sc, 0, c2 - s2, 0],
[0, 0, 0, s, 0, c]])
return np.dot(np.dot(T, D), T.T)
def plot_meshes(self):
# plot mesh for micro problem
pb = self.micro_app.problem
coors = pb.domain.mesh.coors
#print(set(coors[:,2]))
graph = pb.domain.mesh.get_conn(pb.domain.mesh.descs[0])
graph_slice = np.zeros((graph.shape[0], 4))
for j in range(graph.shape[0]):
graph_slice[j,:] = graph[j,coors[graph[j,:],2] == 0]
cells_matrix = pb.domain.regions['Ym'].get_cells()
cells_fibers = pb.domain.regions['Yf'].get_cells()
fig = plt.figure(figsize = (12, 5))
ax = fig.add_subplot(121)
pc = PolyCollection(verts=coors[graph[cells_matrix,0:4],:2], facecolors='white',
edgecolors='black')
ax.add_collection(pc)
pc = PolyCollection(verts=coors[graph[cells_fibers,0:4],:2], facecolors='gray',
edgecolors='black')
ax.add_collection(pc)
ax.axis('equal')
ax.set_title('2D plot of microstructure')
ax = fig.add_subplot(122, projection='3d')
for e in range(graph.shape[0]):
if e in cells_fibers:
color = 'gray'
else:
color = 'white'
tupleList = coors[graph[e,:],:]
vertices = [[0, 1, 2, 3], [4, 5, 6, 7],
[0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]
verts = [[tupleList[vertices[ix][iy]] for iy in range(len(vertices[0]))]
for ix in range(len(vertices))]
pc3d = Poly3DCollection(verts=verts, facecolors=color,
edgecolors='black', linewidths=1, alpha=0.5)
ax.add_collection3d(pc3d)
ax.set_title('3D plot of microstructure')
plt.show(fig)
# plot mesh for macro problem
pb = self.macro_app.problem
coors = pb.domain.mesh.coors
graph = pb.domain.mesh.get_conn(pb.domain.mesh.descs[0])
fig2 = plt.figure(figsize=(5,6))
ax = fig2.add_subplot(111, projection='3d')
for e in range(graph.shape[0]):
tupleList = coors[graph[e,:],:]
vertices = [[0, 1, 2, 3], [4, 5, 6, 7],
[0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]
verts = [[tupleList[vertices[ix][iy]] for iy in range(len(vertices[0]))]
for ix in range(len(vertices))]
pc3d = Poly3DCollection(verts=verts, facecolors='white',
edgecolors='black', linewidths=1, alpha=0.5)
ax.add_collection3d(pc3d)
ax.set_xlim3d(-0.03, 0.03)
ax.set_ylim3d(-0.01, 0.01)
ax.set_zlim3d(-0.01, 0.1)
ax.set_title('3D plot of macro system')
plt.show(fig2)
return None
def mat_eval(self, x):
mic_od = self.micro_app.conf.opt_data
mac_od = self.macro_app.conf.opt_data
mic_od['coefs'] = {}
mic_od['mat_params'] = x_norm2real(x)
self.micro_app()
D = mic_od['D_homog']
comp_k = []
for phi in self.phis:
#print('phi = %d' % phi)
mac_od['D_homog'] = self.rotate_mat(D, np.deg2rad(phi))
self.macro_app()
comp_k.append(mac_od['k'])
# added by Audrey: get a plot of a slice of the mesh
if self.plot_meshes_bool:
self.plot_meshes()
return comp_k
def bounds():
x_L = [120e9, 0.2, 2e9, 0.2]
x_U = [200e9, 0.45, 8e9, 0.45]
return x_L, x_U
def x_norm2real(x):
x_L, x_U = np.array(bounds())
return x * (x_U - x_L) + x_L
def x_real2norm(x):
x_L, x_U = np.array(bounds())
return (x - x_L) / (x_U - x_L)
micro_filename = data_dir + '/examples/homogenization/' + 'homogenization_opt.py'
macro_filename = data_dir + '/examples/homogenization/' + 'linear_elasticity_opt.py'
def one_simulation(x0, plot_meshes_bool=False):
"""
This function is the main callable here: it takes in as input the parameter vector,
here x0=[E_fiber, nu_fiber, E_matrix, nu_matrix], and returns the simulated output
(here slope of the force-elongation curve obtained during a tensile test), to be compared
with the measured data.
"""
x0 = x0.reshape((-1, ))
phis = [0, 30, 60, 90]
#exp_data = zip([0, 30, 60, 90], [1051140., 197330., 101226., 95474.])
ms = MaterialSimulator(macro_filename, micro_filename,
phis,
plot_meshes_bool=plot_meshes_bool)
qoi = ms.mat_eval(x0)
return qoi
def one_simulation_2params(x0, plot_meshes_bool=False):
x0 = x0.reshape((-1, ))
x0 = np.array([x0[0], 0.45, x0[1], 0.])
phis = [0, 30, 60, 90]
#exp_data = zip([0, 30, 60, 90], [1051140., 197330., 101226., 95474.])
ms = MaterialSimulator(macro_filename, micro_filename,
phis, plot_meshes_bool=plot_meshes_bool)
qoi = ms.mat_eval(x0)
return qoi
def one_simulation_2params_rvs(x0, plot_meshes_bool=False):
x0 = x0.reshape((-1, ))
x0 = np.array([x0[0], 0.45, x0[1], 0.])
phis = [0, 30, 60, 90]
ms = MaterialSimulator(macro_filename, micro_filename,
phis,
plot_meshes_bool=plot_meshes_bool)
qoi = ms.mat_eval(x0)
qoi = np.tile(np.array(qoi), 100)
return qoi
| [
"sfepy.base.conf.get_standard_keywords",
"sfepy.base.base.output.set_output",
"sfepy.base.conf.ProblemConf.from_file",
"sfepy.base.base.Struct",
"sfepy.homogenization.homogen_app.HomogenizationApp",
"sfepy.applications.PDESolverApp"
] | [((184, 204), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (199, 204), False, 'import sys\n'), ((7258, 7293), 'numpy.array', 'np.array', (['[x0[0], 0.45, x0[1], 0.0]'], {}), '([x0[0], 0.45, x0[1], 0.0])\n', (7266, 7293), True, 'import numpy as np\n'), ((7662, 7697), 'numpy.array', 'np.array', (['[x0[0], 0.45, x0[1], 0.0]'], {}), '([x0[0], 0.45, x0[1], 0.0])\n', (7670, 7697), True, 'import numpy as np\n'), ((839, 862), 'sfepy.base.conf.get_standard_keywords', 'get_standard_keywords', ([], {}), '()\n', (860, 862), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((941, 1009), 'sfepy.base.conf.ProblemConf.from_file', 'ProblemConf.from_file', (['filename', 'required', 'other'], {'define_args': 'kwargs'}), '(filename, required, other, define_args=kwargs)\n', (962, 1009), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((1065, 1238), 'sfepy.base.base.Struct', 'Struct', ([], {'output_filename_trunk': 'None', 'save_ebc': '(False)', 'save_ebc_nodes': '(False)', 'save_regions': '(False)', 'save_regions_as_groups': '(False)', 'save_field_meshes': '(False)', 'solve_not': '(False)'}), '(output_filename_trunk=None, save_ebc=False, save_ebc_nodes=False,\n save_regions=False, save_regions_as_groups=False, save_field_meshes=\n False, solve_not=False)\n', (1071, 1238), False, 'from sfepy.base.base import Struct, output\n'), ((1415, 1470), 'sfepy.base.base.output.set_output', 'output.set_output', ([], {'filename': '"""sfepy_log.txt"""', 'quiet': '(True)'}), "(filename='sfepy_log.txt', quiet=True)\n", (1432, 1470), False, 'from sfepy.base.base import Struct, output\n'), ((2281, 2294), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (2287, 2294), True, 'import numpy as np\n'), ((2307, 2320), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (2313, 2320), True, 'import numpy as np\n'), ((2388, 2552), 'numpy.array', 'np.array', (['[[c2, 0, s2, 0, 2 * sc, 0], [0, 1, 0, 0, 0, 0], [s2, 0, c2, 0, -2 * sc, 0],\n [0, 0, 0, c, 0, -s], [-sc, 0, sc, 0, c2 - s2, 0], [0, 0, 0, s, 0, c]]'], {}), '([[c2, 0, s2, 0, 2 * sc, 0], [0, 1, 0, 0, 0, 0], [s2, 0, c2, 0, -2 *\n sc, 0], [0, 0, 0, c, 0, -s], [-sc, 0, sc, 0, c2 - s2, 0], [0, 0, 0, s, \n 0, c]])\n', (2396, 2552), True, 'import numpy as np\n'), ((2949, 2978), 'numpy.zeros', 'np.zeros', (['(graph.shape[0], 4)'], {}), '((graph.shape[0], 4))\n', (2957, 2978), True, 'import numpy as np\n'), ((3216, 3243), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 5)'}), '(figsize=(12, 5))\n', (3226, 3243), True, 'import matplotlib.pyplot as plt\n'), ((3293, 3395), 'matplotlib.collections.PolyCollection', 'PolyCollection', ([], {'verts': 'coors[graph[cells_matrix, 0:4], :2]', 'facecolors': '"""white"""', 'edgecolors': '"""black"""'}), "(verts=coors[graph[cells_matrix, 0:4], :2], facecolors=\n 'white', edgecolors='black')\n", (3307, 3395), False, 'from matplotlib.collections import PolyCollection\n'), ((3445, 3545), 'matplotlib.collections.PolyCollection', 'PolyCollection', ([], {'verts': 'coors[graph[cells_fibers, 0:4], :2]', 'facecolors': '"""gray"""', 'edgecolors': '"""black"""'}), "(verts=coors[graph[cells_fibers, 0:4], :2], facecolors='gray',\n edgecolors='black')\n", (3459, 3545), False, 'from matplotlib.collections import PolyCollection\n'), ((4392, 4405), 'matplotlib.pyplot.show', 'plt.show', (['fig'], {}), '(fig)\n', (4400, 4405), True, 'import matplotlib.pyplot as plt\n'), ((4606, 4632), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 6)'}), '(figsize=(5, 6))\n', (4616, 4632), True, 'import matplotlib.pyplot as plt\n'), ((5356, 5370), 'matplotlib.pyplot.show', 'plt.show', (['fig2'], {}), '(fig2)\n', (5364, 5370), True, 'import matplotlib.pyplot as plt\n'), ((7923, 7936), 'numpy.array', 'np.array', (['qoi'], {}), '(qoi)\n', (7931, 7936), True, 'import numpy as np\n'), ((1511, 1566), 'sfepy.homogenization.homogen_app.HomogenizationApp', 'HomogenizationApp', (['conf', 'options', '"""material_opt_micro:"""'], {}), "(conf, options, 'material_opt_micro:')\n", (1528, 1566), False, 'from sfepy.homogenization.homogen_app import HomogenizationApp\n'), ((1600, 1650), 'sfepy.applications.PDESolverApp', 'PDESolverApp', (['conf', 'options', '"""material_opt_macro:"""'], {}), "(conf, options, 'material_opt_macro:')\n", (1612, 1650), False, 'from sfepy.applications import PDESolverApp\n'), ((2672, 2684), 'numpy.dot', 'np.dot', (['T', 'D'], {}), '(T, D)\n', (2678, 2684), True, 'import numpy as np\n'), ((4186, 4282), 'mpl_toolkits.mplot3d.art3d.Poly3DCollection', 'Poly3DCollection', ([], {'verts': 'verts', 'facecolors': 'color', 'edgecolors': '"""black"""', 'linewidths': '(1)', 'alpha': '(0.5)'}), "(verts=verts, facecolors=color, edgecolors='black',\n linewidths=1, alpha=0.5)\n", (4202, 4282), False, 'from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection\n'), ((5046, 5144), 'mpl_toolkits.mplot3d.art3d.Poly3DCollection', 'Poly3DCollection', ([], {'verts': 'verts', 'facecolors': '"""white"""', 'edgecolors': '"""black"""', 'linewidths': '(1)', 'alpha': '(0.5)'}), "(verts=verts, facecolors='white', edgecolors='black',\n linewidths=1, alpha=0.5)\n", (5062, 5144), False, 'from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection\n'), ((5782, 5797), 'numpy.deg2rad', 'np.deg2rad', (['phi'], {}), '(phi)\n', (5792, 5797), True, 'import numpy as np\n')] |
"""
Linearization of higher order solutions for the purposes of visualization.
"""
from __future__ import absolute_import
import numpy as nm
from sfepy.linalg import dot_sequences
from sfepy.discrete.fem.refine import refine_reference
from six.moves import range
def get_eval_dofs(dofs, dof_conn, ps, ori=None):
"""
Get default function for evaluating field DOFs given a list of elements and
reference element coordinates.
"""
def _eval(iels, rx):
edofs = dofs[dof_conn[iels]]
if ori is not None:
eori = ori[iels]
else:
eori = None
bf = ps.eval_base(rx, ori=eori, force_axis=True)[...,0,:]
rvals = dot_sequences(bf, edofs)
return rvals
return _eval
def get_eval_coors(coors, conn, ps):
"""
Get default function for evaluating physical coordinates given a list of
elements and reference element coordinates.
"""
def _eval(iels, rx):
ecoors = coors[conn[iels]]
aux = ecoors.transpose((0, 2, 1))
bf = ps.eval_base(rx).squeeze()
phys_coors = nm.dot(aux, bf.T).transpose((0, 2, 1))
return phys_coors
return _eval
def create_output(eval_dofs, eval_coors, n_el, ps, min_level=0, max_level=2,
eps=1e-4):
"""
Create mesh with linear elements that approximates DOFs returned by
`eval_dofs()` corresponding to a higher order approximation with a relative
precision given by `eps`. The DOFs are evaluated in physical coordinates
returned by `eval_coors()`.
"""
def _get_msd(iels, rx, ree):
rvals = eval_dofs(iels, rx)
rng = rvals.max() - rvals.min()
n_components = rvals.shape[-1]
msd = 0.0
for ic in range(n_components):
rval = rvals[..., ic]
sd = rval[:, ree]
# ~ max. second derivative.
msd += nm.abs(sd[..., 0] + sd[..., 2]
- 2.0 * sd[..., 1]).max(axis=-1)
msd /= n_components
return msd, rng
rx0 = ps.geometry.coors
rc0 = ps.geometry.conn[None, :]
rx, rc, ree = refine_reference(ps.geometry, 1)
factor = rc.shape[0] / rc0.shape[0]
iels = nm.arange(n_el)
msd, rng = _get_msd(iels, rx, ree)
eps_r = rng * eps
flag = msd > eps_r
iels0 = flag0 = None
coors = []
conns = []
vdofs = []
inod = 0
for level in range(max_level + 1):
if level < min_level:
flag.fill(True) # Force refinement everywhere.
elif level == max_level:
# Last level - take everything.
flag.fill(False)
# Deal with finished elements.
if flag0 is not None:
ii = nm.searchsorted(iels0, iels)
expand_flag0 = flag0[ii].repeat(factor, axis=1)
else:
expand_flag0 = nm.ones_like(flag)
ie, ir = nm.where((flag == False) & (expand_flag0 == True))
if len(ie):
uie, iies = nm.unique(ie, return_inverse=True)
# Each (sub-)element has own coordinates - no shared vertices.
xes = eval_coors(iels[uie], rx0)
des = eval_dofs(iels[uie], rx0)
# Vectorize (how??) or use cython?
cc = []
vd = []
for ii, iie in enumerate(iies):
ce = rc0[ir[ii]]
xe = xes[iie]
cc.append(xe[ce])
de = des[iie]
vd.append(de[ce])
cc = nm.vstack(cc)
vd = nm.vstack(vd)
nc = cc.shape[0]
np = rc0.shape[1]
conn = nm.arange(nc, dtype=nm.int32).reshape((nc // np, np))
coors.append(cc)
conns.append(conn + inod)
vdofs.append(vd)
inod += nc
if not flag.any():
break
iels0 = iels
flag0 = flag
# Deal with elements to refine.
if level < max_level:
eflag = flag.sum(axis=1, dtype=nm.bool)
iels = iels[eflag]
rc0 = rc
rx0 = rx
rx, rc, ree = refine_reference(ps.geometry, level + 2)
msd, rng = _get_msd(iels, rx, ree)
eps_r = rng * eps
flag = msd > eps_r
all_coors = nm.concatenate(coors, axis=0)
conn = nm.concatenate(conns, axis=0)
all_vdofs = nm.concatenate(vdofs, axis=0)
mat_ids = nm.zeros(conn.shape[0], dtype=nm.int32)
return level, all_coors, conn, all_vdofs, mat_ids
| [
"sfepy.linalg.dot_sequences",
"sfepy.discrete.fem.refine.refine_reference"
] | [((2121, 2153), 'sfepy.discrete.fem.refine.refine_reference', 'refine_reference', (['ps.geometry', '(1)'], {}), '(ps.geometry, 1)\n', (2137, 2153), False, 'from sfepy.discrete.fem.refine import refine_reference\n'), ((2207, 2222), 'numpy.arange', 'nm.arange', (['n_el'], {}), '(n_el)\n', (2216, 2222), True, 'import numpy as nm\n'), ((2410, 2430), 'six.moves.range', 'range', (['(max_level + 1)'], {}), '(max_level + 1)\n', (2415, 2430), False, 'from six.moves import range\n'), ((4269, 4298), 'numpy.concatenate', 'nm.concatenate', (['coors'], {'axis': '(0)'}), '(coors, axis=0)\n', (4283, 4298), True, 'import numpy as nm\n'), ((4310, 4339), 'numpy.concatenate', 'nm.concatenate', (['conns'], {'axis': '(0)'}), '(conns, axis=0)\n', (4324, 4339), True, 'import numpy as nm\n'), ((4356, 4385), 'numpy.concatenate', 'nm.concatenate', (['vdofs'], {'axis': '(0)'}), '(vdofs, axis=0)\n', (4370, 4385), True, 'import numpy as nm\n'), ((4401, 4440), 'numpy.zeros', 'nm.zeros', (['conn.shape[0]'], {'dtype': 'nm.int32'}), '(conn.shape[0], dtype=nm.int32)\n', (4409, 4440), True, 'import numpy as nm\n'), ((687, 711), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['bf', 'edofs'], {}), '(bf, edofs)\n', (700, 711), False, 'from sfepy.linalg import dot_sequences\n'), ((1748, 1767), 'six.moves.range', 'range', (['n_components'], {}), '(n_components)\n', (1753, 1767), False, 'from six.moves import range\n'), ((2883, 2933), 'numpy.where', 'nm.where', (['((flag == False) & (expand_flag0 == True))'], {}), '((flag == False) & (expand_flag0 == True))\n', (2891, 2933), True, 'import numpy as nm\n'), ((2715, 2743), 'numpy.searchsorted', 'nm.searchsorted', (['iels0', 'iels'], {}), '(iels0, iels)\n', (2730, 2743), True, 'import numpy as nm\n'), ((2846, 2864), 'numpy.ones_like', 'nm.ones_like', (['flag'], {}), '(flag)\n', (2858, 2864), True, 'import numpy as nm\n'), ((2978, 3012), 'numpy.unique', 'nm.unique', (['ie'], {'return_inverse': '(True)'}), '(ie, return_inverse=True)\n', (2987, 3012), True, 'import numpy as nm\n'), ((3491, 3504), 'numpy.vstack', 'nm.vstack', (['cc'], {}), '(cc)\n', (3500, 3504), True, 'import numpy as nm\n'), ((3522, 3535), 'numpy.vstack', 'nm.vstack', (['vd'], {}), '(vd)\n', (3531, 3535), True, 'import numpy as nm\n'), ((4102, 4142), 'sfepy.discrete.fem.refine.refine_reference', 'refine_reference', (['ps.geometry', '(level + 2)'], {}), '(ps.geometry, level + 2)\n', (4118, 4142), False, 'from sfepy.discrete.fem.refine import refine_reference\n'), ((1095, 1112), 'numpy.dot', 'nm.dot', (['aux', 'bf.T'], {}), '(aux, bf.T)\n', (1101, 1112), True, 'import numpy as nm\n'), ((1893, 1943), 'numpy.abs', 'nm.abs', (['(sd[..., 0] + sd[..., 2] - 2.0 * sd[..., 1])'], {}), '(sd[..., 0] + sd[..., 2] - 2.0 * sd[..., 1])\n', (1899, 1943), True, 'import numpy as nm\n'), ((3615, 3644), 'numpy.arange', 'nm.arange', (['nc'], {'dtype': 'nm.int32'}), '(nc, dtype=nm.int32)\n', (3624, 3644), True, 'import numpy as nm\n')] |
#!/usr/bin/env python
# 12.01.2007, c
"""
Solve partial differential equations given in a SfePy problem definition file.
Example problem definition files can be found in ``examples/`` directory of the
SfePy top-level directory. This script works with all the examples except those
in ``examples/standalone/``.
Both normal and parametric study runs are supported. A parametric study allows
repeated runs for varying some of the simulation parameters - see
``examples/diffusion/poisson_parametric_study.py`` file.
"""
from __future__ import print_function
from __future__ import absolute_import
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import sfepy
from sfepy.base.base import output
from sfepy.base.conf import ProblemConf, get_standard_keywords
from sfepy.applications import PDESolverApp
def print_terms():
import sfepy.terms as t
tt = t.term_table
print('Terms: %d available:' % len(tt))
print(sorted(tt.keys()))
def print_solvers():
from sfepy.solvers import solver_table
print('Solvers: %d available:' % len(solver_table))
print(sorted(solver_table.keys()))
helps = {
'debug':
'automatically start debugger when an exception is raised',
'conf' :
'override problem description file items, written as python'
' dictionary without surrounding braces',
'options' : 'override options item of problem description,'
' written as python dictionary without surrounding braces',
'define' : 'pass given arguments written as python dictionary'
' without surrounding braces to define() function of problem description'
' file',
'filename' :
'basename of output file(s) [default: <basename of input file>]',
'output_format' :
'output file format, one of: {vtk, h5} [default: vtk]',
'save_restart' :
'if given, save restart files according to the given mode.',
'load_restart' :
'if given, load the given restart file',
'log' :
'log all messages to specified file (existing file will be overwritten!)',
'quiet' :
'do not print any messages to screen',
'save_ebc' :
'save a zero solution with applied EBCs (Dirichlet boundary conditions)',
'save_ebc_nodes' :
'save a zero solution with added non-zeros in EBC (Dirichlet boundary'
' conditions) nodes - scalar variables are shown using colors,'
' vector variables using arrows with non-zero components corresponding'
' to constrained components',
'save_regions' :
'save problem regions as meshes',
'save_regions_as_groups' :
'save problem regions in a single mesh but mark them by using different'
' element/node group numbers',
'save_field_meshes' :
'save meshes of problem fields (with extra DOF nodes)',
'solve_not' :
'do not solve (use in connection with --save-*)',
'list' :
'list data, what can be one of: {terms, solvers}',
}
def main():
parser = ArgumentParser(description=__doc__,
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('--version', action='version',
version='%(prog)s ' + sfepy.__version__)
parser.add_argument('--debug',
action='store_true', dest='debug',
default=False, help=helps['debug'])
parser.add_argument('-c', '--conf', metavar='"key : value, ..."',
action='store', dest='conf', type=str,
default=None, help= helps['conf'])
parser.add_argument('-O', '--options', metavar='"key : value, ..."',
action='store', dest='app_options', type=str,
default=None, help=helps['options'])
parser.add_argument('-d', '--define', metavar='"key : value, ..."',
action='store', dest='define_args', type=str,
default=None, help=helps['define'])
parser.add_argument('-o', metavar='filename',
action='store', dest='output_filename_trunk',
default=None, help=helps['filename'])
parser.add_argument('--format', metavar='format',
action='store', dest='output_format',
default=None, help=helps['output_format'])
parser.add_argument('--save-restart', metavar='mode', type=int,
action='store', dest='save_restart',
default=None, help=helps['save_restart'])
parser.add_argument('--load-restart', metavar='filename',
action='store', dest='load_restart',
default=None, help=helps['load_restart'])
parser.add_argument('--log', metavar='file',
action='store', dest='log',
default=None, help=helps['log'])
parser.add_argument('-q', '--quiet',
action='store_true', dest='quiet',
default=False, help=helps['quiet'])
parser.add_argument('--save-ebc',
action='store_true', dest='save_ebc',
default=False, help=helps['save_ebc'])
parser.add_argument('--save-ebc-nodes',
action='store_true', dest='save_ebc_nodes',
default=False, help=helps['save_ebc_nodes'])
parser.add_argument('--save-regions',
action='store_true', dest='save_regions',
default=False, help=helps['save_regions'])
parser.add_argument('--save-regions-as-groups',
action='store_true', dest='save_regions_as_groups',
default=False, help=helps['save_regions_as_groups'])
parser.add_argument('--save-field-meshes',
action='store_true', dest='save_field_meshes',
default=False, help=helps['save_field_meshes'])
parser.add_argument('--solve-not',
action='store_true', dest='solve_not',
default=False, help=helps['solve_not'])
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--list', metavar='what',
action='store', dest='_list',
default=None, help=helps['list'])
group.add_argument('filename_in', nargs='?')
options, petsc_opts = parser.parse_known_args()
if options._list is not None:
if options._list == 'terms':
print_terms()
elif options._list == 'solvers':
print_solvers()
return
if options.debug:
from sfepy.base.base import debug_on_error; debug_on_error()
filename_in = options.filename_in
output.set_output(filename=options.log,
quiet=options.quiet,
combined=options.log is not None)
required, other = get_standard_keywords()
if options.solve_not:
required.remove('equations')
required.remove('solver_[0-9]+|solvers')
other.extend(['equations'])
conf = ProblemConf.from_file_and_options(filename_in, options,
required, other,
define_args=options.define_args)
opts = conf.options
output_prefix = opts.get('output_prefix', 'sfepy:')
opts.save_restart = options.save_restart
opts.load_restart = options.load_restart
app = PDESolverApp(conf, options, output_prefix)
if hasattr(opts, 'parametric_hook'): # Parametric study.
parametric_hook = conf.get_function(opts.parametric_hook)
app.parametrize(parametric_hook)
app()
if __name__ == '__main__':
main()
| [
"sfepy.base.conf.get_standard_keywords",
"sfepy.solvers.solver_table.keys",
"sfepy.base.conf.ProblemConf.from_file_and_options",
"sfepy.base.base.output.set_output",
"sfepy.applications.PDESolverApp",
"sfepy.base.base.debug_on_error"
] | [((2913, 2998), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '__doc__', 'formatter_class': 'RawDescriptionHelpFormatter'}), '(description=__doc__, formatter_class=RawDescriptionHelpFormatter\n )\n', (2927, 2998), False, 'from argparse import ArgumentParser, RawDescriptionHelpFormatter\n'), ((6685, 6784), 'sfepy.base.base.output.set_output', 'output.set_output', ([], {'filename': 'options.log', 'quiet': 'options.quiet', 'combined': '(options.log is not None)'}), '(filename=options.log, quiet=options.quiet, combined=\n options.log is not None)\n', (6702, 6784), False, 'from sfepy.base.base import output\n'), ((6847, 6870), 'sfepy.base.conf.get_standard_keywords', 'get_standard_keywords', ([], {}), '()\n', (6868, 6870), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((7031, 7140), 'sfepy.base.conf.ProblemConf.from_file_and_options', 'ProblemConf.from_file_and_options', (['filename_in', 'options', 'required', 'other'], {'define_args': 'options.define_args'}), '(filename_in, options, required, other,\n define_args=options.define_args)\n', (7064, 7140), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((7410, 7452), 'sfepy.applications.PDESolverApp', 'PDESolverApp', (['conf', 'options', 'output_prefix'], {}), '(conf, options, output_prefix)\n', (7422, 7452), False, 'from sfepy.applications import PDESolverApp\n'), ((6625, 6641), 'sfepy.base.base.debug_on_error', 'debug_on_error', ([], {}), '()\n', (6639, 6641), False, 'from sfepy.base.base import debug_on_error\n'), ((1097, 1116), 'sfepy.solvers.solver_table.keys', 'solver_table.keys', ([], {}), '()\n', (1114, 1116), False, 'from sfepy.solvers import solver_table\n')] |
r"""
Incompressible Stokes flow with Navier (slip) boundary conditions, flow driven
by a moving wall and a small diffusion for stabilization.
This example demonstrates the use of `no-penetration` and `edge direction`
boundary conditions together with Navier or slip boundary conditions.
Alternatively the `no-penetration` boundary conditions can be applied in a weak
sense using the penalty term ``dw_non_penetration_p``.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}
- \int_{\Omega} p\ \nabla \cdot \ul{v}
+ \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d)
+ \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u}
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} \mu \nabla q \cdot \nabla p
+ \int_{\Omega} q\ \nabla \cdot \ul{u}
= 0
\;, \quad \forall q \;,
where :math:`\nu` is the fluid viscosity, :math:`\beta` is the slip
coefficient, :math:`\mu` is the (small) numerical diffusion coefficient,
:math:`\Gamma_1` is the top wall that moves with the given driving velocity
:math:`\ul{u}_d` and :math:`\Gamma_2` are the remaining walls. The Navier
conditions are in effect on both :math:`\Gamma_1`, :math:`\Gamma_2` and are
expressed by the corresponding integrals in the equations above.
The `no-penetration` boundary conditions are applied on :math:`\Gamma_1`,
:math:`\Gamma_2`, except the vertices of the block edges, where the `edge
direction` boundary conditions are applied.
The penalty term formulation is given by the following equations.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}
- \int_{\Omega} p\ \nabla \cdot \ul{v}
+ \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d)
+ \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u}
+ \int_{\Gamma_1 \cup \Gamma_2} \epsilon (\ul{n} \cdot \ul{v})
(\ul{n} \cdot \ul{u})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} \mu \nabla q \cdot \nabla p
+ \int_{\Omega} q\ \nabla \cdot \ul{u}
= 0
\;, \quad \forall q \;,
where :math:`\epsilon` is the penalty coefficient (sufficiently large). The
`no-penetration` boundary conditions are applied on :math:`\Gamma_1`,
:math:`\Gamma_2`.
Optionally, Dirichlet boundary conditions can be applied on
the inlet in the both cases, see below.
For large meshes use the ``'ls_i'`` linear solver - PETSc + petsc4py are needed
in that case.
Several parameters can be set using the ``--define`` option of ``simple.py``,
see :func:`define()` and the examples below.
Examples
--------
Specify the inlet velocity and a finer mesh::
python3 simple.py examples/navier_stokes/stokes_slip_bc -d shape="(11,31,31),u_inlet=0.5"
python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk
Use the penalty term formulation and einsum-based terms with the default
(numpy) backend::
python3 simple.py examples/navier_stokes/stokes_slip_bc -d "mode=penalty,term_mode=einsum"
python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk
Change backend to opt_einsum (needs to be installed) and use the quadratic velocity approximation order::
python3 simple.py examples/navier_stokes/stokes_slip_bc -d "u_order=2,mode=penalty,term_mode=einsum,backend=opt_einsum,optimize=auto"
python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk
Note the pressure field distribution improvement w.r.t. the previous examples. IfPETSc + petsc4py are installed, try using the iterative solver to speed up the solution::
python3 simple.py examples/navier_stokes/stokes_slip_bc -d "u_order=2,ls=ls_i,mode=penalty,term_mode=einsum,backend=opt_einsum,optimize=auto"
python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk
"""
from __future__ import absolute_import
import numpy as nm
from sfepy.base.base import assert_, output
from sfepy.discrete.fem.meshio import UserMeshIO
from sfepy.mesh.mesh_generators import gen_block_mesh
from sfepy.homogenization.utils import define_box_regions
def define(dims=(3, 1, 0.5), shape=(11, 15, 15), u_order=1, refine=0,
ls='ls_d', u_inlet=None, mode='lcbc', term_mode='original',
backend='numpy', optimize='optimal', verbosity=0):
"""
Parameters
----------
dims : tuple
The block domain dimensions.
shape : tuple
The mesh resolution: increase to improve accuracy.
u_order : int
The velocity field approximation order.
refine : int
The refinement level.
ls : 'ls_d' or 'ls_i'
The pre-configured linear solver name.
u_inlet : float, optional
The x-component of the inlet velocity.
mode : 'lcbc' or 'penalty'
The alternative formulations.
term_mode : 'original' or 'einsum'
The switch to use either the original or new experimental einsum-based
terms.
backend : str
The einsum mode backend.
optimize : str
The einsum mode optimization (backend dependent).
verbosity : 0, 1, 2, 3
The verbosity level of einsum-based terms.
"""
output('dims: {}, shape: {}, u_order: {}, refine: {}, u_inlet: {}'
.format(dims, shape, u_order, refine, u_inlet))
output('linear solver: {}'.format(ls))
output('mode: {}, term_mode: {}'.format(mode, term_mode))
if term_mode == 'einsum':
output('backend: {}, optimize: {}, verbosity: {}'
.format(backend, optimize, verbosity))
assert_(mode in {'lcbc', 'penalty'})
assert_(term_mode in {'original', 'einsum'})
if u_order > 1:
assert_(mode == 'penalty', msg='set mode=penalty to use u_order > 1!')
dims = nm.array(dims, dtype=nm.float64)
shape = nm.array(shape, dtype=nm.int32)
def mesh_hook(mesh, mode):
"""
Generate the block mesh.
"""
if mode == 'read':
mesh = gen_block_mesh(dims, shape, [0, 0, 0], name='user_block',
verbose=False)
return mesh
elif mode == 'write':
pass
filename_mesh = UserMeshIO(mesh_hook)
regions = define_box_regions(3, 0.5 * dims)
regions.update({
'Omega' : 'all',
'Edges_v' : ("""(r.Near *v r.Bottom) +v
(r.Bottom *v r.Far) +v
(r.Far *v r.Top) +v
(r.Top *v r.Near)""", 'edge'),
'Gamma1_f' : ('copy r.Top', 'face'),
'Gamma2_f' : ('r.Near +v r.Bottom +v r.Far', 'face'),
'Gamma_f' : ('r.Gamma1_f +v r.Gamma2_f', 'face'),
'Gamma_v' : ('r.Gamma_f -v r.Edges_v', 'face'),
'Inlet_f' : ('r.Left -v r.Gamma_f', 'face'),
})
fields = {
'velocity' : ('real', 3, 'Omega', u_order),
'pressure' : ('real', 1, 'Omega', 1),
}
def get_u_d(ts, coors, region=None):
"""
Given stator velocity.
"""
out = nm.zeros_like(coors)
out[:] = [1.0, 1.0, 0.0]
return out
functions = {
'get_u_d' : (get_u_d,),
}
variables = {
'u' : ('unknown field', 'velocity', 0),
'v' : ('test field', 'velocity', 'u'),
'u_d' : ('parameter field', 'velocity',
{'setter' : 'get_u_d'}),
'p' : ('unknown field', 'pressure', 1),
'q' : ('test field', 'pressure', 'p'),
}
materials = {
'm' : ({
'nu' : 1e-3,
'beta' : 1e-2,
'mu' : 1e-10,
},),
}
ebcs = {
}
if u_inlet is not None:
ebcs['inlet'] = ('Inlet_f', {'u.0' : u_inlet, 'u.[1, 2]' : 0.0})
if mode == 'lcbc':
lcbcs = {
'walls' : ('Gamma_v', {'u.all' : None}, None, 'no_penetration',
'normals_Gamma.vtk'),
'edges' : ('Edges_v', [(-0.5, 1.5)], {'u.all' : None}, None,
'edge_direction', 'edges_Edges.vtk'),
}
if term_mode == 'original':
equations = {
'balance' :
"""dw_div_grad.5.Omega(m.nu, v, u)
- dw_stokes.5.Omega(v, p)
+ dw_dot.5.Gamma1_f(m.beta, v, u)
+ dw_dot.5.Gamma2_f(m.beta, v, u)
=
+ dw_dot.5.Gamma1_f(m.beta, v, u_d)""",
'incompressibility' :
"""dw_laplace.5.Omega(m.mu, q, p)
+ dw_stokes.5.Omega(u, q) = 0""",
}
else:
equations = {
'balance' :
"""de_div_grad.5.Omega(m.nu, v, u)
- de_stokes.5.Omega(v, p)
+ de_dot.5.Gamma1_f(m.beta, v, u)
+ de_dot.5.Gamma2_f(m.beta, v, u)
=
+ de_dot.5.Gamma1_f(m.beta, v, u_d)""",
'incompressibility' :
"""de_laplace.5.Omega(m.mu, q, p)
+ de_stokes.5.Omega(u, q) = 0""",
}
else:
materials['m'][0]['np_eps'] = 1e3
if term_mode == 'original':
equations = {
'balance' :
"""dw_div_grad.5.Omega(m.nu, v, u)
- dw_stokes.5.Omega(v, p)
+ dw_dot.5.Gamma1_f(m.beta, v, u)
+ dw_dot.5.Gamma2_f(m.beta, v, u)
+ dw_non_penetration_p.5.Gamma1_f(m.np_eps, v, u)
+ dw_non_penetration_p.5.Gamma2_f(m.np_eps, v, u)
=
+ dw_dot.5.Gamma1_f(m.beta, v, u_d)""",
'incompressibility' :
"""dw_laplace.5.Omega(m.mu, q, p)
+ dw_stokes.5.Omega(u, q) = 0""",
}
else:
equations = {
'balance' :
"""de_div_grad.5.Omega(m.nu, v, u)
- de_stokes.5.Omega(v, p)
+ de_dot.5.Gamma1_f(m.beta, v, u)
+ de_dot.5.Gamma2_f(m.beta, v, u)
+ de_non_penetration_p.5.Gamma1_f(m.np_eps, v, u)
+ de_non_penetration_p.5.Gamma2_f(m.np_eps, v, u)
=
+ de_dot.5.Gamma1_f(m.beta, v, u_d)""",
'incompressibility' :
"""de_laplace.5.Omega(m.mu, q, p)
+ de_stokes.5.Omega(u, q) = 0""",
}
solvers = {
'ls_d' : ('ls.auto_direct', {}),
'ls_i' : ('ls.petsc', {
'method' : 'bcgsl', # ksp_type
'precond' : 'bjacobi', # pc_type
'sub_precond' : 'ilu', # sub_pc_type
'eps_a' : 0.0, # abstol
'eps_r' : 1e-12, # rtol
'eps_d' : 1e10, # Divergence tolerance.
'i_max' : 200, # maxits
}),
'newton' : ('nls.newton', {
'i_max' : 1,
'eps_a' : 1e-10,
}),
}
options = {
'nls' : 'newton',
'ls' : ls,
'eterm': {
'verbosity' : verbosity,
'backend_args' : {
'backend' : backend,
'optimize' : optimize,
'layout' : None,
},
},
'refinement_level' : refine,
}
return locals()
| [
"sfepy.base.base.assert_",
"sfepy.discrete.fem.meshio.UserMeshIO",
"sfepy.homogenization.utils.define_box_regions",
"sfepy.mesh.mesh_generators.gen_block_mesh"
] | [((5428, 5464), 'sfepy.base.base.assert_', 'assert_', (["(mode in {'lcbc', 'penalty'})"], {}), "(mode in {'lcbc', 'penalty'})\n", (5435, 5464), False, 'from sfepy.base.base import assert_, output\n'), ((5469, 5513), 'sfepy.base.base.assert_', 'assert_', (["(term_mode in {'original', 'einsum'})"], {}), "(term_mode in {'original', 'einsum'})\n", (5476, 5513), False, 'from sfepy.base.base import assert_, output\n'), ((5624, 5656), 'numpy.array', 'nm.array', (['dims'], {'dtype': 'nm.float64'}), '(dims, dtype=nm.float64)\n', (5632, 5656), True, 'import numpy as nm\n'), ((5669, 5700), 'numpy.array', 'nm.array', (['shape'], {'dtype': 'nm.int32'}), '(shape, dtype=nm.int32)\n', (5677, 5700), True, 'import numpy as nm\n'), ((6036, 6057), 'sfepy.discrete.fem.meshio.UserMeshIO', 'UserMeshIO', (['mesh_hook'], {}), '(mesh_hook)\n', (6046, 6057), False, 'from sfepy.discrete.fem.meshio import UserMeshIO\n'), ((6073, 6106), 'sfepy.homogenization.utils.define_box_regions', 'define_box_regions', (['(3)', '(0.5 * dims)'], {}), '(3, 0.5 * dims)\n', (6091, 6106), False, 'from sfepy.homogenization.utils import define_box_regions\n'), ((5542, 5612), 'sfepy.base.base.assert_', 'assert_', (["(mode == 'penalty')"], {'msg': '"""set mode=penalty to use u_order > 1!"""'}), "(mode == 'penalty', msg='set mode=penalty to use u_order > 1!')\n", (5549, 5612), False, 'from sfepy.base.base import assert_, output\n'), ((6859, 6879), 'numpy.zeros_like', 'nm.zeros_like', (['coors'], {}), '(coors)\n', (6872, 6879), True, 'import numpy as nm\n'), ((5836, 5908), 'sfepy.mesh.mesh_generators.gen_block_mesh', 'gen_block_mesh', (['dims', 'shape', '[0, 0, 0]'], {'name': '"""user_block"""', 'verbose': '(False)'}), "(dims, shape, [0, 0, 0], name='user_block', verbose=False)\n", (5850, 5908), False, 'from sfepy.mesh.mesh_generators import gen_block_mesh\n')] |
#!/usr/bin/env python
"""
Diametrically point loaded 2-D disk, using commands for interactive use. See
:ref:`sec-primer`.
The script combines the functionality of all the ``its2D_?.py`` examples and
allows setting various simulation parameters, namely:
- material parameters
- displacement field approximation order
- uniform mesh refinement level
The example shows also how to probe the results as in
:ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi.
Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the
approximation order greater than one.
In the SfePy top-level directory the following command can be used to get usage
information::
python examples/linear_elasticity/its2D_interactive.py -h
Notes
-----
The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and
Matplotlib use the same backend type (for example wx).
"""
from __future__ import absolute_import
import sys
from six.moves import range
sys.path.append('.')
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import numpy as nm
import matplotlib.pyplot as plt
from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct
from sfepy.discrete import (FieldVariable, Material, Integral, Integrals,
Equation, Equations, Problem)
from sfepy.discrete.fem import Mesh, FEDomain, Field
from sfepy.terms import Term
from sfepy.discrete.conditions import Conditions, EssentialBC
from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson
from sfepy.solvers.ls import ScipyDirect
from sfepy.solvers.nls import Newton
from sfepy.discrete.fem.geometry_element import geometry_data
from sfepy.discrete.probes import LineProbe
from sfepy.discrete.projections import project_by_component
from examples.linear_elasticity.its2D_2 import stress_strain
from examples.linear_elasticity.its2D_3 import nodal_stress
def gen_lines(problem):
"""
Define two line probes.
Additional probes can be added by appending to `ps0` (start points) and
`ps1` (end points) lists.
"""
ps0 = [[0.0, 0.0], [0.0, 0.0]]
ps1 = [[75.0, 0.0], [0.0, 75.0]]
# Use enough points for higher order approximations.
n_point = 1000
labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)]
probes = []
for ip in range(len(ps0)):
p0, p1 = ps0[ip], ps1[ip]
probes.append(LineProbe(p0, p1, n_point))
return probes, labels
def probe_results(u, strain, stress, probe, label):
"""
Probe the results using the given probe and plot the probed values.
"""
results = {}
pars, vals = probe(u)
results['u'] = (pars, vals)
pars, vals = probe(strain)
results['cauchy_strain'] = (pars, vals)
pars, vals = probe(stress)
results['cauchy_stress'] = (pars, vals)
fig = plt.figure()
plt.clf()
fig.subplots_adjust(hspace=0.4)
plt.subplot(311)
pars, vals = results['u']
for ic in range(vals.shape[1]):
plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1),
lw=1, ls='-', marker='+', ms=3)
plt.ylabel('displacements')
plt.xlabel('probe %s' % label, fontsize=8)
plt.legend(loc='best', fontsize=10)
sym_indices = ['11', '22', '12']
plt.subplot(312)
pars, vals = results['cauchy_strain']
for ic in range(vals.shape[1]):
plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic],
lw=1, ls='-', marker='+', ms=3)
plt.ylabel('Cauchy strain')
plt.xlabel('probe %s' % label, fontsize=8)
plt.legend(loc='best', fontsize=10)
plt.subplot(313)
pars, vals = results['cauchy_stress']
for ic in range(vals.shape[1]):
plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic],
lw=1, ls='-', marker='+', ms=3)
plt.ylabel('Cauchy stress')
plt.xlabel('probe %s' % label, fontsize=8)
plt.legend(loc='best', fontsize=10)
return fig, results
helps = {
'young' : "the Young's modulus [default: %(default)s]",
'poisson' : "the Poisson's ratio [default: %(default)s]",
'load' : "the vertical load value (negative means compression)"
" [default: %(default)s]",
'order' : 'displacement field approximation order [default: %(default)s]',
'refine' : 'uniform mesh refinement level [default: %(default)s]',
'probe' : 'probe the results',
'show' : 'show the results figure',
}
def main():
from sfepy import data_dir
parser = ArgumentParser(description=__doc__,
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('--version', action='version', version='%(prog)s')
parser.add_argument('--young', metavar='float', type=float,
action='store', dest='young',
default=2000.0, help=helps['young'])
parser.add_argument('--poisson', metavar='float', type=float,
action='store', dest='poisson',
default=0.4, help=helps['poisson'])
parser.add_argument('--load', metavar='float', type=float,
action='store', dest='load',
default=-1000.0, help=helps['load'])
parser.add_argument('--order', metavar='int', type=int,
action='store', dest='order',
default=1, help=helps['order'])
parser.add_argument('-r', '--refine', metavar='int', type=int,
action='store', dest='refine',
default=0, help=helps['refine'])
parser.add_argument('-s', '--show',
action="store_true", dest='show',
default=False, help=helps['show'])
parser.add_argument('-p', '--probe',
action="store_true", dest='probe',
default=False, help=helps['probe'])
options = parser.parse_args()
assert_((0.0 < options.poisson < 0.5),
"Poisson's ratio must be in ]0, 0.5[!")
assert_((0 < options.order),
'displacement approximation order must be at least 1!')
output('using values:')
output(" Young's modulus:", options.young)
output(" Poisson's ratio:", options.poisson)
output(' vertical load:', options.load)
output('uniform mesh refinement level:', options.refine)
# Build the problem definition.
mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh')
domain = FEDomain('domain', mesh)
if options.refine > 0:
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))
omega = domain.create_region('Omega', 'all')
left = domain.create_region('Left',
'vertices in x < 0.001', 'facet')
bottom = domain.create_region('Bottom',
'vertices in y < 0.001', 'facet')
top = domain.create_region('Top', 'vertex 2', 'vertex')
field = Field.from_args('fu', nm.float64, 'vector', omega,
approx_order=options.order)
u = FieldVariable('u', 'unknown', field)
v = FieldVariable('v', 'test', field, primary_var_name='u')
D = stiffness_from_youngpoisson(2, options.young, options.poisson)
asphalt = Material('Asphalt', D=D)
load = Material('Load', values={'.val' : [0.0, options.load]})
integral = Integral('i', order=2*options.order)
integral0 = Integral('i', order=0)
t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)',
integral, omega, Asphalt=asphalt, v=v, u=u)
t2 = Term.new('dw_point_load(Load.val, v)',
integral0, top, Load=load, v=v)
eq = Equation('balance', t1 - t2)
eqs = Equations([eq])
xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0})
ysym = EssentialBC('YSym', left, {'u.0' : 0.0})
ls = ScipyDirect({})
nls_status = IndexedStruct()
nls = Newton({}, lin_solver=ls, status=nls_status)
pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls)
pb.time_update(ebcs=Conditions([xsym, ysym]))
# Solve the problem.
state = pb.solve()
output(nls_status)
# Postprocess the solution.
out = state.create_output_dict()
out = stress_strain(out, pb, state, extend=True)
pb.save_state('its2D_interactive.vtk', out=out)
gdata = geometry_data['2_3']
nc = len(gdata.coors)
integral_vn = Integral('ivn', coors=gdata.coors,
weights=[gdata.volume / nc] * nc)
nodal_stress(out, pb, state, integrals=Integrals([integral_vn]))
if options.probe:
# Probe the solution.
probes, labels = gen_lines(pb)
sfield = Field.from_args('sym_tensor', nm.float64, 3, omega,
approx_order=options.order - 1)
stress = FieldVariable('stress', 'parameter', sfield,
primary_var_name='(set-to-None)')
strain = FieldVariable('strain', 'parameter', sfield,
primary_var_name='(set-to-None)')
cfield = Field.from_args('component', nm.float64, 1, omega,
approx_order=options.order - 1)
component = FieldVariable('component', 'parameter', cfield,
primary_var_name='(set-to-None)')
ev = pb.evaluate
order = 2 * (options.order - 1)
strain_qp = ev('ev_cauchy_strain.%d.Omega(u)' % order, mode='qp')
stress_qp = ev('ev_cauchy_stress.%d.Omega(Asphalt.D, u)' % order,
mode='qp', copy_materials=False)
project_by_component(strain, strain_qp, component, order)
project_by_component(stress, stress_qp, component, order)
all_results = []
for ii, probe in enumerate(probes):
fig, results = probe_results(u, strain, stress, probe, labels[ii])
fig.savefig('its2D_interactive_probe_%d.png' % ii)
all_results.append(results)
for ii, results in enumerate(all_results):
output('probe %d:' % ii)
output.level += 2
for key, res in ordered_iteritems(results):
output(key + ':')
val = res[1]
output(' min: %+.2e, mean: %+.2e, max: %+.2e'
% (val.min(), val.mean(), val.max()))
output.level -= 2
if options.show:
# Show the solution. If the approximation order is greater than 1, the
# extra DOFs are simply thrown away.
from sfepy.postprocess.viewer import Viewer
view = Viewer('its2D_interactive.vtk')
view(vector_mode='warp_norm', rel_scaling=1,
is_scalar_bar=True, is_wireframe=True)
if __name__ == '__main__':
main()
| [
"sfepy.discrete.conditions.EssentialBC",
"sfepy.discrete.probes.LineProbe",
"sfepy.mechanics.matcoefs.stiffness_from_youngpoisson",
"sfepy.discrete.Integral",
"sfepy.postprocess.viewer.Viewer",
"sfepy.discrete.projections.project_by_component",
"sfepy.solvers.ls.ScipyDirect",
"sfepy.discrete.Integrals... | [((984, 1004), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (999, 1004), False, 'import sys\n'), ((2837, 2849), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2847, 2849), True, 'import matplotlib.pyplot as plt\n'), ((2854, 2863), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (2861, 2863), True, 'import matplotlib.pyplot as plt\n'), ((2904, 2920), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(311)'], {}), '(311)\n', (2915, 2920), True, 'import matplotlib.pyplot as plt\n'), ((2965, 2985), 'six.moves.range', 'range', (['vals.shape[1]'], {}), '(vals.shape[1])\n', (2970, 2985), False, 'from six.moves import range\n'), ((3105, 3132), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""displacements"""'], {}), "('displacements')\n", (3115, 3132), True, 'import matplotlib.pyplot as plt\n'), ((3137, 3179), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (["('probe %s' % label)"], {'fontsize': '(8)'}), "('probe %s' % label, fontsize=8)\n", (3147, 3179), True, 'import matplotlib.pyplot as plt\n'), ((3184, 3219), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""', 'fontsize': '(10)'}), "(loc='best', fontsize=10)\n", (3194, 3219), True, 'import matplotlib.pyplot as plt\n'), ((3263, 3279), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(312)'], {}), '(312)\n', (3274, 3279), True, 'import matplotlib.pyplot as plt\n'), ((3336, 3356), 'six.moves.range', 'range', (['vals.shape[1]'], {}), '(vals.shape[1])\n', (3341, 3356), False, 'from six.moves import range\n'), ((3483, 3510), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cauchy strain"""'], {}), "('Cauchy strain')\n", (3493, 3510), True, 'import matplotlib.pyplot as plt\n'), ((3515, 3557), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (["('probe %s' % label)"], {'fontsize': '(8)'}), "('probe %s' % label, fontsize=8)\n", (3525, 3557), True, 'import matplotlib.pyplot as plt\n'), ((3562, 3597), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""', 'fontsize': '(10)'}), "(loc='best', fontsize=10)\n", (3572, 3597), True, 'import matplotlib.pyplot as plt\n'), ((3603, 3619), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(313)'], {}), '(313)\n', (3614, 3619), True, 'import matplotlib.pyplot as plt\n'), ((3676, 3696), 'six.moves.range', 'range', (['vals.shape[1]'], {}), '(vals.shape[1])\n', (3681, 3696), False, 'from six.moves import range\n'), ((3828, 3855), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cauchy stress"""'], {}), "('Cauchy stress')\n", (3838, 3855), True, 'import matplotlib.pyplot as plt\n'), ((3860, 3902), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (["('probe %s' % label)"], {'fontsize': '(8)'}), "('probe %s' % label, fontsize=8)\n", (3870, 3902), True, 'import matplotlib.pyplot as plt\n'), ((3907, 3942), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""', 'fontsize': '(10)'}), "(loc='best', fontsize=10)\n", (3917, 3942), True, 'import matplotlib.pyplot as plt\n'), ((4485, 4570), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '__doc__', 'formatter_class': 'RawDescriptionHelpFormatter'}), '(description=__doc__, formatter_class=RawDescriptionHelpFormatter\n )\n', (4499, 4570), False, 'from argparse import ArgumentParser, RawDescriptionHelpFormatter\n'), ((5884, 5960), 'sfepy.base.base.assert_', 'assert_', (['(0.0 < options.poisson < 0.5)', '"""Poisson\'s ratio must be in ]0, 0.5[!"""'], {}), '(0.0 < options.poisson < 0.5, "Poisson\'s ratio must be in ]0, 0.5[!")\n', (5891, 5960), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((5979, 6065), 'sfepy.base.base.assert_', 'assert_', (['(0 < options.order)', '"""displacement approximation order must be at least 1!"""'], {}), "(0 < options.order,\n 'displacement approximation order must be at least 1!')\n", (5986, 6065), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((6081, 6104), 'sfepy.base.base.output', 'output', (['"""using values:"""'], {}), "('using values:')\n", (6087, 6104), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((6109, 6152), 'sfepy.base.base.output', 'output', (['""" Young\'s modulus:"""', 'options.young'], {}), '(" Young\'s modulus:", options.young)\n', (6115, 6152), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((6157, 6202), 'sfepy.base.base.output', 'output', (['""" Poisson\'s ratio:"""', 'options.poisson'], {}), '(" Poisson\'s ratio:", options.poisson)\n', (6163, 6202), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((6207, 6247), 'sfepy.base.base.output', 'output', (['""" vertical load:"""', 'options.load'], {}), "(' vertical load:', options.load)\n", (6213, 6247), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((6252, 6308), 'sfepy.base.base.output', 'output', (['"""uniform mesh refinement level:"""', 'options.refine'], {}), "('uniform mesh refinement level:', options.refine)\n", (6258, 6308), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((6357, 6407), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (["(data_dir + '/meshes/2d/its2D.mesh')"], {}), "(data_dir + '/meshes/2d/its2D.mesh')\n", (6371, 6407), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((6421, 6445), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""domain"""', 'mesh'], {}), "('domain', mesh)\n", (6429, 6445), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((7041, 7119), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""fu"""', 'nm.float64', '"""vector"""', 'omega'], {'approx_order': 'options.order'}), "('fu', nm.float64, 'vector', omega, approx_order=options.order)\n", (7056, 7119), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((7157, 7193), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""u"""', '"""unknown"""', 'field'], {}), "('u', 'unknown', field)\n", (7170, 7193), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((7202, 7257), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""v"""', '"""test"""', 'field'], {'primary_var_name': '"""u"""'}), "('v', 'test', field, primary_var_name='u')\n", (7215, 7257), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((7267, 7329), 'sfepy.mechanics.matcoefs.stiffness_from_youngpoisson', 'stiffness_from_youngpoisson', (['(2)', 'options.young', 'options.poisson'], {}), '(2, options.young, options.poisson)\n', (7294, 7329), False, 'from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson\n'), ((7345, 7369), 'sfepy.discrete.Material', 'Material', (['"""Asphalt"""'], {'D': 'D'}), "('Asphalt', D=D)\n", (7353, 7369), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((7381, 7435), 'sfepy.discrete.Material', 'Material', (['"""Load"""'], {'values': "{'.val': [0.0, options.load]}"}), "('Load', values={'.val': [0.0, options.load]})\n", (7389, 7435), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((7453, 7491), 'sfepy.discrete.Integral', 'Integral', (['"""i"""'], {'order': '(2 * options.order)'}), "('i', order=2 * options.order)\n", (7461, 7491), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((7506, 7528), 'sfepy.discrete.Integral', 'Integral', (['"""i"""'], {'order': '(0)'}), "('i', order=0)\n", (7514, 7528), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((7539, 7631), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_lin_elastic(Asphalt.D, v, u)"""', 'integral', 'omega'], {'Asphalt': 'asphalt', 'v': 'v', 'u': 'u'}), "('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=\n asphalt, v=v, u=u)\n", (7547, 7631), False, 'from sfepy.terms import Term\n'), ((7654, 7724), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_point_load(Load.val, v)"""', 'integral0', 'top'], {'Load': 'load', 'v': 'v'}), "('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v)\n", (7662, 7724), False, 'from sfepy.terms import Term\n'), ((7752, 7780), 'sfepy.discrete.Equation', 'Equation', (['"""balance"""', '(t1 - t2)'], {}), "('balance', t1 - t2)\n", (7760, 7780), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((7791, 7806), 'sfepy.discrete.Equations', 'Equations', (['[eq]'], {}), '([eq])\n', (7800, 7806), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((7819, 7860), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""XSym"""', 'bottom', "{'u.1': 0.0}"], {}), "('XSym', bottom, {'u.1': 0.0})\n", (7830, 7860), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((7873, 7912), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""YSym"""', 'left', "{'u.0': 0.0}"], {}), "('YSym', left, {'u.0': 0.0})\n", (7884, 7912), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((7924, 7939), 'sfepy.solvers.ls.ScipyDirect', 'ScipyDirect', (['{}'], {}), '({})\n', (7935, 7939), False, 'from sfepy.solvers.ls import ScipyDirect\n'), ((7958, 7973), 'sfepy.base.base.IndexedStruct', 'IndexedStruct', ([], {}), '()\n', (7971, 7973), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((7984, 8028), 'sfepy.solvers.nls.Newton', 'Newton', (['{}'], {'lin_solver': 'ls', 'status': 'nls_status'}), '({}, lin_solver=ls, status=nls_status)\n', (7990, 8028), False, 'from sfepy.solvers.nls import Newton\n'), ((8039, 8091), 'sfepy.discrete.Problem', 'Problem', (['"""elasticity"""'], {'equations': 'eqs', 'nls': 'nls', 'ls': 'ls'}), "('elasticity', equations=eqs, nls=nls, ls=ls)\n", (8046, 8091), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((8196, 8214), 'sfepy.base.base.output', 'output', (['nls_status'], {}), '(nls_status)\n', (8202, 8214), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((8295, 8337), 'examples.linear_elasticity.its2D_2.stress_strain', 'stress_strain', (['out', 'pb', 'state'], {'extend': '(True)'}), '(out, pb, state, extend=True)\n', (8308, 8337), False, 'from examples.linear_elasticity.its2D_2 import stress_strain\n'), ((8469, 8537), 'sfepy.discrete.Integral', 'Integral', (['"""ivn"""'], {'coors': 'gdata.coors', 'weights': '([gdata.volume / nc] * nc)'}), "('ivn', coors=gdata.coors, weights=[gdata.volume / nc] * nc)\n", (8477, 8537), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((2995, 3087), 'matplotlib.pyplot.plot', 'plt.plot', (['pars', 'vals[:, ic]'], {'label': "('$u_{%d}$' % (ic + 1))", 'lw': '(1)', 'ls': '"""-"""', 'marker': '"""+"""', 'ms': '(3)'}), "(pars, vals[:, ic], label='$u_{%d}$' % (ic + 1), lw=1, ls='-',\n marker='+', ms=3)\n", (3003, 3087), True, 'import matplotlib.pyplot as plt\n'), ((3366, 3466), 'matplotlib.pyplot.plot', 'plt.plot', (['pars', 'vals[:, ic]'], {'label': "('$e_{%s}$' % sym_indices[ic])", 'lw': '(1)', 'ls': '"""-"""', 'marker': '"""+"""', 'ms': '(3)'}), "(pars, vals[:, ic], label='$e_{%s}$' % sym_indices[ic], lw=1, ls=\n '-', marker='+', ms=3)\n", (3374, 3466), True, 'import matplotlib.pyplot as plt\n'), ((3706, 3811), 'matplotlib.pyplot.plot', 'plt.plot', (['pars', 'vals[:, ic]'], {'label': "('$\\\\sigma_{%s}$' % sym_indices[ic])", 'lw': '(1)', 'ls': '"""-"""', 'marker': '"""+"""', 'ms': '(3)'}), "(pars, vals[:, ic], label='$\\\\sigma_{%s}$' % sym_indices[ic], lw=1,\n ls='-', marker='+', ms=3)\n", (3714, 3811), True, 'import matplotlib.pyplot as plt\n'), ((6492, 6513), 'six.moves.range', 'range', (['options.refine'], {}), '(options.refine)\n', (6497, 6513), False, 'from six.moves import range\n'), ((8744, 8832), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""sym_tensor"""', 'nm.float64', '(3)', 'omega'], {'approx_order': '(options.order - 1)'}), "('sym_tensor', nm.float64, 3, omega, approx_order=options.\n order - 1)\n", (8759, 8832), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((8877, 8955), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""stress"""', '"""parameter"""', 'sfield'], {'primary_var_name': '"""(set-to-None)"""'}), "('stress', 'parameter', sfield, primary_var_name='(set-to-None)')\n", (8890, 8955), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((9004, 9082), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""strain"""', '"""parameter"""', 'sfield'], {'primary_var_name': '"""(set-to-None)"""'}), "('strain', 'parameter', sfield, primary_var_name='(set-to-None)')\n", (9017, 9082), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((9132, 9219), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""component"""', 'nm.float64', '(1)', 'omega'], {'approx_order': '(options.order - 1)'}), "('component', nm.float64, 1, omega, approx_order=options.\n order - 1)\n", (9147, 9219), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((9268, 9354), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""component"""', '"""parameter"""', 'cfield'], {'primary_var_name': '"""(set-to-None)"""'}), "('component', 'parameter', cfield, primary_var_name=\n '(set-to-None)')\n", (9281, 9354), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((9663, 9720), 'sfepy.discrete.projections.project_by_component', 'project_by_component', (['strain', 'strain_qp', 'component', 'order'], {}), '(strain, strain_qp, component, order)\n', (9683, 9720), False, 'from sfepy.discrete.projections import project_by_component\n'), ((9729, 9786), 'sfepy.discrete.projections.project_by_component', 'project_by_component', (['stress', 'stress_qp', 'component', 'order'], {}), '(stress, stress_qp, component, order)\n', (9749, 9786), False, 'from sfepy.discrete.projections import project_by_component\n'), ((10646, 10677), 'sfepy.postprocess.viewer.Viewer', 'Viewer', (['"""its2D_interactive.vtk"""'], {}), "('its2D_interactive.vtk')\n", (10652, 10677), False, 'from sfepy.postprocess.viewer import Viewer\n'), ((2404, 2430), 'sfepy.discrete.probes.LineProbe', 'LineProbe', (['p0', 'p1', 'n_point'], {}), '(p0, p1, n_point)\n', (2413, 2430), False, 'from sfepy.discrete.probes import LineProbe\n'), ((6527, 6554), 'sfepy.base.base.output', 'output', (["('refine %d...' % ii)"], {}), "('refine %d...' % ii)\n", (6533, 6554), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((6604, 6680), '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", (6610, 6680), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((8117, 8141), 'sfepy.discrete.conditions.Conditions', 'Conditions', (['[xsym, ysym]'], {}), '([xsym, ysym])\n', (8127, 8141), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((8608, 8632), 'sfepy.discrete.Integrals', 'Integrals', (['[integral_vn]'], {}), '([integral_vn])\n', (8617, 8632), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Integrals, Equation, Equations, Problem\n'), ((10104, 10128), 'sfepy.base.base.output', 'output', (["('probe %d:' % ii)"], {}), "('probe %d:' % ii)\n", (10110, 10128), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((10187, 10213), 'sfepy.base.base.ordered_iteritems', 'ordered_iteritems', (['results'], {}), '(results)\n', (10204, 10213), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n'), ((10231, 10248), 'sfepy.base.base.output', 'output', (["(key + ':')"], {}), "(key + ':')\n", (10237, 10248), False, 'from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct\n')] |
"""
Computational domain for isogeometric analysis.
"""
import os.path as op
import numpy as nm
from sfepy.base.base import Struct
from sfepy.discrete.common.domain import Domain
import sfepy.discrete.iga as iga
import sfepy.discrete.iga.io as io
from sfepy.discrete.iga.extmods.igac import eval_in_tp_coors
class NurbsPatch(Struct):
"""
Single NURBS patch data.
"""
def __init__(self, knots, degrees, cps,
weights, cs, conn):
Struct.__init__(self, name='nurbs', knots=knots, degrees=degrees,
cps=cps, weights=weights, cs=cs, conn=conn)
self.n_els = [len(ii) for ii in cs]
self.dim = len(self.n_els)
def _get_ref_coors_1d(self, pars, axis):
uk = nm.unique(self.knots[axis])
indices = nm.searchsorted(uk[1:], pars)
ref_coors = nm.empty_like(pars)
for ii in xrange(len(uk) - 1):
ispan = nm.where(indices == ii)[0]
pp = pars[ispan]
ref_coors[ispan] = (pp - uk[ii]) / (uk[ii+1] - uk[ii])
return uk, indices, ref_coors
def __call__(self, u=None, v=None, w=None, field=None):
"""
Igakit-like interface for NURBS evaluation.
"""
pars = [u]
if v is not None: pars += [v]
if w is not None: pars += [w]
indices = []
rcs = []
for ia, par in enumerate(pars):
uk, indx, rc = self._get_ref_coors_1d(par, ia)
indices.append(indx.astype(nm.uint32))
rcs.append(rc)
out = eval_in_tp_coors(field, indices,
rcs, self.cps, self.weights,
self.degrees,
self.cs, self.conn)
return out
def evaluate(self, field, u=None, v=None, w=None):
"""
Igakit-like interface for NURBS evaluation.
"""
return self(u, v, w, field)
class IGDomain(Domain):
"""
Bezier extraction based NURBS domain for isogeometric analysis.
"""
@staticmethod
def from_file(filename):
"""
filename : str
The name of the IGA domain file.
"""
(knots, degrees, cps, weights, cs, conn,
bcps, bweights, bconn, regions) = io.read_iga_data(filename)
nurbs = NurbsPatch(knots, degrees, cps, weights, cs, conn)
bmesh = Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn)
name = op.splitext(filename)[0]
domain = IGDomain(name, nurbs=nurbs, bmesh=bmesh, regions=regions)
return domain
def __init__(self, name, nurbs, bmesh, regions=None, **kwargs):
"""
Create an IGA domain.
Parameters
----------
name : str
The domain name.
"""
Domain.__init__(self, name, nurbs=nurbs, bmesh=bmesh, regions=regions,
**kwargs)
from sfepy.discrete.fem.geometry_element import create_geometry_elements
from sfepy.discrete.fem import Mesh
from sfepy.discrete.fem.extmods.cmesh import CMesh
from sfepy.discrete.fem.utils import prepare_remap
ac = nm.ascontiguousarray
self.nurbs.cs = [ac(nm.array(cc, dtype=nm.float64)[:, None, ...])
for cc in self.nurbs.cs]
self.nurbs.degrees = self.nurbs.degrees.astype(nm.int32)
self.facets = iga.get_bezier_element_entities(nurbs.degrees)
tconn = iga.get_bezier_topology(bmesh.conn, nurbs.degrees)
itc = nm.unique(tconn)
remap = prepare_remap(itc, bmesh.conn.max() + 1)
ltcoors = bmesh.cps[itc]
ltconn = remap[tconn]
n_nod, dim = ltcoors.shape
n_el = ltconn.shape[0]
self.shape = Struct(n_nod=n_nod, dim=dim, tdim=0, n_el=n_el, n_gr=1)
desc = '%d_%d' % (dim, 2**dim)
mat_id = nm.zeros(ltconn.shape[0], dtype=nm.int32)
self.mesh = Mesh.from_data(self.name + '_topo', ltcoors, None, [ltconn],
[mat_id], [desc])
self.cmesh = CMesh.from_mesh(self.mesh)
gels = create_geometry_elements()
self.cmesh.set_local_entities(gels)
self.cmesh.setup_entities()
self.shape.tdim = self.cmesh.tdim
self.gel = gels[desc]
if regions is not None:
self.vertex_set_bcs = {}
for key, val in self.regions.iteritems():
self.vertex_set_bcs[key] = remap[val]
self.cell_offsets = {0 : 0}
self.reset_regions()
| [
"sfepy.discrete.iga.io.read_iga_data",
"sfepy.discrete.fem.Mesh.from_data",
"sfepy.base.base.Struct",
"sfepy.discrete.common.domain.Domain.__init__",
"sfepy.discrete.iga.get_bezier_element_entities",
"sfepy.discrete.fem.geometry_element.create_geometry_elements",
"sfepy.discrete.fem.extmods.cmesh.CMesh.... | [((472, 585), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'name': '"""nurbs"""', 'knots': 'knots', 'degrees': 'degrees', 'cps': 'cps', 'weights': 'weights', 'cs': 'cs', 'conn': 'conn'}), "(self, name='nurbs', knots=knots, degrees=degrees, cps=cps,\n weights=weights, cs=cs, conn=conn)\n", (487, 585), False, 'from sfepy.base.base import Struct\n'), ((744, 771), 'numpy.unique', 'nm.unique', (['self.knots[axis]'], {}), '(self.knots[axis])\n', (753, 771), True, 'import numpy as nm\n'), ((790, 819), 'numpy.searchsorted', 'nm.searchsorted', (['uk[1:]', 'pars'], {}), '(uk[1:], pars)\n', (805, 819), True, 'import numpy as nm\n'), ((840, 859), 'numpy.empty_like', 'nm.empty_like', (['pars'], {}), '(pars)\n', (853, 859), True, 'import numpy as nm\n'), ((1544, 1643), 'sfepy.discrete.iga.extmods.igac.eval_in_tp_coors', 'eval_in_tp_coors', (['field', 'indices', 'rcs', 'self.cps', 'self.weights', 'self.degrees', 'self.cs', 'self.conn'], {}), '(field, indices, rcs, self.cps, self.weights, self.degrees,\n self.cs, self.conn)\n', (1560, 1643), False, 'from sfepy.discrete.iga.extmods.igac import eval_in_tp_coors\n'), ((2262, 2288), 'sfepy.discrete.iga.io.read_iga_data', 'io.read_iga_data', (['filename'], {}), '(filename)\n', (2278, 2288), True, 'import sfepy.discrete.iga.io as io\n'), ((2373, 2433), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""bmesh"""', 'cps': 'bcps', 'weights': 'bweights', 'conn': 'bconn'}), "(name='bmesh', cps=bcps, weights=bweights, conn=bconn)\n", (2379, 2433), False, 'from sfepy.base.base import Struct\n'), ((2790, 2875), 'sfepy.discrete.common.domain.Domain.__init__', 'Domain.__init__', (['self', 'name'], {'nurbs': 'nurbs', 'bmesh': 'bmesh', 'regions': 'regions'}), '(self, name, nurbs=nurbs, bmesh=bmesh, regions=regions, **kwargs\n )\n', (2805, 2875), False, 'from sfepy.discrete.common.domain import Domain\n'), ((3386, 3432), 'sfepy.discrete.iga.get_bezier_element_entities', 'iga.get_bezier_element_entities', (['nurbs.degrees'], {}), '(nurbs.degrees)\n', (3417, 3432), True, 'import sfepy.discrete.iga as iga\n'), ((3450, 3500), 'sfepy.discrete.iga.get_bezier_topology', 'iga.get_bezier_topology', (['bmesh.conn', 'nurbs.degrees'], {}), '(bmesh.conn, nurbs.degrees)\n', (3473, 3500), True, 'import sfepy.discrete.iga as iga\n'), ((3515, 3531), 'numpy.unique', 'nm.unique', (['tconn'], {}), '(tconn)\n', (3524, 3531), True, 'import numpy as nm\n'), ((3742, 3797), 'sfepy.base.base.Struct', 'Struct', ([], {'n_nod': 'n_nod', 'dim': 'dim', 'tdim': '(0)', 'n_el': 'n_el', 'n_gr': '(1)'}), '(n_nod=n_nod, dim=dim, tdim=0, n_el=n_el, n_gr=1)\n', (3748, 3797), False, 'from sfepy.base.base import Struct\n'), ((3855, 3896), 'numpy.zeros', 'nm.zeros', (['ltconn.shape[0]'], {'dtype': 'nm.int32'}), '(ltconn.shape[0], dtype=nm.int32)\n', (3863, 3896), True, 'import numpy as nm\n'), ((3917, 3995), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (["(self.name + '_topo')", 'ltcoors', 'None', '[ltconn]', '[mat_id]', '[desc]'], {}), "(self.name + '_topo', ltcoors, None, [ltconn], [mat_id], [desc])\n", (3931, 3995), False, 'from sfepy.discrete.fem import Mesh\n'), ((4053, 4079), 'sfepy.discrete.fem.extmods.cmesh.CMesh.from_mesh', 'CMesh.from_mesh', (['self.mesh'], {}), '(self.mesh)\n', (4068, 4079), False, 'from sfepy.discrete.fem.extmods.cmesh import CMesh\n'), ((4095, 4121), 'sfepy.discrete.fem.geometry_element.create_geometry_elements', 'create_geometry_elements', ([], {}), '()\n', (4119, 4121), False, 'from sfepy.discrete.fem.geometry_element import create_geometry_elements\n'), ((2450, 2471), 'os.path.splitext', 'op.splitext', (['filename'], {}), '(filename)\n', (2461, 2471), True, 'import os.path as op\n'), ((919, 942), 'numpy.where', 'nm.where', (['(indices == ii)'], {}), '(indices == ii)\n', (927, 942), True, 'import numpy as nm\n'), ((3201, 3231), 'numpy.array', 'nm.array', (['cc'], {'dtype': 'nm.float64'}), '(cc, dtype=nm.float64)\n', (3209, 3231), True, 'import numpy as nm\n')] |
import re
from copy import copy
import numpy as nm
from sfepy.base.base import (as_float_or_complex, get_default, assert_,
Container, Struct, basestr, goptions)
from sfepy.base.compat import in1d
# Used for imports in term files.
from sfepy.terms.extmods import terms
from sfepy.linalg import split_range
_match_args = re.compile('^([^\(\}]*)\((.*)\)$').match
_match_virtual = re.compile('^virtual$').match
_match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match
_match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match
_match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match
_match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match
_match_material_root = re.compile('(.+)\.(.*)').match
def get_arg_kinds(arg_types):
"""
Translate `arg_types` of a Term to a canonical form.
Parameters
----------
arg_types : tuple of strings
The term argument types, as given in the `arg_types` attribute.
Returns
-------
arg_kinds : list of strings
The argument kinds - one of 'virtual_variable', 'state_variable',
'parameter_variable', 'opt_material', 'user'.
"""
arg_kinds = []
for ii, arg_type in enumerate(arg_types):
if _match_virtual(arg_type):
arg_kinds.append('virtual_variable')
elif _match_state(arg_type):
arg_kinds.append('state_variable')
elif _match_parameter(arg_type):
arg_kinds.append('parameter_variable')
elif _match_material(arg_type):
arg_kinds.append('material')
elif _match_material_opt(arg_type):
arg_kinds.append('opt_material')
if ii > 0:
msg = 'opt_material at position %d, must be at 0!' % ii
raise ValueError(msg)
else:
arg_kinds.append('user')
return arg_kinds
def get_shape_kind(integration):
"""
Get data shape kind for given integration type.
"""
if integration == 'surface':
shape_kind = 'surface'
elif integration in ('volume', 'plate', 'surface_extra'):
shape_kind = 'volume'
elif integration == 'point':
shape_kind = 'point'
else:
raise NotImplementedError('unsupported term integration! (%s)'
% integration)
return shape_kind
def split_complex_args(args):
"""
Split complex arguments to real and imaginary parts.
Returns
-------
newargs : dictionary
Dictionary with lists corresponding to `args` such that each
argument of numpy.complex128 data type is split to its real and
imaginary part. The output depends on the number of complex
arguments in 'args':
- 0: list (key 'r') identical to input one
- 1: two lists with keys 'r', 'i' corresponding to real
and imaginary parts
- 2: output dictionary contains four lists:
- 'r' - real(arg1), real(arg2)
- 'i' - imag(arg1), imag(arg2)
- 'ri' - real(arg1), imag(arg2)
- 'ir' - imag(arg1), real(arg2)
"""
newargs = {}
cai = []
for ii, arg in enumerate(args):
if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128):
cai.append(ii)
if len(cai) > 0:
newargs['r'] = list(args[:])
newargs['i'] = list(args[:])
arg1 = cai[0]
newargs['r'][arg1] = args[arg1].real.copy()
newargs['i'][arg1] = args[arg1].imag.copy()
if len(cai) == 2:
arg2 = cai[1]
newargs['r'][arg2] = args[arg2].real.copy()
newargs['i'][arg2] = args[arg2].imag.copy()
newargs['ri'] = list(args[:])
newargs['ir'] = list(args[:])
newargs['ri'][arg1] = newargs['r'][arg1]
newargs['ri'][arg2] = newargs['i'][arg2]
newargs['ir'][arg1] = newargs['i'][arg1]
newargs['ir'][arg2] = newargs['r'][arg2]
elif len(cai) > 2:
raise NotImplementedError('more than 2 complex arguments! (%d)'
% len(cai))
else:
newargs['r'] = args[:]
return newargs
def vector_chunk_generator(total_size, chunk_size, shape_in,
zero=False, set_shape=True, dtype=nm.float64):
if not chunk_size:
chunk_size = total_size
shape = list(shape_in)
sizes = split_range(total_size, chunk_size)
ii = nm.array(0, dtype=nm.int32)
for size in sizes:
chunk = nm.arange(size, dtype=nm.int32) + ii
if set_shape:
shape[0] = size
if zero:
out = nm.zeros(shape, dtype=dtype)
else:
out = nm.empty(shape, dtype=dtype)
yield out, chunk
ii += size
def create_arg_parser():
from pyparsing import Literal, Word, delimitedList, Group, \
StringStart, StringEnd, Optional, nums, alphas, alphanums
inumber = Word("+-" + nums, nums)
history = Optional(Literal('[').suppress() + inumber
+ Literal(']').suppress(), default=0)("history")
history.setParseAction(lambda str, loc, toks: int(toks[0]))
variable = Group(Word(alphas, alphanums + '._') + history)
derivative = Group(Literal('d') + variable\
+ Literal('/').suppress() + Literal('dt'))
trace = Group(Literal('tr') + Literal('(').suppress() + variable \
+ Literal(')').suppress())
generalized_var = derivative | trace | variable
args = StringStart() + delimitedList(generalized_var) + StringEnd()
return args
# 22.01.2006, c
class CharacteristicFunction(Struct):
def __init__(self, region):
self.igs = region.igs
self.region = region
self.local_chunk = None
self.ig = None
def __call__(self, chunk_size, shape_in, zero=False, set_shape=True,
ret_local_chunk=False, dtype=nm.float64):
els = self.region.get_cells(self.ig)
for out, chunk in vector_chunk_generator(els.shape[0], chunk_size,
shape_in, zero, set_shape,
dtype):
self.local_chunk = chunk
if ret_local_chunk:
yield out, chunk
else:
yield out, els[chunk]
self.local_chunk = None
def set_current_group(self, ig):
self.ig = ig
def get_local_chunk(self):
return self.local_chunk
class ConnInfo(Struct):
def get_region(self, can_trace=True):
if self.is_trace and can_trace:
return self.region.get_mirror_region()[0]
else:
return self.region
def get_region_name(self, can_trace=True):
if self.is_trace and can_trace:
reg = self.region.get_mirror_region()[0]
else:
reg = self.region
if reg is not None:
return reg.name
else:
return None
def iter_igs(self):
if self.region is not None:
for ig in self.region.igs:
if self.virtual_igs is not None:
ir = self.virtual_igs.tolist().index(ig)
rig = self.virtual_igs[ir]
else:
rig = None
if not self.is_trace:
ii = ig
else:
ig_map_i = self.region.get_mirror_region()[2]
ii = ig_map_i[ig]
if self.state_igs is not None:
ic = self.state_igs.tolist().index(ii)
cig = self.state_igs[ic]
else:
cig = None
yield rig, cig
else:
yield None, None
class Terms(Container):
@staticmethod
def from_desc(term_descs, regions, integrals=None):
"""
Create terms, assign each term its region.
"""
from sfepy.terms import term_table
terms = Terms()
for td in term_descs:
try:
constructor = term_table[td.name]
except:
msg = "term '%s' is not in %s" % (td.name,
sorted(term_table.keys()))
raise ValueError(msg)
try:
region = regions[td.region]
except IndexError:
raise KeyError('region "%s" does not exist!' % td.region)
term = Term.from_desc(constructor, td, region, integrals=integrals)
terms.append(term)
return terms
def __init__(self, objs=None):
Container.__init__(self, objs=objs)
self.update_expression()
def insert(self, ii, obj):
Container.insert(self, ii, obj)
self.update_expression()
def append(self, obj):
Container.append(self, obj)
self.update_expression()
def update_expression(self):
self.expression = []
for term in self:
aux = [term.sign, term.name, term.arg_str,
term.integral_name, term.region.name]
self.expression.append(aux)
def __mul__(self, other):
out = Terms()
for name, term in self.iteritems():
out.append(term * other)
return out
def __rmul__(self, other):
return self * other
def __add__(self, other):
if isinstance(other, Term):
out = self.copy()
out.append(other)
elif isinstance(other, Terms):
out = Terms(self._objs + other._objs)
else:
raise ValueError('cannot add Terms with %s!' % other)
return out
def __radd__(self, other):
return self + other
def __sub__(self, other):
if isinstance(other, Term):
out = self + (-other)
elif isinstance(other, Terms):
out = self + (-other)
else:
raise ValueError('cannot subtract Terms with %s!' % other)
return out
def __rsub__(self, other):
return -self + other
def __pos__(self):
return self
def __neg__(self):
return -1.0 * self
def setup(self):
for term in self:
term.setup()
def assign_args(self, variables, materials, user=None):
"""
Assign all term arguments.
"""
for term in self:
term.assign_args(variables, materials, user)
def get_variable_names(self):
out = []
for term in self:
out.extend(term.get_variable_names())
return list(set(out))
def get_material_names(self):
out = []
for term in self:
out.extend(term.get_material_names())
return list(set(out))
def get_user_names(self):
out = []
for term in self:
out.extend(term.get_user_names())
return list(set(out))
def set_current_group(self, ig):
for term in self:
term.char_fun.set_current_group(ig)
class Term(Struct):
name = ''
arg_types = ()
arg_shapes = {}
integration = 'volume'
geometries = ['2_3', '2_4', '3_4', '3_8']
@staticmethod
def new(name, integral, region, **kwargs):
from sfepy.terms import term_table
arg_str = _match_args(name)
if arg_str is not None:
name, arg_str = arg_str.groups()
else:
raise ValueError('bad term syntax! (%s)' % name)
if name in term_table:
constructor = term_table[name]
else:
msg = "term '%s' is not in %s" % (name, sorted(term_table.keys()))
raise ValueError(msg)
obj = constructor(name, arg_str, integral, region, **kwargs)
return obj
@staticmethod
def from_desc(constructor, desc, region, integrals=None):
from sfepy.discrete import Integrals
if integrals is None:
integrals = Integrals()
if desc.name == 'intFE':
obj = constructor(desc.name, desc.args, None, region, desc=desc)
else:
obj = constructor(desc.name, desc.args, None, region)
obj.set_integral(integrals.get(desc.integral))
obj.sign = desc.sign
return obj
def __init__(self, name, arg_str, integral, region, **kwargs):
self.name = name
self.arg_str = arg_str
self.region = region
self._kwargs = kwargs
self._integration = self.integration
self.sign = 1.0
self.set_integral(integral)
def __mul__(self, other):
try:
mul = as_float_or_complex(other)
except ValueError:
raise ValueError('cannot multiply Term with %s!' % other)
out = self.copy(name=self.name)
out.sign = mul * self.sign
return out
def __rmul__(self, other):
return self * other
def __add__(self, other):
if isinstance(other, Term):
out = Terms([self, other])
else:
out = NotImplemented
return out
def __sub__(self, other):
if isinstance(other, Term):
out = Terms([self, -1.0 * other])
else:
out = NotImplemented
return out
def __pos__(self):
return self
def __neg__(self):
out = -1.0 * self
return out
def set_integral(self, integral):
"""
Set the term integral.
"""
self.integral = integral
if self.integral is not None:
self.integral_name = self.integral.name
def setup(self):
self.char_fun = CharacteristicFunction(self.region)
self.function = Struct.get(self, 'function', None)
self.step = 0
self.dt = 1.0
self.is_quasistatic = False
self.has_region = True
self.setup_formal_args()
if self._kwargs:
self.setup_args(**self._kwargs)
else:
self.args = []
def setup_formal_args(self):
self.arg_names = []
self.arg_steps = {}
self.arg_derivatives = {}
self.arg_traces = {}
parser = create_arg_parser()
self.arg_desc = parser.parseString(self.arg_str)
for arg in self.arg_desc:
trace = False
derivative = None
if isinstance(arg[1], int):
name, step = arg
else:
kind = arg[0]
name, step = arg[1]
if kind == 'd':
derivative = arg[2]
elif kind == 'tr':
trace = True
match = _match_material_root(name)
if match:
name = (match.group(1), match.group(2))
self.arg_names.append(name)
self.arg_steps[name] = step
self.arg_derivatives[name] = derivative
self.arg_traces[name] = trace
def setup_args(self, **kwargs):
self._kwargs = kwargs
self.args = []
for arg_name in self.arg_names:
if isinstance(arg_name, basestr):
self.args.append(self._kwargs[arg_name])
else:
self.args.append((self._kwargs[arg_name[0]], arg_name[1]))
self.classify_args()
self.check_args()
def __call__(self, diff_var=None, chunk_size=None, **kwargs):
"""
Subclasses either implement __call__ or plug in a proper _call().
"""
return self._call(diff_var, chunk_size, **kwargs)
def _call(self, diff_var=None, chunk_size=None, **kwargs):
msg = 'base class method "_call" called for %s' \
% self.__class__.__name__
raise RuntimeError(msg)
def assign_args(self, variables, materials, user=None):
"""
Check term argument existence in variables, materials, user data
and assign the arguments to terms. Also check compatibility of
field and term subdomain lists (igs).
"""
if user is None:
user = {}
kwargs = {}
for arg_name in self.arg_names:
if isinstance(arg_name, basestr):
if arg_name in variables.names:
kwargs[arg_name] = variables[arg_name]
elif arg_name in user:
kwargs[arg_name] = user[arg_name]
else:
raise ValueError('argument %s not found!' % arg_name)
else:
arg_name = arg_name[0]
if arg_name in materials.names:
kwargs[arg_name] = materials[arg_name]
else:
raise ValueError('material argument %s not found!'
% arg_name)
self.setup_args(**kwargs)
def classify_args(self):
"""
Classify types of the term arguments and find matching call
signature.
A state variable can be in place of a parameter variable and
vice versa.
"""
self.names = Struct(name='arg_names',
material=[], variable=[], user=[],
state=[], virtual=[], parameter=[])
# Prepare for 'opt_material' - just prepend a None argument if needed.
if isinstance(self.arg_types[0], tuple):
arg_types = self.arg_types[0]
else:
arg_types = self.arg_types
if len(arg_types) == (len(self.args) + 1):
self.args.insert(0, (None, None))
self.arg_names.insert(0, (None, None))
if isinstance(self.arg_types[0], tuple):
assert_(len(self.modes) == len(self.arg_types))
# Find matching call signature using variable arguments - material
# and user arguments are ignored!
matched = []
for it, arg_types in enumerate(self.arg_types):
arg_kinds = get_arg_kinds(arg_types)
if self._check_variables(arg_kinds):
matched.append((it, arg_kinds))
if len(matched) == 1:
i_match, arg_kinds = matched[0]
arg_types = self.arg_types[i_match]
self.mode = self.modes[i_match]
elif len(matched) == 0:
msg = 'cannot match arguments! (%s)' % self.arg_names
raise ValueError(msg)
else:
msg = 'ambiguous arguments! (%s)' % self.arg_names
raise ValueError(msg)
else:
arg_types = self.arg_types
arg_kinds = get_arg_kinds(self.arg_types)
self.mode = Struct.get(self, 'mode', None)
if not self._check_variables(arg_kinds):
raise ValueError('cannot match variables! (%s)'
% self.arg_names)
# Set actual argument types.
self.ats = list(arg_types)
for ii, arg_kind in enumerate(arg_kinds):
name = self.arg_names[ii]
if arg_kind.endswith('variable'):
names = self.names.variable
if arg_kind == 'virtual_variable':
self.names.virtual.append(name)
elif arg_kind == 'state_variable':
self.names.state.append(name)
elif arg_kind == 'parameter_variable':
self.names.parameter.append(name)
elif arg_kind.endswith('material'):
names = self.names.material
else:
names = self.names.user
names.append(name)
self.n_virtual = len(self.names.virtual)
if self.n_virtual > 1:
raise ValueError('at most one virtual variable is allowed! (%d)'
% self.n_virtual)
self.set_arg_types()
self.setup_integration()
def _check_variables(self, arg_kinds):
for ii, arg_kind in enumerate(arg_kinds):
if arg_kind.endswith('variable'):
var = self.args[ii]
check = {'virtual_variable' : var.is_virtual,
'state_variable' : var.is_state_or_parameter,
'parameter_variable' : var.is_state_or_parameter}
if not check[arg_kind]():
return False
else:
return True
def set_arg_types(self):
pass
def check_args(self):
"""
Common checking to all terms.
Check compatibility of field and term subdomain lists (igs).
"""
vns = self.get_variable_names()
for name in vns:
field = self._kwargs[name].get_field()
if field is None:
continue
if not nm.all(in1d(self.region.vertices,
field.region.vertices)):
msg = ('%s: incompatible regions: (self, field %s)'
+ '(%s in %s)') %\
(self.name, field.name,
self.region.vertices, field.region.vertices)
raise ValueError(msg)
def get_variable_names(self):
return self.names.variable
def get_material_names(self):
out = []
for aux in self.names.material:
if aux[0] is not None:
out.append(aux[0])
return out
def get_user_names(self):
return self.names.user
def get_virtual_name(self):
if not self.names.virtual:
return None
var = self.get_virtual_variable()
return var.name
def get_state_names(self):
"""
If variables are given, return only true unknowns whose data are of
the current time step (0).
"""
variables = self.get_state_variables()
return [var.name for var in variables]
def get_parameter_names(self):
return copy(self.names.parameter)
def get_conn_key(self):
"""The key to be used in DOF connectivity information."""
key = (self.name,) + tuple(self.arg_names)
key += (self.integral_name, self.region.name)
return key
def get_conn_info(self):
vvar = self.get_virtual_variable()
svars = self.get_state_variables()
pvars = self.get_parameter_variables()
all_vars = self.get_variables()
dc_type = self.get_dof_conn_type()
tgs = self.get_geometry_types()
v_igs = v_tg = None
if vvar is not None:
field = vvar.get_field()
if field is not None:
v_igs = field.igs
if vvar.name in tgs:
v_tg = tgs[vvar.name]
else:
v_tg = None
else:
# No virtual variable -> all unknowns are in fact known parameters.
pvars += svars
svars = []
region = self.get_region()
if region is not None:
is_any_trace = reduce(lambda x, y: x or y,
self.arg_traces.values())
if is_any_trace:
region.setup_mirror_region()
self.char_fun.igs = region.igs
vals = []
aux_pvars = []
for svar in svars:
# Allow only true state variables.
if not svar.is_state():
aux_pvars.append(svar)
continue
field = svar.get_field()
if field is not None:
s_igs = field.igs
else:
s_igs = None
is_trace = self.arg_traces[svar.name]
if svar.name in tgs:
ps_tg = tgs[svar.name]
else:
ps_tg = v_tg
val = ConnInfo(virtual=vvar, virtual_igs=v_igs,
state=svar, state_igs=s_igs,
primary=svar, primary_igs=s_igs,
has_virtual=True,
has_state=True,
is_trace=is_trace,
dc_type=dc_type,
v_tg=v_tg,
ps_tg=ps_tg,
region=region,
all_vars=all_vars)
vals.append(val)
pvars += aux_pvars
for pvar in pvars:
field = pvar.get_field()
if field is not None:
p_igs = field.igs
else:
p_igs = None
is_trace = self.arg_traces[pvar.name]
if pvar.name in tgs:
ps_tg = tgs[pvar.name]
else:
ps_tg = v_tg
val = ConnInfo(virtual=vvar, virtual_igs=v_igs,
state=None, state_igs=[],
primary=pvar.get_primary(), primary_igs=p_igs,
has_virtual=vvar is not None,
has_state=False,
is_trace=is_trace,
dc_type=dc_type,
v_tg=v_tg,
ps_tg=ps_tg,
region=region,
all_vars=all_vars)
vals.append(val)
if vvar and (len(vals) == 0):
# No state, parameter variables, just the virtual one.
val = ConnInfo(virtual=vvar, virtual_igs=v_igs,
state=vvar.get_primary(), state_igs=v_igs,
primary=vvar.get_primary(), primary_igs=v_igs,
has_virtual=True,
has_state=False,
is_trace=False,
dc_type=dc_type,
v_tg=v_tg,
ps_tg=v_tg,
region=region,
all_vars=all_vars)
vals.append(val)
return vals
def get_args_by_name(self, arg_names):
"""
Return arguments by name.
"""
out = []
for name in arg_names:
try:
ii = self.arg_names.index(name)
except ValueError:
raise ValueError('non-existing argument! (%s)' % name)
out.append(self.args[ii])
return out
def get_args(self, arg_types=None, **kwargs):
"""
Return arguments by type as specified in arg_types (or
self.ats). Arguments in **kwargs can override the ones assigned
at the term construction - this is useful for passing user data.
"""
ats = self.ats
if arg_types is None:
arg_types = ats
args = []
iname, region_name, ig = self.get_current_group()
for at in arg_types:
ii = ats.index(at)
arg_name = self.arg_names[ii]
if isinstance(arg_name, basestr):
if arg_name in kwargs:
args.append(kwargs[arg_name])
else:
args.append(self.args[ii])
else:
mat, par_name = self.args[ii]
if mat is not None:
mat_data = mat.get_data((region_name, self.integral_name),
ig, par_name)
else:
mat_data = None
args.append(mat_data)
return args
def get_kwargs(self, keys, **kwargs):
"""Extract arguments from **kwargs listed in keys (default is
None)."""
return [kwargs.get(name) for name in keys]
def get_arg_name(self, arg_type, full=False, join=None):
"""
Get the name of the argument specified by `arg_type.`
Parameters
----------
arg_type : str
The argument type string.
full : bool
If True, return the full name. For example, if the name of a
variable argument is 'u' and its time derivative is
requested, the full name is 'du/dt'.
join : str, optional
Optionally, the material argument name tuple can be joined
to a single string using the `join` string.
Returns
-------
name : str
The argument name.
"""
try:
ii = self.ats.index(arg_type)
except ValueError:
return None
name = self.arg_names[ii]
if full:
# Include derivatives.
if self.arg_derivatives[name]:
name = 'd%s/%s' % (name, self.arg_derivatives[name])
if (join is not None) and isinstance(name, tuple):
name = join.join(name)
return name
def setup_integration(self):
self.has_geometry = True
self.geometry_types = {}
if isinstance(self.integration, basestr):
for var in self.get_variables():
self.geometry_types[var.name] = self.integration
else:
if self.mode is not None:
self.integration = self._integration[self.mode]
if self.integration is not None:
for arg_type, gtype in self.integration.iteritems():
var = self.get_args(arg_types=[arg_type])[0]
self.geometry_types[var.name] = gtype
gtypes = list(set(self.geometry_types.itervalues()))
if 'surface_extra' in gtypes:
self.dof_conn_type = 'volume'
elif len(gtypes):
self.dof_conn_type = gtypes[0]
def get_region(self):
return self.region
def get_geometry_types(self):
"""
Returns
-------
out : dict
The required geometry types for each variable argument.
"""
return self.geometry_types
def get_current_group(self):
return (self.integral_name, self.region.name, self.char_fun.ig)
def get_dof_conn_type(self):
return Struct(name='dof_conn_info', type=self.dof_conn_type,
region_name=self.region.name)
def set_current_group(self, ig):
self.char_fun.set_current_group(ig)
def igs(self):
return self.char_fun.igs
def get_assembling_cells(self, shape=None):
"""
Return the assembling cell indices into a DOF connectivity.
"""
cells = nm.arange(shape[0], dtype=nm.int32)
return cells
def iter_groups(self):
if self.dof_conn_type == 'point':
igs = self.igs()[0:1]
else:
igs = self.igs()
for ig in igs:
if self.integration in ('volume', 'plate'):
if not len(self.region.get_cells(ig)): continue
self.set_current_group(ig)
yield ig
def time_update(self, ts):
if ts is not None:
self.step = ts.step
self.dt = ts.dt
self.is_quasistatic = ts.is_quasistatic
def advance(self, ts):
"""
Advance to the next time step. Implemented in subclasses.
"""
def get_vector(self, variable):
"""Get the vector stored in `variable` according to self.arg_steps
and self.arg_derivatives. Supports only the backward difference w.r.t.
time."""
name = variable.name
return variable(step=self.arg_steps[name],
derivative=self.arg_derivatives[name])
def get_approximation(self, variable, get_saved=False):
"""
Return approximation corresponding to `variable`. Also return
the corresponding geometry (actual or saved, according to
`get_saved`).
"""
geo, _, key = self.get_mapping(variable, get_saved=get_saved,
return_key=True)
ig = key[2]
ap = variable.get_approximation(ig)
return ap, geo
def get_variables(self, as_list=True):
if as_list:
variables = self.get_args_by_name(self.names.variable)
else:
variables = {}
for var in self.get_args_by_name(self.names.variable):
variables[var.name] = var
return variables
def get_virtual_variable(self):
aux = self.get_args_by_name(self.names.virtual)
if len(aux) == 1:
var = aux[0]
else:
var = None
return var
def get_state_variables(self, unknown_only=False):
variables = self.get_args_by_name(self.names.state)
if unknown_only:
variables = [var for var in variables
if (var.kind == 'unknown') and
(self.arg_steps[var.name] == 0)]
return variables
def get_parameter_variables(self):
return self.get_args_by_name(self.names.parameter)
def get_materials(self, join=False):
materials = self.get_args_by_name(self.names.material)
for mat in materials:
if mat[0] is None:
materials.remove(mat)
if join:
materials = list(set(mat[0] for mat in materials))
return materials
def get_qp_key(self):
"""
Return a key identifying uniquely the term quadrature points.
"""
return (self.region.name, self.integral.name)
def get_physical_qps(self):
"""
Get physical quadrature points corresponding to the term region
and integral.
"""
from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs
if self.integration == 'point':
phys_qps = PhysicalQPs(self.region.igs)
elif self.integration == 'plate':
phys_qps = get_physical_qps(self.region, self.integral,
map_kind='v')
else:
phys_qps = get_physical_qps(self.region, self.integral)
return phys_qps
def get_mapping(self, variable, get_saved=False, return_key=False):
"""
Get the reference mapping from a variable.
Notes
-----
This is a convenience wrapper of Field.get_mapping() that
initializes the arguments using the term data.
"""
integration = self.geometry_types[variable.name]
is_trace = self.arg_traces[variable.name]
if is_trace:
region, ig_map, ig_map_i = self.region.get_mirror_region()
ig = ig_map_i[self.char_fun.ig]
else:
region = self.region
ig = self.char_fun.ig
out = variable.field.get_mapping(ig, region,
self.integral, integration,
get_saved=get_saved,
return_key=return_key)
return out
def get_data_shape(self, variable):
"""
Get data shape information from variable.
Notes
-----
This is a convenience wrapper of FieldVariable.get_data_shape() that
initializes the arguments using the term data.
"""
integration = self.geometry_types[variable.name]
is_trace = self.arg_traces[variable.name]
if is_trace:
region, ig_map, ig_map_i = self.region.get_mirror_region()
ig = ig_map_i[self.char_fun.ig]
else:
region = self.region
ig = self.char_fun.ig
out = variable.get_data_shape(ig, self.integral,
integration, region.name)
return out
def get(self, variable, quantity_name, bf=None, integration=None,
step=None, time_derivative=None):
"""
Get the named quantity related to the variable.
Notes
-----
This is a convenience wrapper of Variable.evaluate() that
initializes the arguments using the term data.
"""
name = variable.name
step = get_default(step, self.arg_steps[name])
time_derivative = get_default(time_derivative,
self.arg_derivatives[name])
integration = get_default(integration, self.geometry_types[name])
data = variable.evaluate(self.char_fun.ig, mode=quantity_name,
region=self.region, integral=self.integral,
integration=integration,
step=step, time_derivative=time_derivative,
is_trace=self.arg_traces[name], bf=bf)
return data
def check_shapes(self, *args, **kwargs):
"""
Default implementation of function to check term argument shapes
at run-time.
"""
pass
def standalone_setup(self):
from sfepy.discrete import create_adof_conns, Variables
conn_info = {'aux' : self.get_conn_info()}
adcs = create_adof_conns(conn_info, None)
variables = Variables(self.get_variables())
variables.set_adof_conns(adcs)
materials = self.get_materials(join=True)
for mat in materials:
mat.time_update(None, [Struct(terms=[self])])
def call_get_fargs(self, args, kwargs):
try:
fargs = self.get_fargs(*args, **kwargs)
except RuntimeError:
terms.errclear()
raise ValueError
return fargs
def call_function(self, out, fargs):
try:
status = self.function(out, *fargs)
except RuntimeError:
terms.errclear()
raise ValueError
if status:
terms.errclear()
raise ValueError('term evaluation failed! (%s)' % self.name)
return status
def eval_real(self, shape, fargs, mode='eval', term_mode=None,
diff_var=None, **kwargs):
out = nm.empty(shape, dtype=nm.float64)
if mode == 'eval':
status = self.call_function(out, fargs)
# Sum over elements but not over components.
out1 = nm.sum(out, 0).squeeze()
return out1, status
else:
status = self.call_function(out, fargs)
return out, status
def eval_complex(self, shape, fargs, mode='eval', term_mode=None,
diff_var=None, **kwargs):
rout = nm.empty(shape, dtype=nm.float64)
fargsd = split_complex_args(fargs)
# Assuming linear forms. Then the matrix is the
# same both for real and imaginary part.
rstatus = self.call_function(rout, fargsd['r'])
if (diff_var is None) and len(fargsd) >= 2:
iout = nm.empty(shape, dtype=nm.float64)
istatus = self.call_function(iout, fargsd['i'])
if mode == 'eval' and len(fargsd) >= 4:
irout = nm.empty(shape, dtype=nm.float64)
irstatus = self.call_function(irout, fargsd['ir'])
riout = nm.empty(shape, dtype=nm.float64)
ristatus = self.call_function(riout, fargsd['ri'])
out = (rout - iout) + (riout + irout) * 1j
status = rstatus or istatus or ristatus or irstatus
else:
out = rout + 1j * iout
status = rstatus or istatus
else:
out, status = rout, rstatus
if mode == 'eval':
out1 = nm.sum(out, 0).squeeze()
return out1, status
else:
return out, status
def evaluate(self, mode='eval', diff_var=None,
standalone=True, ret_status=False, **kwargs):
"""
Evaluate the term.
Parameters
----------
mode : 'eval' (default), or 'weak'
The term evaluation mode.
Returns
-------
val : float or array
In 'eval' mode, the term returns a single value (the
integral, it does not need to be a scalar), while in 'weak'
mode it returns an array for each element.
status : int, optional
The flag indicating evaluation success (0) or failure
(nonzero). Only provided if `ret_status` is True.
iels : array of ints, optional
The local elements indices in 'weak' mode. Only provided in
non-'eval' modes.
"""
if standalone:
self.standalone_setup()
kwargs = kwargs.copy()
term_mode = kwargs.pop('term_mode', None)
if mode == 'eval':
val = 0.0
status = 0
for ig in self.iter_groups():
args = self.get_args(**kwargs)
self.check_shapes(*args)
_args = tuple(args) + (mode, term_mode, diff_var)
fargs = self.call_get_fargs(_args, kwargs)
shape, dtype = self.get_eval_shape(*_args, **kwargs)
if dtype == nm.float64:
_v, stat = self.eval_real(shape, fargs, mode, term_mode,
**kwargs)
elif dtype == nm.complex128:
_v, stat = self.eval_complex(shape, fargs, mode, term_mode,
**kwargs)
else:
raise ValueError('unsupported term dtype! (%s)' % dtype)
val += _v
status += stat
val *= self.sign
elif mode in ('el_avg', 'el', 'qp'):
vals = None
iels = nm.empty((0, 2), dtype=nm.int32)
status = 0
for ig in self.iter_groups():
args = self.get_args(**kwargs)
self.check_shapes(*args)
_args = tuple(args) + (mode, term_mode, diff_var)
fargs = self.call_get_fargs(_args, kwargs)
shape, dtype = self.get_eval_shape(*_args, **kwargs)
if dtype == nm.float64:
val, stat = self.eval_real(shape, fargs, mode,
term_mode, **kwargs)
elif dtype == nm.complex128:
val, stat = self.eval_complex(shape, fargs, mode,
term_mode, **kwargs)
if vals is None:
vals = val
else:
vals = nm.r_[vals, val]
_iels = self.get_assembling_cells(val.shape)
aux = nm.c_[nm.repeat(ig, _iels.shape[0])[:, None],
_iels[:, None]]
iels = nm.r_[iels, aux]
status += stat
vals *= self.sign
elif mode == 'weak':
vals = []
iels = []
status = 0
varr = self.get_virtual_variable()
if diff_var is not None:
varc = self.get_variables(as_list=False)[diff_var]
for ig in self.iter_groups():
args = self.get_args(**kwargs)
self.check_shapes(*args)
_args = tuple(args) + (mode, term_mode, diff_var)
fargs = self.call_get_fargs(_args, kwargs)
n_elr, n_qpr, dim, n_enr, n_cr = self.get_data_shape(varr)
n_row = n_cr * n_enr
if diff_var is None:
shape = (n_elr, 1, n_row, 1)
else:
n_elc, n_qpc, dim, n_enc, n_cc = self.get_data_shape(varc)
n_col = n_cc * n_enc
shape = (n_elr, 1, n_row, n_col)
if varr.dtype == nm.float64:
val, stat = self.eval_real(shape, fargs, mode, term_mode,
diff_var, **kwargs)
elif varr.dtype == nm.complex128:
val, stat = self.eval_complex(shape, fargs, mode, term_mode,
diff_var, **kwargs)
else:
raise ValueError('unsupported term dtype! (%s)'
% varr.dtype)
vals.append(self.sign * val)
iels.append((ig, self.get_assembling_cells(val.shape)))
status += stat
# Setup return value.
if mode == 'eval':
out = (val,)
else:
out = (vals, iels)
if goptions['check_term_finiteness']:
assert_(nm.isfinite(out[0]).all(),
msg='%+.2e * %s.%d.%s(%s) term values not finite!'
% (self.sign, self.name, self.integral.order,
self.region.name, self.arg_str))
if ret_status:
out = out + (status,)
if len(out) == 1:
out = out[0]
return out
def assemble_to(self, asm_obj, val, iels, mode='vector', diff_var=None):
import sfepy.discrete.fem.extmods.assemble as asm
vvar = self.get_virtual_variable()
dc_type = self.get_dof_conn_type()
if mode == 'vector':
if asm_obj.dtype == nm.float64:
assemble = asm.assemble_vector
else:
assert_(asm_obj.dtype == nm.complex128)
assemble = asm.assemble_vector_complex
for ii in range(len(val)):
if not(val[ii].dtype == nm.complex128):
val[ii] = nm.complex128(val[ii])
for ii, (ig, _iels) in enumerate(iels):
vec_in_els = val[ii]
dc = vvar.get_dof_conn(dc_type, ig)
assert_(vec_in_els.shape[2] == dc.shape[1])
assemble(asm_obj, vec_in_els, _iels, 1.0, dc)
elif mode == 'matrix':
if asm_obj.dtype == nm.float64:
assemble = asm.assemble_matrix
else:
assert_(asm_obj.dtype == nm.complex128)
assemble = asm.assemble_matrix_complex
svar = diff_var
tmd = (asm_obj.data, asm_obj.indptr, asm_obj.indices)
for ii, (ig, _iels) in enumerate(iels):
mtx_in_els = val[ii]
if ((asm_obj.dtype == nm.complex128)
and (mtx_in_els.dtype == nm.float64)):
mtx_in_els = mtx_in_els.astype(nm.complex128)
rdc = vvar.get_dof_conn(dc_type, ig)
is_trace = self.arg_traces[svar.name]
cdc = svar.get_dof_conn(dc_type, ig, is_trace=is_trace)
assert_(mtx_in_els.shape[2:] == (rdc.shape[1], cdc.shape[1]))
sign = 1.0
if self.arg_derivatives[svar.name]:
if not self.is_quasistatic or (self.step > 0):
sign *= 1.0 / self.dt
else:
sign = 0.0
assemble(tmd[0], tmd[1], tmd[2], mtx_in_els,
_iels, sign, rdc, cdc)
else:
raise ValueError('unknown assembling mode! (%s)' % mode)
| [
"sfepy.base.base.Container.append",
"sfepy.base.base.Struct",
"sfepy.terms.extmods.terms.append",
"sfepy.terms.term_table.keys",
"sfepy.base.base.get_default",
"sfepy.discrete.Integrals",
"sfepy.terms.extmods.terms.errclear",
"sfepy.base.base.Container.insert",
"sfepy.linalg.split_range",
"sfepy.d... | [((353, 391), 're.compile', 're.compile', (['"""^([^\\\\(\\\\}]*)\\\\((.*)\\\\)$"""'], {}), "('^([^\\\\(\\\\}]*)\\\\((.*)\\\\)$')\n", (363, 391), False, 'import re\n'), ((411, 434), 're.compile', 're.compile', (['"""^virtual$"""'], {}), "('^virtual$')\n", (421, 434), False, 'import re\n'), ((456, 494), 're.compile', 're.compile', (['"""^state(_[_a-zA-Z0-9]+)?$"""'], {}), "('^state(_[_a-zA-Z0-9]+)?$')\n", (466, 494), False, 'import re\n'), ((520, 562), 're.compile', 're.compile', (['"""^parameter(_[_a-zA-Z0-9]+)?$"""'], {}), "('^parameter(_[_a-zA-Z0-9]+)?$')\n", (530, 562), False, 'import re\n'), ((587, 628), 're.compile', 're.compile', (['"""^material(_[_a-zA-Z0-9]+)?$"""'], {}), "('^material(_[_a-zA-Z0-9]+)?$')\n", (597, 628), False, 'import re\n'), ((657, 702), 're.compile', 're.compile', (['"""^opt_material(_[_a-zA-Z0-9]+)?$"""'], {}), "('^opt_material(_[_a-zA-Z0-9]+)?$')\n", (667, 702), False, 'import re\n'), ((732, 757), 're.compile', 're.compile', (['"""(.+)\\\\.(.*)"""'], {}), "('(.+)\\\\.(.*)')\n", (742, 757), False, 'import re\n'), ((4445, 4480), 'sfepy.linalg.split_range', 'split_range', (['total_size', 'chunk_size'], {}), '(total_size, chunk_size)\n', (4456, 4480), False, 'from sfepy.linalg import split_range\n'), ((4490, 4517), 'numpy.array', 'nm.array', (['(0)'], {'dtype': 'nm.int32'}), '(0, dtype=nm.int32)\n', (4498, 4517), True, 'import numpy as nm\n'), ((4986, 5009), 'pyparsing.Word', 'Word', (["('+-' + nums)", 'nums'], {}), "('+-' + nums, nums)\n", (4990, 5009), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((5614, 5625), 'pyparsing.StringEnd', 'StringEnd', ([], {}), '()\n', (5623, 5625), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((8696, 8731), 'sfepy.base.base.Container.__init__', 'Container.__init__', (['self'], {'objs': 'objs'}), '(self, objs=objs)\n', (8714, 8731), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((8806, 8837), 'sfepy.base.base.Container.insert', 'Container.insert', (['self', 'ii', 'obj'], {}), '(self, ii, obj)\n', (8822, 8837), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((8907, 8934), 'sfepy.base.base.Container.append', 'Container.append', (['self', 'obj'], {}), '(self, obj)\n', (8923, 8934), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((13742, 13776), 'sfepy.base.base.Struct.get', 'Struct.get', (['self', '"""function"""', 'None'], {}), "(self, 'function', None)\n", (13752, 13776), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((17097, 17196), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""arg_names"""', 'material': '[]', 'variable': '[]', 'user': '[]', 'state': '[]', 'virtual': '[]', 'parameter': '[]'}), "(name='arg_names', material=[], variable=[], user=[], state=[],\n virtual=[], parameter=[])\n", (17103, 17196), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((21935, 21961), 'copy.copy', 'copy', (['self.names.parameter'], {}), '(self.names.parameter)\n', (21939, 21961), False, 'from copy import copy\n'), ((29985, 30073), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""dof_conn_info"""', 'type': 'self.dof_conn_type', 'region_name': 'self.region.name'}), "(name='dof_conn_info', type=self.dof_conn_type, region_name=self.\n region.name)\n", (29991, 30073), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((30383, 30418), 'numpy.arange', 'nm.arange', (['shape[0]'], {'dtype': 'nm.int32'}), '(shape[0], dtype=nm.int32)\n', (30392, 30418), True, 'import numpy as nm\n'), ((35945, 35984), 'sfepy.base.base.get_default', 'get_default', (['step', 'self.arg_steps[name]'], {}), '(step, self.arg_steps[name])\n', (35956, 35984), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((36011, 36067), 'sfepy.base.base.get_default', 'get_default', (['time_derivative', 'self.arg_derivatives[name]'], {}), '(time_derivative, self.arg_derivatives[name])\n', (36022, 36067), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((36128, 36179), 'sfepy.base.base.get_default', 'get_default', (['integration', 'self.geometry_types[name]'], {}), '(integration, self.geometry_types[name])\n', (36139, 36179), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((36897, 36931), 'sfepy.discrete.create_adof_conns', 'create_adof_conns', (['conn_info', 'None'], {}), '(conn_info, None)\n', (36914, 36931), False, 'from sfepy.discrete import create_adof_conns, Variables\n'), ((37846, 37879), 'numpy.empty', 'nm.empty', (['shape'], {'dtype': 'nm.float64'}), '(shape, dtype=nm.float64)\n', (37854, 37879), True, 'import numpy as nm\n'), ((38325, 38358), 'numpy.empty', 'nm.empty', (['shape'], {'dtype': 'nm.float64'}), '(shape, dtype=nm.float64)\n', (38333, 38358), True, 'import numpy as nm\n'), ((4557, 4588), 'numpy.arange', 'nm.arange', (['size'], {'dtype': 'nm.int32'}), '(size, dtype=nm.int32)\n', (4566, 4588), True, 'import numpy as nm\n'), ((4679, 4707), 'numpy.zeros', 'nm.zeros', (['shape'], {'dtype': 'dtype'}), '(shape, dtype=dtype)\n', (4687, 4707), True, 'import numpy as nm\n'), ((4740, 4768), 'numpy.empty', 'nm.empty', (['shape'], {'dtype': 'dtype'}), '(shape, dtype=dtype)\n', (4748, 4768), True, 'import numpy as nm\n'), ((5226, 5256), 'pyparsing.Word', 'Word', (['alphas', "(alphanums + '._')"], {}), "(alphas, alphanums + '._')\n", (5230, 5256), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((5368, 5381), 'pyparsing.Literal', 'Literal', (['"""dt"""'], {}), "('dt')\n", (5375, 5381), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((5565, 5578), 'pyparsing.StringStart', 'StringStart', ([], {}), '()\n', (5576, 5578), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((5581, 5611), 'pyparsing.delimitedList', 'delimitedList', (['generalized_var'], {}), '(generalized_var)\n', (5594, 5611), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((8611, 8629), 'sfepy.terms.extmods.terms.append', 'terms.append', (['term'], {}), '(term)\n', (8623, 8629), False, 'from sfepy.terms.extmods import terms\n'), ((12011, 12022), 'sfepy.discrete.Integrals', 'Integrals', ([], {}), '()\n', (12020, 12022), False, 'from sfepy.discrete import Integrals\n'), ((12669, 12695), 'sfepy.base.base.as_float_or_complex', 'as_float_or_complex', (['other'], {}), '(other)\n', (12688, 12695), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((18685, 18715), 'sfepy.base.base.Struct.get', 'Struct.get', (['self', '"""mode"""', 'None'], {}), "(self, 'mode', None)\n", (18695, 18715), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((33615, 33643), 'sfepy.discrete.common.mappings.PhysicalQPs', 'PhysicalQPs', (['self.region.igs'], {}), '(self.region.igs)\n', (33626, 33643), False, 'from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs\n'), ((37607, 37623), 'sfepy.terms.extmods.terms.errclear', 'terms.errclear', ([], {}), '()\n', (37621, 37623), False, 'from sfepy.terms.extmods import terms\n'), ((38636, 38669), 'numpy.empty', 'nm.empty', (['shape'], {'dtype': 'nm.float64'}), '(shape, dtype=nm.float64)\n', (38644, 38669), True, 'import numpy as nm\n'), ((33710, 33768), 'sfepy.discrete.common.mappings.get_physical_qps', 'get_physical_qps', (['self.region', 'self.integral'], {'map_kind': '"""v"""'}), "(self.region, self.integral, map_kind='v')\n", (33726, 33768), False, 'from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs\n'), ((33847, 33891), 'sfepy.discrete.common.mappings.get_physical_qps', 'get_physical_qps', (['self.region', 'self.integral'], {}), '(self.region, self.integral)\n', (33863, 33891), False, 'from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs\n'), ((37316, 37332), 'sfepy.terms.extmods.terms.errclear', 'terms.errclear', ([], {}), '()\n', (37330, 37332), False, 'from sfepy.terms.extmods import terms\n'), ((37529, 37545), 'sfepy.terms.extmods.terms.errclear', 'terms.errclear', ([], {}), '()\n', (37543, 37545), False, 'from sfepy.terms.extmods import terms\n'), ((38807, 38840), 'numpy.empty', 'nm.empty', (['shape'], {'dtype': 'nm.float64'}), '(shape, dtype=nm.float64)\n', (38815, 38840), True, 'import numpy as nm\n'), ((38932, 38965), 'numpy.empty', 'nm.empty', (['shape'], {'dtype': 'nm.float64'}), '(shape, dtype=nm.float64)\n', (38940, 38965), True, 'import numpy as nm\n'), ((41485, 41517), 'numpy.empty', 'nm.empty', (['(0, 2)'], {'dtype': 'nm.int32'}), '((0, 2), dtype=nm.int32)\n', (41493, 41517), True, 'import numpy as nm\n'), ((45150, 45189), 'sfepy.base.base.assert_', 'assert_', (['(asm_obj.dtype == nm.complex128)'], {}), '(asm_obj.dtype == nm.complex128)\n', (45157, 45189), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((45563, 45606), 'sfepy.base.base.assert_', 'assert_', (['(vec_in_els.shape[2] == dc.shape[1])'], {}), '(vec_in_els.shape[2] == dc.shape[1])\n', (45570, 45606), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((5292, 5304), 'pyparsing.Literal', 'Literal', (['"""d"""'], {}), "('d')\n", (5299, 5304), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((5402, 5415), 'pyparsing.Literal', 'Literal', (['"""tr"""'], {}), "('tr')\n", (5409, 5415), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((5475, 5487), 'pyparsing.Literal', 'Literal', (['""")"""'], {}), "(')')\n", (5482, 5487), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((20804, 20853), 'sfepy.base.compat.in1d', 'in1d', (['self.region.vertices', 'field.region.vertices'], {}), '(self.region.vertices, field.region.vertices)\n', (20808, 20853), False, 'from sfepy.base.compat import in1d\n'), ((37141, 37161), 'sfepy.base.base.Struct', 'Struct', ([], {'terms': '[self]'}), '(terms=[self])\n', (37147, 37161), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((38036, 38050), 'numpy.sum', 'nm.sum', (['out', '(0)'], {}), '(out, 0)\n', (38042, 38050), True, 'import numpy as nm\n'), ((39365, 39379), 'numpy.sum', 'nm.sum', (['out', '(0)'], {}), '(out, 0)\n', (39371, 39379), True, 'import numpy as nm\n'), ((45828, 45867), 'sfepy.base.base.assert_', 'assert_', (['(asm_obj.dtype == nm.complex128)'], {}), '(asm_obj.dtype == nm.complex128)\n', (45835, 45867), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((46482, 46543), 'sfepy.base.base.assert_', 'assert_', (['(mtx_in_els.shape[2:] == (rdc.shape[1], cdc.shape[1]))'], {}), '(mtx_in_els.shape[2:] == (rdc.shape[1], cdc.shape[1]))\n', (46489, 46543), False, 'from sfepy.base.base import as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions\n'), ((5093, 5105), 'pyparsing.Literal', 'Literal', (['"""]"""'], {}), "(']')\n", (5100, 5105), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((5342, 5354), 'pyparsing.Literal', 'Literal', (['"""/"""'], {}), "('/')\n", (5349, 5354), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((11687, 11704), 'sfepy.terms.term_table.keys', 'term_table.keys', ([], {}), '()\n', (11702, 11704), False, 'from sfepy.terms import term_table\n'), ((44421, 44440), 'numpy.isfinite', 'nm.isfinite', (['out[0]'], {}), '(out[0])\n', (44432, 44440), True, 'import numpy as nm\n'), ((45382, 45404), 'numpy.complex128', 'nm.complex128', (['val[ii]'], {}), '(val[ii])\n', (45395, 45404), True, 'import numpy as nm\n'), ((5034, 5046), 'pyparsing.Literal', 'Literal', (['"""["""'], {}), "('[')\n", (5041, 5046), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((5418, 5430), 'pyparsing.Literal', 'Literal', (['"""("""'], {}), "('(')\n", (5425, 5430), False, 'from pyparsing import Literal, Word, delimitedList, Group, StringStart, StringEnd, Optional, nums, alphas, alphanums\n'), ((8293, 8310), 'sfepy.terms.term_table.keys', 'term_table.keys', ([], {}), '()\n', (8308, 8310), False, 'from sfepy.terms import term_table\n'), ((42452, 42481), 'numpy.repeat', 'nm.repeat', (['ig', '_iels.shape[0]'], {}), '(ig, _iels.shape[0])\n', (42461, 42481), True, 'import numpy as nm\n')] |
"""
Functions to visualize quadrature points in reference elements.
"""
import numpy as nm
import matplotlib.pyplot as plt
from sfepy.base.base import output
from sfepy.postprocess.plot_dofs import _get_axes, _to2d
from sfepy.postprocess.plot_facets import plot_geometry
def _get_qp(geometry, order):
from sfepy.discrete import Integral
from sfepy.discrete.fem.geometry_element import GeometryElement
aux = Integral('aux', order=order)
coors, weights = aux.get_qp(geometry)
true_order = aux.qps[geometry].order
output('geometry:', geometry, 'order:', order, 'num. points:',
coors.shape[0], 'true_order:', true_order)
output('min. weight:', weights.min())
output('max. weight:', weights.max())
return GeometryElement(geometry), coors, weights
def _get_bqp(geometry, order):
from sfepy.discrete import Integral
from sfepy.discrete.fem.geometry_element import GeometryElement
from sfepy.discrete.fem import Mesh, FEDomain, Field
gel = GeometryElement(geometry)
mesh = Mesh.from_data('aux', gel.coors, None,
[gel.conn[None, :]], [[0]], [geometry])
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
surf = domain.create_region('Surf', 'vertices of surface', 'facet')
field = Field.from_args('f', nm.float64, shape=1,
region=omega, approx_order=1)
field.setup_surface_data(surf)
integral = Integral('aux', order=order)
field.create_bqp('Surf', integral)
sd = field.surface_data['Surf']
qp = field.qp_coors[(integral.order, sd.bkey)]
output('geometry:', geometry, 'order:', order, 'num. points:',
qp.vals.shape[1], 'true_order:',
integral.qps[gel.surface_facet_name].order)
output('min. weight:', qp.weights.min())
output('max. weight:', qp.weights.max())
return (gel, qp.vals.reshape((-1, mesh.dim)),
nm.tile(qp.weights, qp.vals.shape[0]))
def plot_weighted_points(ax, coors, weights, min_radius=10, max_radius=50,
show_colorbar=False):
"""
Plot points with given coordinates as circles/spheres with radii given by
weights.
"""
dim = coors.shape[1]
ax = _get_axes(ax, dim)
wmin, wmax = weights.min(), weights.max()
if (wmax - wmin) < 1e-12:
nweights = weights * max_radius / wmax
else:
nweights = ((weights - wmin) * (max_radius - min_radius)
/ (wmax - wmin) + min_radius)
coors = _to2d(coors)
sc = ax.scatter(*coors.T, s=nweights, c=weights, alpha=1)
if show_colorbar:
plt.colorbar(sc)
return ax
def label_points(ax, coors):
"""
Label points with their indices.
"""
dim = coors.shape[1]
ax = _get_axes(ax, dim)
shift = 0.02 * (coors.max(0) - coors.min(0))
ccs = coors + shift
for ic, cc in enumerate(ccs):
ax.text(*cc, s='%d' % ic, color='b')
def plot_quadrature(ax, geometry, order, boundary=False,
min_radius=10, max_radius=50,
show_colorbar=False, show_labels=False):
"""
Plot quadrature points for the given geometry and integration order.
The points are plotted as circles/spheres with radii given by quadrature
weights - the weights are mapped to [`min_radius`, `max_radius`] interval.
"""
if not boundary:
gel, coors, weights = _get_qp(geometry, order)
else:
gel, coors, weights = _get_bqp(geometry, order)
dim = coors.shape[1]
ax = _get_axes(ax, dim)
plot_geometry(ax, gel)
plot_weighted_points(ax, coors, weights,
min_radius=min_radius, max_radius=max_radius,
show_colorbar=show_colorbar)
if show_labels:
label_points(ax, coors)
return ax, coors, weights
| [
"sfepy.postprocess.plot_dofs._to2d",
"sfepy.discrete.fem.geometry_element.GeometryElement",
"sfepy.base.base.output",
"sfepy.postprocess.plot_dofs._get_axes",
"sfepy.discrete.fem.Mesh.from_data",
"sfepy.discrete.Integral",
"sfepy.discrete.fem.Field.from_args",
"sfepy.postprocess.plot_facets.plot_geome... | [((423, 451), 'sfepy.discrete.Integral', 'Integral', (['"""aux"""'], {'order': 'order'}), "('aux', order=order)\n", (431, 451), False, 'from sfepy.discrete import Integral\n'), ((540, 650), 'sfepy.base.base.output', 'output', (['"""geometry:"""', 'geometry', '"""order:"""', 'order', '"""num. points:"""', 'coors.shape[0]', '"""true_order:"""', 'true_order'], {}), "('geometry:', geometry, 'order:', order, 'num. points:', coors.shape[\n 0], 'true_order:', true_order)\n", (546, 650), False, 'from sfepy.base.base import output\n'), ((1003, 1028), 'sfepy.discrete.fem.geometry_element.GeometryElement', 'GeometryElement', (['geometry'], {}), '(geometry)\n', (1018, 1028), False, 'from sfepy.discrete.fem.geometry_element import GeometryElement\n'), ((1041, 1119), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (['"""aux"""', 'gel.coors', 'None', '[gel.conn[None, :]]', '[[0]]', '[geometry]'], {}), "('aux', gel.coors, None, [gel.conn[None, :]], [[0]], [geometry])\n", (1055, 1119), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1159, 1183), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""domain"""', 'mesh'], {}), "('domain', mesh)\n", (1167, 1183), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1318, 1389), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""f"""', 'nm.float64'], {'shape': '(1)', 'region': 'omega', 'approx_order': '(1)'}), "('f', nm.float64, shape=1, region=omega, approx_order=1)\n", (1333, 1389), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1469, 1497), 'sfepy.discrete.Integral', 'Integral', (['"""aux"""'], {'order': 'order'}), "('aux', order=order)\n", (1477, 1497), False, 'from sfepy.discrete import Integral\n'), ((1630, 1774), 'sfepy.base.base.output', 'output', (['"""geometry:"""', 'geometry', '"""order:"""', 'order', '"""num. points:"""', 'qp.vals.shape[1]', '"""true_order:"""', 'integral.qps[gel.surface_facet_name].order'], {}), "('geometry:', geometry, 'order:', order, 'num. points:', qp.vals.\n shape[1], 'true_order:', integral.qps[gel.surface_facet_name].order)\n", (1636, 1774), False, 'from sfepy.base.base import output\n'), ((2248, 2266), 'sfepy.postprocess.plot_dofs._get_axes', '_get_axes', (['ax', 'dim'], {}), '(ax, dim)\n', (2257, 2266), False, 'from sfepy.postprocess.plot_dofs import _get_axes, _to2d\n'), ((2530, 2542), 'sfepy.postprocess.plot_dofs._to2d', '_to2d', (['coors'], {}), '(coors)\n', (2535, 2542), False, 'from sfepy.postprocess.plot_dofs import _get_axes, _to2d\n'), ((2785, 2803), 'sfepy.postprocess.plot_dofs._get_axes', '_get_axes', (['ax', 'dim'], {}), '(ax, dim)\n', (2794, 2803), False, 'from sfepy.postprocess.plot_dofs import _get_axes, _to2d\n'), ((3551, 3569), 'sfepy.postprocess.plot_dofs._get_axes', '_get_axes', (['ax', 'dim'], {}), '(ax, dim)\n', (3560, 3569), False, 'from sfepy.postprocess.plot_dofs import _get_axes, _to2d\n'), ((3575, 3597), 'sfepy.postprocess.plot_facets.plot_geometry', 'plot_geometry', (['ax', 'gel'], {}), '(ax, gel)\n', (3588, 3597), False, 'from sfepy.postprocess.plot_facets import plot_geometry\n'), ((753, 778), 'sfepy.discrete.fem.geometry_element.GeometryElement', 'GeometryElement', (['geometry'], {}), '(geometry)\n', (768, 778), False, 'from sfepy.discrete.fem.geometry_element import GeometryElement\n'), ((1945, 1982), 'numpy.tile', 'nm.tile', (['qp.weights', 'qp.vals.shape[0]'], {}), '(qp.weights, qp.vals.shape[0])\n', (1952, 1982), True, 'import numpy as nm\n'), ((2636, 2652), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['sc'], {}), '(sc)\n', (2648, 2652), True, 'import matplotlib.pyplot as plt\n')] |
import numpy as np
from sfepy.base.goptions import goptions
from sfepy.discrete.fem import Field
try:
from sfepy.discrete.fem import FEDomain as Domain
except ImportError:
from sfepy.discrete.fem import Domain
from sfepy.discrete import (FieldVariable, Material, Integral, Function,
Equation, Equations, Problem)
from sfepy.terms import Term
from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC
from sfepy.solvers.ls import ScipyDirect
from sfepy.solvers.nls import Newton
import sfepy.discrete.fem.periodic as per
from sfepy.discrete import Functions
from sfepy.mesh.mesh_generators import gen_block_mesh
from sfepy.mechanics.matcoefs import ElasticConstants
from sfepy.base.base import output
from sfepy.discrete.conditions import LinearCombinationBC
goptions['verbose'] = False
output.set_output(quiet=True)
class ElasticFESimulation(object):
"""
Use SfePy to solve a linear strain problem in 2D with a varying
microstructure on a rectangular grid. The rectangle (cube) is held
at the negative edge (plane) and displaced by 1 on the positive x
edge (plane). Periodic boundary conditions are applied to the
other boundaries.
The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x,
n_y, n_z).
>>> X = np.zeros((1, 3, 3), dtype=int)
>>> X[0, :, 1] = 1
>>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0),
... poissons_ratio=(0., 0.))
>>> sim.run(X)
>>> y = sim.strain
y is the strain with components as follows
>>> exx = y[..., 0]
>>> eyy = y[..., 1]
>>> exy = y[..., 2]
In this example, the strain is only in the x-direction and has a
uniform value of 1 since the displacement is always 1 and the size
of the domain is 1.
>>> assert np.allclose(exx, 1)
>>> assert np.allclose(eyy, 0)
>>> assert np.allclose(exy, 0)
The following example is for a system with contrast. It tests the
left/right periodic offset and the top/bottom periodicity.
>>> X = np.array([[[1, 0, 0, 1],
... [0, 1, 1, 1],
... [0, 0, 1, 1],
... [1, 0, 0, 1]]])
>>> n_samples, N, N = X.shape
>>> macro_strain = 0.1
>>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1)
>>> sim.run(X)
>>> u = sim.displacement[0]
Check that the offset for the left/right planes is `N *
macro_strain`.
>>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain)
Check that the left/right side planes are periodic in y.
>>> assert np.allclose(u[0,:,1], u[-1,:,1])
Check that the top/bottom planes are periodic in both x and y.
>>> assert np.allclose(u[:,0], u[:,-1])
"""
def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,):
"""Instantiate a ElasticFESimulation.
Args:
elastic_modulus (1D array): array of elastic moduli for phases
poissons_ratio (1D array): array of Possion's ratios for phases
macro_strain (float, optional): Scalar for macroscopic strain
"""
self.macro_strain = macro_strain
self.dx = 1.0
self.elastic_modulus = elastic_modulus
self.poissons_ratio = poissons_ratio
if len(elastic_modulus) != len(poissons_ratio):
raise RuntimeError(
'elastic_modulus and poissons_ratio must be the same length')
def _convert_properties(self, dim):
"""
Convert from elastic modulus and Poisson's ratio to the Lame
parameter and shear modulus
>>> model = ElasticFESimulation(elastic_modulus=(1., 2.),
... poissons_ratio=(1., 1.))
>>> result = model._convert_properties(2)
>>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]])
>>> assert(np.allclose(result, answer))
Args:
dim (int): Scalar value for the dimension of the microstructure.
Returns:
array with the Lame parameter and the shear modulus for each phase.
"""
def _convert(E, nu):
ec = ElasticConstants(young=E, poisson=nu)
mu = dim / 3. * ec.mu
lame = ec.lam
return lame, mu
return np.array([_convert(E, nu) for E,
nu in zip(self.elastic_modulus, self.poissons_ratio)])
def _get_property_array(self, X):
"""
Generate property array with elastic_modulus and poissons_ratio for
each phase.
Test case for 2D with 3 phases.
>>> X2D = np.array([[[0, 1, 2, 1],
... [2, 1, 0, 0],
... [1, 0, 2, 2]]])
>>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.),
... poissons_ratio=(1., 1., 1.))
>>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5
>>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2
>>> lm = zip(lame, mu)
>>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]],
... [lm[2], lm[1], lm[0], lm[0]],
... [lm[1], lm[0], lm[2], lm[2]]])
>>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property))
Test case for 3D with 2 phases.
>>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.),
... poissons_ratio=(1., 1.))
>>> X3D = np.array([[[0, 1],
... [0, 0]],
... [[1, 1],
... [0, 1]]])
>>> X3D_property = np.array([[[lm[0], lm[1]],
... [lm[0], lm[0]]],
... [[lm[1], lm[1]],
... [lm[0], lm[1]]]])
>>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property))
"""
dim = len(X.shape) - 1
n_phases = len(self.elastic_modulus)
if not issubclass(X.dtype.type, np.integer):
raise TypeError("X must be an integer array")
if np.max(X) >= n_phases or np.min(X) < 0:
raise RuntimeError(
"X must be between 0 and {N}.".format(N=n_phases - 1))
if not (2 <= dim <= 3):
raise RuntimeError("the shape of X is incorrect")
return self._convert_properties(dim)[X]
def run(self, X):
"""
Run the simulation.
Args:
X (ND array): microstructure with shape (n_samples, n_x, ...)
"""
X_property = self._get_property_array(X)
strain = []
displacement = []
stress = []
for x in X_property:
strain_, displacement_, stress_ = self._solve(x)
strain.append(strain_)
displacement.append(displacement_)
stress.append(stress_)
self.strain = np.array(strain)
self.displacement = np.array(displacement)
self.stress = np.array(stress)
@property
def response(self):
return self.strain[..., 0]
def _get_material(self, property_array, domain):
"""
Creates an SfePy material from the material property fields for the
quadrature points.
Args:
property_array: array of the properties with shape (n_x, n_y, n_z, 2)
Returns:
an SfePy material
"""
min_xyz = domain.get_mesh_bounding_box()[0]
dims = domain.get_mesh_bounding_box().shape[1]
def _material_func_(ts, coors, mode=None, **kwargs):
if mode == 'qp':
ijk_out = np.empty_like(coors, dtype=int)
ijk = np.floor((coors - min_xyz[None]) / self.dx,
ijk_out, casting="unsafe")
ijk_tuple = tuple(ijk.swapaxes(0, 1))
property_array_qp = property_array[ijk_tuple]
lam = property_array_qp[..., 0]
mu = property_array_qp[..., 1]
lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1)))
mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1)))
from sfepy.mechanics.matcoefs import stiffness_from_lame
stiffness = stiffness_from_lame(dims, lam=lam, mu=mu)
return {'lam': lam, 'mu': mu, 'D': stiffness}
else:
return
material_func = Function('material_func', _material_func_)
return Material('m', function=material_func)
def _subdomain_func(self, x=(), y=(), z=(), max_x=None):
"""
Creates a function to mask subdomains in Sfepy.
Args:
x: tuple of lines or points to be masked in the x-plane
y: tuple of lines or points to be masked in the y-plane
z: tuple of lines or points to be masked in the z-plane
Returns:
array of masked location indices
"""
eps = 1e-3 * self.dx
def _func(coords, domain=None):
flag_x = len(x) == 0
flag_y = len(y) == 0
flag_z = len(z) == 0
for x_ in x:
flag = (coords[:, 0] < (x_ + eps)) & \
(coords[:, 0] > (x_ - eps))
flag_x = flag_x | flag
for y_ in y:
flag = (coords[:, 1] < (y_ + eps)) & \
(coords[:, 1] > (y_ - eps))
flag_y = flag_y | flag
for z_ in z:
flag = (coords[:, 2] < (z_ + eps)) & \
(coords[:, 2] > (z_ - eps))
flag_z = flag_z | flag
flag = flag_x & flag_y & flag_z
if max_x is not None:
flag = flag & (coords[:, 0] < (max_x - eps))
return np.where(flag)[0]
return _func
def _get_mesh(self, shape):
"""
Generate an Sfepy rectangular mesh
Args:
shape: proposed shape of domain (vertex shape) (n_x, n_y)
Returns:
Sfepy mesh
"""
center = np.zeros_like(shape)
return gen_block_mesh(shape, np.array(shape) + 1, center,
verbose=False)
def _get_fixed_displacementsBCs(self, domain):
"""
Fix the left top and bottom points in x, y and z
Args:
domain: an Sfepy domain
Returns:
the Sfepy boundary conditions
"""
min_xyz = domain.get_mesh_bounding_box()[0]
max_xyz = domain.get_mesh_bounding_box()[1]
kwargs = {}
fix_points_dict = {'u.0': 0.0, 'u.1': 0.0}
if len(min_xyz) == 3:
kwargs = {'z': (max_xyz[2], min_xyz[2])}
fix_points_dict['u.2'] = 0.0
fix_x_points_ = self._subdomain_func(x=(min_xyz[0],),
y=(max_xyz[1], min_xyz[1]),
**kwargs)
fix_x_points = Function('fix_x_points', fix_x_points_)
region_fix_points = domain.create_region(
'region_fix_points',
'vertices by fix_x_points',
'vertex',
functions=Functions([fix_x_points]))
return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict)
def _get_shift_displacementsBCs(self, domain):
"""
Fix the right top and bottom points in x, y and z
Args:
domain: an Sfepy domain
Returns:
the Sfepy boundary conditions
"""
min_xyz = domain.get_mesh_bounding_box()[0]
max_xyz = domain.get_mesh_bounding_box()[1]
kwargs = {}
if len(min_xyz) == 3:
kwargs = {'z': (max_xyz[2], min_xyz[2])}
displacement = self.macro_strain * (max_xyz[0] - min_xyz[0])
shift_points_dict = {'u.0': displacement}
shift_x_points_ = self._subdomain_func(x=(max_xyz[0],),
y=(max_xyz[1], min_xyz[1]),
**kwargs)
shift_x_points = Function('shift_x_points', shift_x_points_)
region_shift_points = domain.create_region(
'region_shift_points',
'vertices by shift_x_points',
'vertex',
functions=Functions([shift_x_points]))
return EssentialBC('shift_points_BC',
region_shift_points, shift_points_dict)
def _get_displacementBCs(self, domain):
shift_points_BC = self._get_shift_displacementsBCs(domain)
fix_points_BC = self._get_fixed_displacementsBCs(domain)
return Conditions([fix_points_BC, shift_points_BC])
def _get_linear_combinationBCs(self, domain):
"""
The right nodes are periodic with the left nodes but also displaced.
Args:
domain: an Sfepy domain
Returns:
the Sfepy boundary conditions
"""
min_xyz = domain.get_mesh_bounding_box()[0]
max_xyz = domain.get_mesh_bounding_box()[1]
xplus_ = self._subdomain_func(x=(max_xyz[0],))
xminus_ = self._subdomain_func(x=(min_xyz[0],))
xplus = Function('xplus', xplus_)
xminus = Function('xminus', xminus_)
region_x_plus = domain.create_region('region_x_plus',
'vertices by xplus',
'facet',
functions=Functions([xplus]))
region_x_minus = domain.create_region('region_x_minus',
'vertices by xminus',
'facet',
functions=Functions([xminus]))
match_x_plane = Function('match_x_plane', per.match_x_plane)
def shift_(ts, coors, region):
return np.ones_like(coors[:, 0]) * \
self.macro_strain * (max_xyz[0] - min_xyz[0])
shift = Function('shift', shift_)
lcbc = LinearCombinationBC(
'lcbc', [region_x_plus, region_x_minus], {
'u.0': 'u.0'}, match_x_plane, 'shifted_periodic',
arguments=(shift,))
return Conditions([lcbc])
def _get_periodicBC_X(self, domain, dim):
dim_dict = {1: ('y', per.match_y_plane),
2: ('z', per.match_z_plane)}
dim_string = dim_dict[dim][0]
match_plane = dim_dict[dim][1]
min_, max_ = domain.get_mesh_bounding_box()[:, dim]
min_x, max_x = domain.get_mesh_bounding_box()[:, 0]
plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)})
minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)})
plus_string = dim_string + 'plus'
minus_string = dim_string + 'minus'
plus = Function(plus_string, plus_)
minus = Function(minus_string, minus_)
region_plus = domain.create_region(
'region_{0}_plus'.format(dim_string),
'vertices by {0}'.format(
plus_string),
'facet',
functions=Functions([plus]))
region_minus = domain.create_region(
'region_{0}_minus'.format(dim_string),
'vertices by {0}'.format(
minus_string),
'facet',
functions=Functions([minus]))
match_plane = Function(
'match_{0}_plane'.format(dim_string), match_plane)
bc_dict = {'u.0': 'u.0'}
bc = PeriodicBC('periodic_{0}'.format(dim_string),
[region_plus, region_minus],
bc_dict,
match='match_{0}_plane'.format(dim_string))
return bc, match_plane
def _get_periodicBC_YZ(self, domain, dim):
dims = domain.get_mesh_bounding_box().shape[1]
dim_dict = {0: ('x', per.match_x_plane),
1: ('y', per.match_y_plane),
2: ('z', per.match_z_plane)}
dim_string = dim_dict[dim][0]
match_plane = dim_dict[dim][1]
min_, max_ = domain.get_mesh_bounding_box()[:, dim]
plus_ = self._subdomain_func(**{dim_string: (max_,)})
minus_ = self._subdomain_func(**{dim_string: (min_,)})
plus_string = dim_string + 'plus'
minus_string = dim_string + 'minus'
plus = Function(plus_string, plus_)
minus = Function(minus_string, minus_)
region_plus = domain.create_region(
'region_{0}_plus'.format(dim_string),
'vertices by {0}'.format(
plus_string),
'facet',
functions=Functions([plus]))
region_minus = domain.create_region(
'region_{0}_minus'.format(dim_string),
'vertices by {0}'.format(
minus_string),
'facet',
functions=Functions([minus]))
match_plane = Function(
'match_{0}_plane'.format(dim_string), match_plane)
bc_dict = {'u.1': 'u.1'}
if dims == 3:
bc_dict['u.2'] = 'u.2'
bc = PeriodicBC('periodic_{0}'.format(dim_string),
[region_plus, region_minus],
bc_dict,
match='match_{0}_plane'.format(dim_string))
return bc, match_plane
def _solve(self, property_array):
"""
Solve the Sfepy problem for one sample.
Args:
property_array: array of shape (n_x, n_y, 2) where the last
index is for Lame's parameter and shear modulus,
respectively.
Returns:
the strain field of shape (n_x, n_y, 2) where the last
index represents the x and y displacements
"""
shape = property_array.shape[:-1]
mesh = self._get_mesh(shape)
domain = Domain('domain', mesh)
region_all = domain.create_region('region_all', 'all')
field = Field.from_args('fu', np.float64, 'vector', region_all,
approx_order=2)
u = FieldVariable('u', 'unknown', field)
v = FieldVariable('v', 'test', field, primary_var_name='u')
m = self._get_material(property_array, domain)
integral = Integral('i', order=4)
t1 = Term.new('dw_lin_elastic_iso(m.lam, m.mu, v, u)',
integral, region_all, m=m, v=v, u=u)
eq = Equation('balance_of_forces', t1)
eqs = Equations([eq])
epbcs, functions = self._get_periodicBCs(domain)
ebcs = self._get_displacementBCs(domain)
lcbcs = self._get_linear_combinationBCs(domain)
ls = ScipyDirect({})
pb = Problem('elasticity', equations=eqs, auto_solvers=None)
pb.time_update(
ebcs=ebcs, epbcs=epbcs, lcbcs=lcbcs, functions=functions)
ev = pb.get_evaluator()
nls = Newton({}, lin_solver=ls,
fun=ev.eval_residual, fun_grad=ev.eval_tangent_matrix)
try:
pb.set_solvers_instances(ls, nls)
except AttributeError:
pb.set_solver(nls)
vec = pb.solve()
u = vec.create_output_dict()['u'].data
u_reshape = np.reshape(u, (tuple(x + 1 for x in shape) + u.shape[-1:]))
dims = domain.get_mesh_bounding_box().shape[1]
strain = np.squeeze(
pb.evaluate(
'ev_cauchy_strain.{dim}.region_all(u)'.format(
dim=dims),
mode='el_avg',
copy_materials=False))
strain_reshape = np.reshape(strain, (shape + strain.shape[-1:]))
stress = np.squeeze(
pb.evaluate(
'ev_cauchy_stress.{dim}.region_all(m.D, u)'.format(
dim=dims),
mode='el_avg',
copy_materials=False))
stress_reshape = np.reshape(stress, (shape + stress.shape[-1:]))
return strain_reshape, u_reshape, stress_reshape
def _get_periodicBCs(self, domain):
dims = domain.get_mesh_bounding_box().shape[1]
bc_list_YZ, func_list_YZ = list(
zip(*[self._get_periodicBC_YZ(domain, i) for i in range(0, dims)]))
bc_list_X, func_list_X = list(
zip(*[self._get_periodicBC_X(domain, i) for i in range(1, dims)]))
return Conditions(
bc_list_YZ + bc_list_X), Functions(func_list_YZ + func_list_X)
| [
"sfepy.discrete.conditions.EssentialBC",
"sfepy.base.base.output.set_output",
"sfepy.discrete.Integral",
"sfepy.solvers.ls.ScipyDirect",
"sfepy.discrete.Equations",
"sfepy.discrete.fem.Field.from_args",
"sfepy.discrete.Equation",
"sfepy.discrete.Function",
"sfepy.mechanics.matcoefs.stiffness_from_la... | [((839, 868), 'sfepy.base.base.output.set_output', 'output.set_output', ([], {'quiet': '(True)'}), '(quiet=True)\n', (856, 868), False, 'from sfepy.base.base import output\n'), ((6954, 6970), 'numpy.array', 'np.array', (['strain'], {}), '(strain)\n', (6962, 6970), True, 'import numpy as np\n'), ((6999, 7021), 'numpy.array', 'np.array', (['displacement'], {}), '(displacement)\n', (7007, 7021), True, 'import numpy as np\n'), ((7044, 7060), 'numpy.array', 'np.array', (['stress'], {}), '(stress)\n', (7052, 7060), True, 'import numpy as np\n'), ((8474, 8516), 'sfepy.discrete.Function', 'Function', (['"""material_func"""', '_material_func_'], {}), "('material_func', _material_func_)\n", (8482, 8516), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((8532, 8569), 'sfepy.discrete.Material', 'Material', (['"""m"""'], {'function': 'material_func'}), "('m', function=material_func)\n", (8540, 8569), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((10104, 10124), 'numpy.zeros_like', 'np.zeros_like', (['shape'], {}), '(shape)\n', (10117, 10124), True, 'import numpy as np\n'), ((10991, 11030), 'sfepy.discrete.Function', 'Function', (['"""fix_x_points"""', 'fix_x_points_'], {}), "('fix_x_points', fix_x_points_)\n", (10999, 11030), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((11240, 11304), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""fix_points_BC"""', 'region_fix_points', 'fix_points_dict'], {}), "('fix_points_BC', region_fix_points, fix_points_dict)\n", (11251, 11304), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC\n'), ((12097, 12140), 'sfepy.discrete.Function', 'Function', (['"""shift_x_points"""', 'shift_x_points_'], {}), "('shift_x_points', shift_x_points_)\n", (12105, 12140), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((12358, 12428), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""shift_points_BC"""', 'region_shift_points', 'shift_points_dict'], {}), "('shift_points_BC', region_shift_points, shift_points_dict)\n", (12369, 12428), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC\n'), ((12648, 12692), 'sfepy.discrete.conditions.Conditions', 'Conditions', (['[fix_points_BC, shift_points_BC]'], {}), '([fix_points_BC, shift_points_BC])\n', (12658, 12692), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC\n'), ((13185, 13210), 'sfepy.discrete.Function', 'Function', (['"""xplus"""', 'xplus_'], {}), "('xplus', xplus_)\n", (13193, 13210), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((13228, 13255), 'sfepy.discrete.Function', 'Function', (['"""xminus"""', 'xminus_'], {}), "('xminus', xminus_)\n", (13236, 13255), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((13801, 13845), 'sfepy.discrete.Function', 'Function', (['"""match_x_plane"""', 'per.match_x_plane'], {}), "('match_x_plane', per.match_x_plane)\n", (13809, 13845), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((14013, 14038), 'sfepy.discrete.Function', 'Function', (['"""shift"""', 'shift_'], {}), "('shift', shift_)\n", (14021, 14038), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((14054, 14189), 'sfepy.discrete.conditions.LinearCombinationBC', 'LinearCombinationBC', (['"""lcbc"""', '[region_x_plus, region_x_minus]', "{'u.0': 'u.0'}", 'match_x_plane', '"""shifted_periodic"""'], {'arguments': '(shift,)'}), "('lcbc', [region_x_plus, region_x_minus], {'u.0': 'u.0'},\n match_x_plane, 'shifted_periodic', arguments=(shift,))\n", (14073, 14189), False, 'from sfepy.discrete.conditions import LinearCombinationBC\n'), ((14244, 14262), 'sfepy.discrete.conditions.Conditions', 'Conditions', (['[lcbc]'], {}), '([lcbc])\n', (14254, 14262), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC\n'), ((14857, 14885), 'sfepy.discrete.Function', 'Function', (['plus_string', 'plus_'], {}), '(plus_string, plus_)\n', (14865, 14885), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((14902, 14932), 'sfepy.discrete.Function', 'Function', (['minus_string', 'minus_'], {}), '(minus_string, minus_)\n', (14910, 14932), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((16372, 16400), 'sfepy.discrete.Function', 'Function', (['plus_string', 'plus_'], {}), '(plus_string, plus_)\n', (16380, 16400), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((16417, 16447), 'sfepy.discrete.Function', 'Function', (['minus_string', 'minus_'], {}), '(minus_string, minus_)\n', (16425, 16447), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((17843, 17865), 'sfepy.discrete.fem.Domain', 'Domain', (['"""domain"""', 'mesh'], {}), "('domain', mesh)\n", (17849, 17865), False, 'from sfepy.discrete.fem import Domain\n'), ((17947, 18018), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""fu"""', 'np.float64', '"""vector"""', 'region_all'], {'approx_order': '(2)'}), "('fu', np.float64, 'vector', region_all, approx_order=2)\n", (17962, 18018), False, 'from sfepy.discrete.fem import Field\n'), ((18064, 18100), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""u"""', '"""unknown"""', 'field'], {}), "('u', 'unknown', field)\n", (18077, 18100), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((18113, 18168), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""v"""', '"""test"""', 'field'], {'primary_var_name': '"""u"""'}), "('v', 'test', field, primary_var_name='u')\n", (18126, 18168), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((18245, 18267), 'sfepy.discrete.Integral', 'Integral', (['"""i"""'], {'order': '(4)'}), "('i', order=4)\n", (18253, 18267), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((18282, 18372), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_lin_elastic_iso(m.lam, m.mu, v, u)"""', 'integral', 'region_all'], {'m': 'm', 'v': 'v', 'u': 'u'}), "('dw_lin_elastic_iso(m.lam, m.mu, v, u)', integral, region_all, m=m,\n v=v, u=u)\n", (18290, 18372), False, 'from sfepy.terms import Term\n'), ((18404, 18437), 'sfepy.discrete.Equation', 'Equation', (['"""balance_of_forces"""', 't1'], {}), "('balance_of_forces', t1)\n", (18412, 18437), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((18452, 18467), 'sfepy.discrete.Equations', 'Equations', (['[eq]'], {}), '([eq])\n', (18461, 18467), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((18645, 18660), 'sfepy.solvers.ls.ScipyDirect', 'ScipyDirect', (['{}'], {}), '({})\n', (18656, 18660), False, 'from sfepy.solvers.ls import ScipyDirect\n'), ((18675, 18730), 'sfepy.discrete.Problem', 'Problem', (['"""elasticity"""'], {'equations': 'eqs', 'auto_solvers': 'None'}), "('elasticity', equations=eqs, auto_solvers=None)\n", (18682, 18730), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((18873, 18958), 'sfepy.solvers.nls.Newton', 'Newton', (['{}'], {'lin_solver': 'ls', 'fun': 'ev.eval_residual', 'fun_grad': 'ev.eval_tangent_matrix'}), '({}, lin_solver=ls, fun=ev.eval_residual, fun_grad=ev.eval_tangent_matrix\n )\n', (18879, 18958), False, 'from sfepy.solvers.nls import Newton\n'), ((19550, 19595), 'numpy.reshape', 'np.reshape', (['strain', '(shape + strain.shape[-1:])'], {}), '(strain, shape + strain.shape[-1:])\n', (19560, 19595), True, 'import numpy as np\n'), ((19847, 19892), 'numpy.reshape', 'np.reshape', (['stress', '(shape + stress.shape[-1:])'], {}), '(stress, shape + stress.shape[-1:])\n', (19857, 19892), True, 'import numpy as np\n'), ((4180, 4217), 'sfepy.mechanics.matcoefs.ElasticConstants', 'ElasticConstants', ([], {'young': 'E', 'poisson': 'nu'}), '(young=E, poisson=nu)\n', (4196, 4217), False, 'from sfepy.mechanics.matcoefs import ElasticConstants\n'), ((20304, 20338), 'sfepy.discrete.conditions.Conditions', 'Conditions', (['(bc_list_YZ + bc_list_X)'], {}), '(bc_list_YZ + bc_list_X)\n', (20314, 20338), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC\n'), ((20353, 20390), 'sfepy.discrete.Functions', 'Functions', (['(func_list_YZ + func_list_X)'], {}), '(func_list_YZ + func_list_X)\n', (20362, 20390), False, 'from sfepy.discrete import Functions\n'), ((6163, 6172), 'numpy.max', 'np.max', (['X'], {}), '(X)\n', (6169, 6172), True, 'import numpy as np\n'), ((6188, 6197), 'numpy.min', 'np.min', (['X'], {}), '(X)\n', (6194, 6197), True, 'import numpy as np\n'), ((7682, 7713), 'numpy.empty_like', 'np.empty_like', (['coors'], {'dtype': 'int'}), '(coors, dtype=int)\n', (7695, 7713), True, 'import numpy as np\n'), ((7736, 7806), 'numpy.floor', 'np.floor', (['((coors - min_xyz[None]) / self.dx)', 'ijk_out'], {'casting': '"""unsafe"""'}), "((coors - min_xyz[None]) / self.dx, ijk_out, casting='unsafe')\n", (7744, 7806), True, 'import numpy as np\n'), ((8304, 8345), 'sfepy.mechanics.matcoefs.stiffness_from_lame', 'stiffness_from_lame', (['dims'], {'lam': 'lam', 'mu': 'mu'}), '(dims, lam=lam, mu=mu)\n', (8323, 8345), False, 'from sfepy.mechanics.matcoefs import stiffness_from_lame\n'), ((9824, 9838), 'numpy.where', 'np.where', (['flag'], {}), '(flag)\n', (9832, 9838), True, 'import numpy as np\n'), ((10162, 10177), 'numpy.array', 'np.array', (['shape'], {}), '(shape)\n', (10170, 10177), True, 'import numpy as np\n'), ((11198, 11223), 'sfepy.discrete.Functions', 'Functions', (['[fix_x_points]'], {}), '([fix_x_points])\n', (11207, 11223), False, 'from sfepy.discrete import Functions\n'), ((12314, 12341), 'sfepy.discrete.Functions', 'Functions', (['[shift_x_points]'], {}), '([shift_x_points])\n', (12323, 12341), False, 'from sfepy.discrete import Functions\n'), ((13493, 13511), 'sfepy.discrete.Functions', 'Functions', (['[xplus]'], {}), '([xplus])\n', (13502, 13511), False, 'from sfepy.discrete import Functions\n'), ((13756, 13775), 'sfepy.discrete.Functions', 'Functions', (['[xminus]'], {}), '([xminus])\n', (13765, 13775), False, 'from sfepy.discrete import Functions\n'), ((15138, 15155), 'sfepy.discrete.Functions', 'Functions', (['[plus]'], {}), '([plus])\n', (15147, 15155), False, 'from sfepy.discrete import Functions\n'), ((15365, 15383), 'sfepy.discrete.Functions', 'Functions', (['[minus]'], {}), '([minus])\n', (15374, 15383), False, 'from sfepy.discrete import Functions\n'), ((16653, 16670), 'sfepy.discrete.Functions', 'Functions', (['[plus]'], {}), '([plus])\n', (16662, 16670), False, 'from sfepy.discrete import Functions\n'), ((16880, 16898), 'sfepy.discrete.Functions', 'Functions', (['[minus]'], {}), '([minus])\n', (16889, 16898), False, 'from sfepy.discrete import Functions\n'), ((13905, 13930), 'numpy.ones_like', 'np.ones_like', (['coors[:, 0]'], {}), '(coors[:, 0])\n', (13917, 13930), True, 'import numpy as np\n')] |
"""
Utility functions based on igakit.
"""
import numpy as nm
from sfepy.base.base import Struct
from sfepy.discrete.fem import Mesh
from sfepy.mesh.mesh_generators import get_tensor_product_conn
def create_linear_fe_mesh(nurbs, pars=None):
"""
Convert a NURBS object into a nD-linear tensor product FE mesh.
Parameters
----------
nurbs : igakit.nurbs.NURBS instance
The NURBS object.
pars : sequence of array, optional
The values of parameters in each parametric dimension. If not given,
the values are set so that the resulting mesh has the same number of
vertices as the number of control points/basis functions of the NURBS
object.
Returns
-------
coors : array
The coordinates of mesh vertices.
conn : array
The vertex connectivity array.
desc : str
The cell kind.
"""
knots = nurbs.knots
shape = nurbs.weights.shape
if pars is None:
pars = []
for ii, kv in enumerate(knots):
par = nm.linspace(kv[0], kv[-1], shape[ii])
pars.append(par)
coors = nurbs(*pars)
coors.shape = (-1, coors.shape[-1])
conn, desc = get_tensor_product_conn([len(ii) for ii in pars])
if (coors[:, -1] == 0.0).all():
coors = coors[:, :-1]
return coors, conn, desc
def create_mesh_and_output(nurbs, pars=None, **kwargs):
"""
Create a nD-linear tensor product FE mesh using
:func:`create_linear_fe_mesh()`, evaluate field variables given as keyword
arguments in the mesh vertices and create a dictionary of output data
usable by Mesh.write().
Parameters
----------
nurbs : igakit.nurbs.NURBS instance
The NURBS object.
pars : sequence of array, optional
The values of parameters in each parametric dimension. If not given,
the values are set so that the resulting mesh has the same number of
vertices as the number of control points/basis functions of the NURBS
object.
**kwargs : kwargs
The field variables as keyword arguments. Their names serve as keys in
the output dictionary.
Returns
-------
mesh : Mesh instance
The finite element mesh.
out : dict
The output dictionary.
"""
coors, conn, desc = create_linear_fe_mesh(nurbs, pars)
mat_id = nm.zeros(conn.shape[0], dtype=nm.int32)
mesh = Mesh.from_data('nurbs', coors, None, [conn], [mat_id], [desc])
out = {}
for key, variable in kwargs.iteritems():
if variable.ndim == 2:
nc = variable.shape[1]
field = variable.reshape(nurbs.weights.shape + (nc,))
else:
field = variable.reshape(nurbs.weights.shape)
nc = 1
vals = nurbs.evaluate(field, *pars)
out[key] = Struct(name='output_data', mode='vertex',
data=vals.reshape((-1, nc)))
return mesh, out
def save_basis(nurbs, pars):
"""
Save a NURBS object basis on a FE mesh corresponding to the given
parametrization in VTK files.
Parameters
----------
nurbs : igakit.nurbs.NURBS instance
The NURBS object.
pars : sequence of array, optional
The values of parameters in each parametric dimension.
"""
coors, conn, desc = create_linear_fe_mesh(nurbs, pars)
mat_id = nm.zeros(conn.shape[0], dtype=nm.int32)
mesh = Mesh.from_data('nurbs', coors, None, [conn], [mat_id], [desc])
n_dof = nurbs.weights.ravel().shape[0]
variable = nm.zeros(n_dof, dtype=nm.float64)
field = variable.reshape(nurbs.weights.shape)
for ic in xrange(n_dof):
variable[ic - 1] = 0.0
variable[ic] = 1.0
vals = nurbs.evaluate(field, *pars).reshape((-1))
out = {}
out['bf'] = Struct(name='output_data', mode='vertex',
data=vals[:, None])
mesh.write('iga_basis_%03d.vtk' % ic, io='auto', out=out)
| [
"sfepy.base.base.Struct",
"sfepy.discrete.fem.Mesh.from_data"
] | [((2365, 2404), 'numpy.zeros', 'nm.zeros', (['conn.shape[0]'], {'dtype': 'nm.int32'}), '(conn.shape[0], dtype=nm.int32)\n', (2373, 2404), True, 'import numpy as nm\n'), ((2416, 2478), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (['"""nurbs"""', 'coors', 'None', '[conn]', '[mat_id]', '[desc]'], {}), "('nurbs', coors, None, [conn], [mat_id], [desc])\n", (2430, 2478), False, 'from sfepy.discrete.fem import Mesh\n'), ((3366, 3405), 'numpy.zeros', 'nm.zeros', (['conn.shape[0]'], {'dtype': 'nm.int32'}), '(conn.shape[0], dtype=nm.int32)\n', (3374, 3405), True, 'import numpy as nm\n'), ((3417, 3479), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (['"""nurbs"""', 'coors', 'None', '[conn]', '[mat_id]', '[desc]'], {}), "('nurbs', coors, None, [conn], [mat_id], [desc])\n", (3431, 3479), False, 'from sfepy.discrete.fem import Mesh\n'), ((3539, 3572), 'numpy.zeros', 'nm.zeros', (['n_dof'], {'dtype': 'nm.float64'}), '(n_dof, dtype=nm.float64)\n', (3547, 3572), True, 'import numpy as nm\n'), ((3806, 3867), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""vertex"""', 'data': 'vals[:, None]'}), "(name='output_data', mode='vertex', data=vals[:, None])\n", (3812, 3867), False, 'from sfepy.base.base import Struct\n'), ((1044, 1081), 'numpy.linspace', 'nm.linspace', (['kv[0]', 'kv[-1]', 'shape[ii]'], {}), '(kv[0], kv[-1], shape[ii])\n', (1055, 1081), True, 'import numpy as nm\n')] |
#!/usr/bin/env python
# 12.01.2007, c
from __future__ import absolute_import
from argparse import ArgumentParser
import sfepy
from sfepy.base.base import output
from sfepy.base.conf import ProblemConf, get_standard_keywords
from sfepy.homogenization.band_gaps_app import AcousticBandGapsApp
from sfepy.base.plotutils import plt
helps = {
'debug':
'automatically start debugger when an exception is raised',
'filename' :
'basename of output file(s) [default: <basename of input file>]',
'detect_band_gaps' :
'detect frequency band gaps',
'analyze_dispersion' :
'analyze dispersion properties (low frequency domain)',
'plot' :
'plot frequency band gaps, assumes -b',
'phase_velocity' :
'compute phase velocity (frequency-independet mass only)'
}
def main():
parser = ArgumentParser()
parser.add_argument("--version", action="version",
version="%(prog)s " + sfepy.__version__)
parser.add_argument('--debug',
action='store_true', dest='debug',
default=False, help=helps['debug'])
parser.add_argument("-o", metavar='filename',
action="store", dest="output_filename_trunk",
default=None, help=helps['filename'])
parser.add_argument("-b", "--band-gaps",
action="store_true", dest="detect_band_gaps",
default=False, help=helps['detect_band_gaps'])
parser.add_argument("-d", "--dispersion",
action="store_true", dest="analyze_dispersion",
default=False, help=helps['analyze_dispersion'])
parser.add_argument("-p", "--plot",
action="store_true", dest="plot",
default=False, help=helps['plot'])
parser.add_argument("--phase-velocity",
action="store_true", dest="phase_velocity",
default=False, help=helps['phase_velocity'])
parser.add_argument("filename_in")
options = parser.parse_args()
if options.debug:
from sfepy.base.base import debug_on_error; debug_on_error()
if options.plot:
if plt is None:
output('matplotlib.pyplot cannot be imported, ignoring option -p!')
options.plot = False
elif options.analyze_dispersion == False:
options.detect_band_gaps = True
required, other = get_standard_keywords()
required.remove('equations')
if not options.analyze_dispersion:
required.remove('solver_[0-9]+|solvers')
if options.phase_velocity:
required = [ii for ii in required if 'ebc' not in ii]
conf = ProblemConf.from_file(options.filename_in, required, other)
app = AcousticBandGapsApp(conf, options, 'phonon:')
opts = conf.options
if hasattr(opts, 'parametric_hook'): # Parametric study.
parametric_hook = conf.get_function(opts.parametric_hook)
app.parametrize(parametric_hook)
app()
if __name__ == '__main__':
main()
| [
"sfepy.base.conf.get_standard_keywords",
"sfepy.homogenization.band_gaps_app.AcousticBandGapsApp",
"sfepy.base.base.output",
"sfepy.base.conf.ProblemConf.from_file",
"sfepy.base.base.debug_on_error"
] | [((820, 836), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (834, 836), False, 'from argparse import ArgumentParser\n'), ((2449, 2472), 'sfepy.base.conf.get_standard_keywords', 'get_standard_keywords', ([], {}), '()\n', (2470, 2472), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((2698, 2757), 'sfepy.base.conf.ProblemConf.from_file', 'ProblemConf.from_file', (['options.filename_in', 'required', 'other'], {}), '(options.filename_in, required, other)\n', (2719, 2757), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((2769, 2814), 'sfepy.homogenization.band_gaps_app.AcousticBandGapsApp', 'AcousticBandGapsApp', (['conf', 'options', '"""phonon:"""'], {}), "(conf, options, 'phonon:')\n", (2788, 2814), False, 'from sfepy.homogenization.band_gaps_app import AcousticBandGapsApp\n'), ((2156, 2172), 'sfepy.base.base.debug_on_error', 'debug_on_error', ([], {}), '()\n', (2170, 2172), False, 'from sfepy.base.base import debug_on_error\n'), ((2231, 2298), 'sfepy.base.base.output', 'output', (['"""matplotlib.pyplot cannot be imported, ignoring option -p!"""'], {}), "('matplotlib.pyplot cannot be imported, ignoring option -p!')\n", (2237, 2298), False, 'from sfepy.base.base import output\n')] |
"""
This module is not a test file. It contains classes grouping some common
functionality, that is used in several test files.
"""
from __future__ import absolute_import
from sfepy.base.base import IndexedStruct
from sfepy.base.testing import TestCommon
import os.path as op
class NLSStatus(IndexedStruct):
"""
Custom nonlinear solver status storing stopping condition of all
time steps.
"""
def __setitem__(self, key, val):
IndexedStruct.__setitem__(self, key, val)
if key == 'condition':
self.conditions.append(val)
class TestDummy(TestCommon):
"""Simulate test OK result for missing optional modules."""
@staticmethod
def from_conf(conf, options):
return TestDummy()
def test_dummy(self):
return True
class TestInput(TestCommon):
"""Test that an input file works. See test_input_*.py files."""
@staticmethod
def from_conf(conf, options, cls=None):
from sfepy.base.base import Struct
from sfepy.base.conf import ProblemConf, get_standard_keywords
from sfepy.applications import assign_standard_hooks
required, other = get_standard_keywords()
input_name = op.join(op.dirname(__file__), conf.input_name)
test_conf = ProblemConf.from_file(input_name, required, other)
if cls is None:
cls = TestInput
test = cls(test_conf=test_conf, conf=conf, options=options)
assign_standard_hooks(test, test_conf.options.get, test_conf)
name = test.get_output_name_trunk()
ext = test.get_output_name_ext()
test.solver_options = Struct(output_filename_trunk=name,
output_format=ext if ext != '' else "vtk",
save_ebc=False, save_ebc_nodes=False,
save_regions=False,
save_regions_as_groups=False,
save_field_meshes=False,
solve_not=False)
return test
def get_output_name_trunk(self):
return op.splitext(op.split(self.conf.output_name)[1])[0]
def get_output_name_ext(self):
return op.splitext(op.split(self.conf.output_name)[1])[1].replace(".", "")
def check_conditions(self, conditions):
ok = (conditions == 0).all()
if not ok:
self.report('nls stopping conditions:')
self.report(conditions)
return ok
def test_input(self):
import numpy as nm
from sfepy.applications import solve_pde
self.report('solving %s...' % self.conf.input_name)
status = IndexedStruct(nls_status=NLSStatus(conditions=[]))
solve_pde(self.test_conf,
self.solver_options,
status=status,
output_dir=self.options.out_dir,
step_hook=self.step_hook,
post_process_hook=self.post_process_hook,
post_process_hook_final=self.post_process_hook_final)
self.report('%s solved' % self.conf.input_name)
ok = self.check_conditions(nm.array(status.nls_status.conditions))
return ok
class TestInputEvolutionary(TestInput):
@staticmethod
def from_conf(conf, options, cls=None):
if cls is None:
cls = TestInputEvolutionary
return TestInput.from_conf(conf, options, cls=cls)
def get_output_name_trunk(self):
return self.conf.output_name_trunk
def get_output_name_ext(self):
return ""
class TestLCBC(TestCommon):
"""Test linear combination BC. See test_lcbc_*.py files."""
@staticmethod
def from_conf(conf, options):
return TestLCBC(conf=conf, options=options)
def test_linear_rigid_body_bc(self):
import scipy
if scipy.version.version == "0.6.0":
# This test uses a functionality implemented in scipy svn, which is
# missing in scipy 0.6.0
return True
from sfepy.base.base import Struct
from sfepy.applications import solve_pde
from sfepy.base.base import IndexedStruct
status = IndexedStruct()
problem, state = solve_pde(self.conf, status=status,
save_results=False)
ok = status.nls_status.condition == 0
self.report('converged: %s' % ok)
out = state.create_output_dict()
strain = problem.evaluate('ev_cauchy_strain.i.Y( u )', mode='el_avg')
out['strain'] = Struct(name='output_data',
mode='cell', data=strain, dofs=None)
name = op.join(self.options.out_dir,
op.split(self.conf.output_name)[1])
problem.domain.mesh.write(name, io='auto', out=out)
##
# Check if rigid body displacements are really rigid should go here.
return ok
| [
"sfepy.base.conf.get_standard_keywords",
"sfepy.applications.assign_standard_hooks",
"sfepy.base.base.IndexedStruct.__setitem__",
"sfepy.base.conf.ProblemConf.from_file",
"sfepy.base.base.Struct",
"sfepy.applications.solve_pde",
"sfepy.base.base.IndexedStruct"
] | [((455, 496), 'sfepy.base.base.IndexedStruct.__setitem__', 'IndexedStruct.__setitem__', (['self', 'key', 'val'], {}), '(self, key, val)\n', (480, 496), False, 'from sfepy.base.base import IndexedStruct\n'), ((1153, 1176), 'sfepy.base.conf.get_standard_keywords', 'get_standard_keywords', ([], {}), '()\n', (1174, 1176), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((1265, 1315), 'sfepy.base.conf.ProblemConf.from_file', 'ProblemConf.from_file', (['input_name', 'required', 'other'], {}), '(input_name, required, other)\n', (1286, 1315), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((1446, 1507), 'sfepy.applications.assign_standard_hooks', 'assign_standard_hooks', (['test', 'test_conf.options.get', 'test_conf'], {}), '(test, test_conf.options.get, test_conf)\n', (1467, 1507), False, 'from sfepy.applications import assign_standard_hooks\n'), ((1624, 1839), 'sfepy.base.base.Struct', 'Struct', ([], {'output_filename_trunk': 'name', 'output_format': "(ext if ext != '' else 'vtk')", 'save_ebc': '(False)', 'save_ebc_nodes': '(False)', 'save_regions': '(False)', 'save_regions_as_groups': '(False)', 'save_field_meshes': '(False)', 'solve_not': '(False)'}), "(output_filename_trunk=name, output_format=ext if ext != '' else\n 'vtk', save_ebc=False, save_ebc_nodes=False, save_regions=False,\n save_regions_as_groups=False, save_field_meshes=False, solve_not=False)\n", (1630, 1839), False, 'from sfepy.base.base import Struct\n'), ((2748, 2974), 'sfepy.applications.solve_pde', 'solve_pde', (['self.test_conf', 'self.solver_options'], {'status': 'status', 'output_dir': 'self.options.out_dir', 'step_hook': 'self.step_hook', 'post_process_hook': 'self.post_process_hook', 'post_process_hook_final': 'self.post_process_hook_final'}), '(self.test_conf, self.solver_options, status=status, output_dir=\n self.options.out_dir, step_hook=self.step_hook, post_process_hook=self.\n post_process_hook, post_process_hook_final=self.post_process_hook_final)\n', (2757, 2974), False, 'from sfepy.applications import solve_pde\n'), ((4194, 4209), 'sfepy.base.base.IndexedStruct', 'IndexedStruct', ([], {}), '()\n', (4207, 4209), False, 'from sfepy.base.base import IndexedStruct\n'), ((4235, 4290), 'sfepy.applications.solve_pde', 'solve_pde', (['self.conf'], {'status': 'status', 'save_results': '(False)'}), '(self.conf, status=status, save_results=False)\n', (4244, 4290), False, 'from sfepy.applications import solve_pde\n'), ((4558, 4621), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'strain', 'dofs': 'None'}), "(name='output_data', mode='cell', data=strain, dofs=None)\n", (4564, 4621), False, 'from sfepy.base.base import Struct\n'), ((1206, 1226), 'os.path.dirname', 'op.dirname', (['__file__'], {}), '(__file__)\n', (1216, 1226), True, 'import os.path as op\n'), ((3165, 3203), 'numpy.array', 'nm.array', (['status.nls_status.conditions'], {}), '(status.nls_status.conditions)\n', (3173, 3203), True, 'import numpy as nm\n'), ((4722, 4753), 'os.path.split', 'op.split', (['self.conf.output_name'], {}), '(self.conf.output_name)\n', (4730, 4753), True, 'import os.path as op\n'), ((2140, 2171), 'os.path.split', 'op.split', (['self.conf.output_name'], {}), '(self.conf.output_name)\n', (2148, 2171), True, 'import os.path as op\n'), ((2242, 2273), 'os.path.split', 'op.split', (['self.conf.output_name'], {}), '(self.conf.output_name)\n', (2250, 2273), True, 'import os.path as op\n')] |
"""
IGA domain generators.
"""
import numpy as nm
from sfepy.base.base import output, Struct
import sfepy.discrete.iga as iga
from sfepy.discrete.iga.domain import NurbsPatch
def gen_patch_block_domain(dims, shape, centre, degrees, continuity=None,
name='block', verbose=True):
"""
Generate a single IGA patch block in 2D or 3D of given degrees and
continuity using igakit.
Parameters
----------
dims : array of D floats
Dimensions of the block.
shape : array of D ints
Numbers of unique knot values along each axis.
centre : array of D floats
Centre of the block.
degrees : array of D floats
NURBS degrees along each axis.
continuity : array of D ints, optional
NURBS continuity along each axis. If None, `degrees-1` is used.
name : string
Domain name.
verbose : bool
If True, report progress of the domain generation.
Returns
-------
nurbs : NurbsPatch instance
The NURBS data. The igakit NURBS object is stored as `nurbs` attribute.
bmesh : Struct instance
The Bezier mesh data.
regions : dict
The patch surface regions.
"""
import igakit.cad as cad
dims = nm.asarray(dims, dtype=nm.float64)
shape = nm.asarray(shape, dtype=nm.int32)
centre = nm.asarray(centre, dtype=nm.float64)
degrees = nm.asarray(degrees, dtype=nm.int32)
if continuity is None:
continuity = degrees - 1
else:
continuity = nm.asarray(continuity, dtype=nm.int32)
dim = len(shape)
output('generating NURBS...', verbose=verbose)
dd = centre - 0.5 * dims
block = cad.grid(shape - 1, degree=degrees, continuity=continuity)
for ia in xrange(dim):
block.scale(dims[ia], ia)
for ia in xrange(dim):
block.translate(dd[ia], ia)
# Force uniform control points. This prevents coarser resolution inside the
# block.
shape = nm.asarray(block.points.shape[:-1])
n_nod = nm.prod(shape)
x0 = centre - 0.5 * dims
dd = dims / (shape - 1)
ngrid = nm.mgrid[[slice(ii) for ii in shape]]
ngrid.shape = (dim, n_nod)
coors = x0 + ngrid.T * dd
coors.shape = shape.tolist() + [dim]
block.array[..., :dim] = coors
output('...done', verbose=verbose)
# Compute Bezier extraction data.
output('computing Bezier mesh...', verbose=verbose)
cs = iga.compute_bezier_extraction(block.knots, block.degree)
n_els = [len(ii) for ii in cs]
conn, bconn = iga.create_connectivity(n_els, block.knots, block.degree)
ccs = iga.combine_bezier_extraction(cs)
cps = block.points[..., :dim].copy()
cps = cps.reshape((-1, dim))
bcps, bweights = iga.compute_bezier_control(cps, block.weights.ravel(), ccs,
conn, bconn)
nurbs = NurbsPatch(block.knots, degrees, cps, block.weights.ravel(), cs,
conn)
nurbs.nurbs = block
bmesh = Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn)
output('...done', verbose=verbose)
output('defining regions...', verbose=verbose)
regions = iga.get_patch_box_regions(n_els, block.degree)
output('...done', verbose=verbose)
return nurbs, bmesh, regions
| [
"sfepy.discrete.iga.get_patch_box_regions",
"sfepy.base.base.output",
"sfepy.discrete.iga.combine_bezier_extraction",
"sfepy.base.base.Struct",
"sfepy.discrete.iga.compute_bezier_extraction",
"sfepy.discrete.iga.create_connectivity"
] | [((1252, 1286), 'numpy.asarray', 'nm.asarray', (['dims'], {'dtype': 'nm.float64'}), '(dims, dtype=nm.float64)\n', (1262, 1286), True, 'import numpy as nm\n'), ((1299, 1332), 'numpy.asarray', 'nm.asarray', (['shape'], {'dtype': 'nm.int32'}), '(shape, dtype=nm.int32)\n', (1309, 1332), True, 'import numpy as nm\n'), ((1346, 1382), 'numpy.asarray', 'nm.asarray', (['centre'], {'dtype': 'nm.float64'}), '(centre, dtype=nm.float64)\n', (1356, 1382), True, 'import numpy as nm\n'), ((1397, 1432), 'numpy.asarray', 'nm.asarray', (['degrees'], {'dtype': 'nm.int32'}), '(degrees, dtype=nm.int32)\n', (1407, 1432), True, 'import numpy as nm\n'), ((1592, 1638), 'sfepy.base.base.output', 'output', (['"""generating NURBS..."""'], {'verbose': 'verbose'}), "('generating NURBS...', verbose=verbose)\n", (1598, 1638), False, 'from sfepy.base.base import output, Struct\n'), ((1681, 1739), 'igakit.cad.grid', 'cad.grid', (['(shape - 1)'], {'degree': 'degrees', 'continuity': 'continuity'}), '(shape - 1, degree=degrees, continuity=continuity)\n', (1689, 1739), True, 'import igakit.cad as cad\n'), ((1972, 2007), 'numpy.asarray', 'nm.asarray', (['block.points.shape[:-1]'], {}), '(block.points.shape[:-1])\n', (1982, 2007), True, 'import numpy as nm\n'), ((2020, 2034), 'numpy.prod', 'nm.prod', (['shape'], {}), '(shape)\n', (2027, 2034), True, 'import numpy as nm\n'), ((2287, 2321), 'sfepy.base.base.output', 'output', (['"""...done"""'], {'verbose': 'verbose'}), "('...done', verbose=verbose)\n", (2293, 2321), False, 'from sfepy.base.base import output, Struct\n'), ((2365, 2416), 'sfepy.base.base.output', 'output', (['"""computing Bezier mesh..."""'], {'verbose': 'verbose'}), "('computing Bezier mesh...', verbose=verbose)\n", (2371, 2416), False, 'from sfepy.base.base import output, Struct\n'), ((2426, 2482), 'sfepy.discrete.iga.compute_bezier_extraction', 'iga.compute_bezier_extraction', (['block.knots', 'block.degree'], {}), '(block.knots, block.degree)\n', (2455, 2482), True, 'import sfepy.discrete.iga as iga\n'), ((2536, 2593), 'sfepy.discrete.iga.create_connectivity', 'iga.create_connectivity', (['n_els', 'block.knots', 'block.degree'], {}), '(n_els, block.knots, block.degree)\n', (2559, 2593), True, 'import sfepy.discrete.iga as iga\n'), ((2605, 2638), 'sfepy.discrete.iga.combine_bezier_extraction', 'iga.combine_bezier_extraction', (['cs'], {}), '(cs)\n', (2634, 2638), True, 'import sfepy.discrete.iga as iga\n'), ((2999, 3059), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""bmesh"""', 'cps': 'bcps', 'weights': 'bweights', 'conn': 'bconn'}), "(name='bmesh', cps=bcps, weights=bweights, conn=bconn)\n", (3005, 3059), False, 'from sfepy.base.base import output, Struct\n'), ((3064, 3098), 'sfepy.base.base.output', 'output', (['"""...done"""'], {'verbose': 'verbose'}), "('...done', verbose=verbose)\n", (3070, 3098), False, 'from sfepy.base.base import output, Struct\n'), ((3104, 3150), 'sfepy.base.base.output', 'output', (['"""defining regions..."""'], {'verbose': 'verbose'}), "('defining regions...', verbose=verbose)\n", (3110, 3150), False, 'from sfepy.base.base import output, Struct\n'), ((3165, 3211), 'sfepy.discrete.iga.get_patch_box_regions', 'iga.get_patch_box_regions', (['n_els', 'block.degree'], {}), '(n_els, block.degree)\n', (3190, 3211), True, 'import sfepy.discrete.iga as iga\n'), ((3216, 3250), 'sfepy.base.base.output', 'output', (['"""...done"""'], {'verbose': 'verbose'}), "('...done', verbose=verbose)\n", (3222, 3250), False, 'from sfepy.base.base import output, Struct\n'), ((1526, 1564), 'numpy.asarray', 'nm.asarray', (['continuity'], {'dtype': 'nm.int32'}), '(continuity, dtype=nm.int32)\n', (1536, 1564), True, 'import numpy as nm\n')] |
"""
Notes
-----
Important attributes of continuous (order > 0) :class:`Field` and
:class:`SurfaceField` instances:
- `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]`
- `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]`
where `conn` is the mesh vertex connectivity, `econn` is the
region-local field connectivity.
"""
from __future__ import absolute_import
import numpy as nm
from sfepy.base.base import output, get_default, assert_
from sfepy.base.base import Struct
from sfepy.discrete.common.fields import parse_shape, Field
from sfepy.discrete.fem.mesh import Mesh
from sfepy.discrete.fem.meshio import convert_complex_output
from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap,
invert_remap, get_min_value)
from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping
from sfepy.discrete.fem.poly_spaces import PolySpace
from sfepy.discrete.fem.fe_surface import FESurface
from sfepy.discrete.integrals import Integral
from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors,
create_output)
import six
def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False,
clear_all=True, extra_dofs=False):
if actual:
if not hasattr(domain.mesh, 'coors_act'):
domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors)
domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod]
else:
domain.cmesh.coors[:] = coors[:domain.mesh.n_nod]
if update_fields:
for field in six.itervalues(fields):
field.set_coors(coors, extra_dofs=extra_dofs)
field.clear_mappings(clear_all=clear_all)
def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space,
econn, only_extra=True):
"""
Compute coordinates of nodes corresponding to `poly_space`, given
mesh coordinates and `geom_poly_space`.
"""
if only_extra:
iex = (poly_space.nts[:,0] > 0).nonzero()[0]
if iex.shape[0] == 0: return
qp_coors = poly_space.node_coors[iex, :]
econn = econn[:, iex].copy()
else:
qp_coors = poly_space.node_coors
##
# Evaluate geometry interpolation base functions in (extra) nodes.
bf = geom_poly_space.eval_base(qp_coors)
bf = bf[:,0,:].copy()
##
# Evaluate extra coordinates with 'bf'.
cmesh = region.domain.cmesh
conn = cmesh.get_incident(0, region.cells, region.tdim)
conn.shape = (econn.shape[0], -1)
ecoors = nm.dot(bf, mesh_coors[conn])
coors[econn] = nm.swapaxes(ecoors, 0, 1)
def _interp_to_faces(vertex_vals, bfs, faces):
dim = vertex_vals.shape[1]
n_face = faces.shape[0]
n_qp = bfs.shape[0]
faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64)
for ii, face in enumerate(faces):
vals = vertex_vals[face,:dim]
faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals)
return(faces_vals)
def get_eval_expression(expression,
fields, materials, variables,
functions=None, mode='eval', term_mode=None,
extra_args=None, verbose=True, kwargs=None):
"""
Get the function for evaluating an expression given a list of elements,
and reference element coordinates.
"""
from sfepy.discrete.evaluate import eval_in_els_and_qp
def _eval(iels, coors):
val = eval_in_els_and_qp(expression, iels, coors,
fields, materials, variables,
functions=functions, mode=mode,
term_mode=term_mode,
extra_args=extra_args, verbose=verbose,
kwargs=kwargs)
return val[..., 0]
return _eval
def create_expression_output(expression, name, primary_field_name,
fields, materials, variables,
functions=None, mode='eval', term_mode=None,
extra_args=None, verbose=True, kwargs=None,
min_level=0, max_level=1, eps=1e-4):
"""
Create output mesh and data for the expression using the adaptive
linearizer.
Parameters
----------
expression : str
The expression to evaluate.
name : str
The name of the data.
primary_field_name : str
The name of field that defines the element groups and polynomial
spaces.
fields : dict
The dictionary of fields used in `variables`.
materials : Materials instance
The materials used in the expression.
variables : Variables instance
The variables used in the expression.
functions : Functions instance, optional
The user functions for materials etc.
mode : one of 'eval', 'el_avg', 'qp'
The evaluation mode - 'qp' requests the values in quadrature points,
'el_avg' element averages and 'eval' means integration over
each term region.
term_mode : str
The term call mode - some terms support different call modes
and depending on the call mode different values are
returned.
extra_args : dict, optional
Extra arguments to be passed to terms in the expression.
verbose : bool
If False, reduce verbosity.
kwargs : dict, optional
The variables (dictionary of (variable name) : (Variable
instance)) to be used in the expression.
min_level : int
The minimum required level of mesh refinement.
max_level : int
The maximum level of mesh refinement.
eps : float
The relative tolerance parameter of mesh adaptivity.
Returns
-------
out : dict
The output dictionary.
"""
field = fields[primary_field_name]
vertex_coors = field.coors[:field.n_vertex_dof, :]
ps = field.poly_space
gps = field.gel.poly_space
vertex_conn = field.econn[:, :field.gel.n_vertex]
eval_dofs = get_eval_expression(expression,
fields, materials, variables,
functions=functions,
mode=mode, extra_args=extra_args,
verbose=verbose, kwargs=kwargs)
eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps)
(level, coors, conn,
vdofs, mat_ids) = create_output(eval_dofs, eval_coors,
vertex_conn.shape[0], ps,
min_level=min_level,
max_level=max_level, eps=eps)
mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids],
field.domain.mesh.descs)
out = {}
out[name] = Struct(name='output_data', mode='vertex',
data=vdofs, var_name=name, dofs=None,
mesh=mesh, level=level)
out = convert_complex_output(out)
return out
class FEField(Field):
"""
Base class for finite element fields.
Notes
-----
- interps and hence node_descs are per region (must have single
geometry!)
Field shape information:
- ``shape`` - the shape of the base functions in a point
- ``n_components`` - the number of DOFs per FE node
- ``val_shape`` - the shape of field value (the product of DOFs and
base functions) in a point
"""
def __init__(self, name, dtype, shape, region, approx_order=1):
"""
Create a finite element field.
Parameters
----------
name : str
The field name.
dtype : numpy.dtype
The field data type: float64 or complex128.
shape : int/tuple/str
The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,)
or 3 or (3,)) or 'vector', or a tuple. The field shape determines
the shape of the FE base functions and is related to the number of
components of variables and to the DOF per node count, depending
on the field kind.
region : Region
The region where the field is defined.
approx_order : int or tuple
The FE approximation order. The tuple form is (order, has_bubble),
e.g. (1, True) means order 1 with a bubble function.
Notes
-----
Assumes one cell type for the whole region!
"""
shape = parse_shape(shape, region.domain.shape.dim)
if not self._check_region(region):
raise ValueError('unsuitable region for field %s! (%s)' %
(name, region.name))
Struct.__init__(self, name=name, dtype=dtype, shape=shape,
region=region)
self.domain = self.region.domain
self._set_approx_order(approx_order)
self._setup_geometry()
self._setup_kind()
self._setup_shape()
self.surface_data = {}
self.point_data = {}
self.ori = None
self._create_interpolant()
self._setup_global_base()
self.setup_coors()
self.clear_mappings(clear_all=True)
self.clear_qp_base()
self.basis_transform = None
self.econn0 = None
self.unused_dofs = None
self.stored_subs = None
def _set_approx_order(self, approx_order):
"""
Set a uniform approximation order.
"""
if isinstance(approx_order, tuple):
self.approx_order = approx_order[0]
self.force_bubble = approx_order[1]
else:
self.approx_order = approx_order
self.force_bubble = False
def get_true_order(self):
"""
Get the true approximation order depending on the reference
element geometry.
For example, for P1 (linear) approximation the true order is 1,
while for Q1 (bilinear) approximation in 2D the true order is 2.
"""
gel = self.gel
if (gel.dim + 1) == gel.n_vertex:
order = self.approx_order
else:
order = gel.dim * self.approx_order
if self.force_bubble:
bubble_order = gel.dim + 1
order = max(order, bubble_order)
return order
def is_higher_order(self):
"""
Return True, if the field's approximation order is greater than one.
"""
return self.force_bubble or (self.approx_order > 1)
def _setup_global_base(self):
"""
Setup global DOF/base functions, their indices and connectivity of the
field. Called methods implemented in subclasses.
"""
self._setup_facet_orientations()
self._init_econn()
self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs()
self.vertex_remap_i = invert_remap(self.vertex_remap)
aux = self._setup_edge_dofs()
self.n_edge_dof, self.edge_dofs, self.edge_remap = aux
aux = self._setup_face_dofs()
self.n_face_dof, self.face_dofs, self.face_remap = aux
aux = self._setup_bubble_dofs()
self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux
self.n_nod = self.n_vertex_dof + self.n_edge_dof \
+ self.n_face_dof + self.n_bubble_dof
self._setup_esurface()
def _setup_esurface(self):
"""
Setup extended surface entities (edges in 2D, faces in 3D),
i.e. indices of surface entities into the extended connectivity.
"""
node_desc = self.node_desc
gel = self.gel
self.efaces = gel.get_surface_entities().copy()
nd = node_desc.edge
if nd is not None:
efs = []
for eof in gel.get_edges_per_face():
efs.append(nm.concatenate([nd[ie] for ie in eof]))
efs = nm.array(efs).squeeze()
if efs.ndim < 2:
efs = efs[:,nm.newaxis]
self.efaces = nm.hstack((self.efaces, efs))
efs = node_desc.face
if efs is not None:
efs = nm.array(efs).squeeze()
if efs.ndim < 2:
efs = efs[:,nm.newaxis]
self.efaces = nm.hstack((self.efaces, efs))
if gel.dim == 3:
self.eedges = gel.edges.copy()
efs = node_desc.edge
if efs is not None:
efs = nm.array(efs).squeeze()
if efs.ndim < 2:
efs = efs[:,nm.newaxis]
self.eedges = nm.hstack((self.eedges, efs))
def set_coors(self, coors, extra_dofs=False):
"""
Set coordinates of field nodes.
"""
# Mesh vertex nodes.
if self.n_vertex_dof:
indx = self.vertex_remap_i
self.coors[:self.n_vertex_dof] = nm.take(coors,
indx.astype(nm.int32),
axis=0)
n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof
# extra nodes
if n_ex_dof:
if extra_dofs:
if self.n_nod != coors.shape[0]:
raise NotImplementedError
self.coors[:] = coors
else:
gps = self.gel.poly_space
ps = self.poly_space
eval_nodal_coors(self.coors, coors, self.region,
ps, gps, self.econn)
def setup_coors(self):
"""
Setup coordinates of field nodes.
"""
mesh = self.domain.mesh
self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64)
self.set_coors(mesh.coors)
def get_vertices(self):
"""
Return indices of vertices belonging to the field region.
"""
return self.vertex_remap_i
def _get_facet_dofs(self, rfacets, remap, dofs):
facets = remap[rfacets]
return dofs[facets[facets >= 0]].ravel()
def get_data_shape(self, integral, integration='volume', region_name=None):
"""
Get element data dimensions.
Parameters
----------
integral : Integral instance
The integral describing used numerical quadrature.
integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom'
The term integration type.
region_name : str
The name of the region of the integral.
Returns
-------
data_shape : 4 ints
The `(n_el, n_qp, dim, n_en)` for volume shape kind,
`(n_fa, n_qp, dim, n_fn)` for surface shape kind and
`(n_nod, 0, 0, 1)` for point shape kind.
Notes
-----
- `n_el`, `n_fa` = number of elements/facets
- `n_qp` = number of quadrature points per element/facet
- `dim` = spatial dimension
- `n_en`, `n_fn` = number of element/facet nodes
- `n_nod` = number of element nodes
"""
region = self.domain.regions[region_name]
shape = region.shape
dim = region.dim
if integration in ('surface', 'surface_extra'):
sd = self.surface_data[region_name]
# This works also for surface fields.
key = sd.face_type
weights = self.get_qp(key, integral).weights
n_qp = weights.shape[0]
if integration == 'surface':
data_shape = (sd.n_fa, n_qp, dim, sd.n_fp)
else:
data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1])
elif integration in ('volume', 'custom'):
_, weights = integral.get_qp(self.gel.name)
n_qp = weights.shape[0]
data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1])
elif integration == 'point':
dofs = self.get_dofs_in_region(region, merge=True)
data_shape = (dofs.shape[0], 0, 0, 1)
else:
raise NotImplementedError('unsupported integration! (%s)'
% integration)
return data_shape
def get_dofs_in_region(self, region, merge=True):
"""
Return indices of DOFs that belong to the given region and group.
"""
node_desc = self.node_desc
dofs = []
vdofs = nm.empty((0,), dtype=nm.int32)
if node_desc.vertex is not None:
vdofs = self.vertex_remap[region.vertices]
vdofs = vdofs[vdofs >= 0]
dofs.append(vdofs)
edofs = nm.empty((0,), dtype=nm.int32)
if node_desc.edge is not None:
edofs = self._get_facet_dofs(region.edges,
self.edge_remap,
self.edge_dofs)
dofs.append(edofs)
fdofs = nm.empty((0,), dtype=nm.int32)
if node_desc.face is not None:
fdofs = self._get_facet_dofs(region.faces,
self.face_remap,
self.face_dofs)
dofs.append(fdofs)
bdofs = nm.empty((0,), dtype=nm.int32)
if (node_desc.bubble is not None) and region.has_cells():
els = self.bubble_remap[region.cells]
bdofs = self.bubble_dofs[els[els >= 0]].ravel()
dofs.append(bdofs)
if merge:
dofs = nm.concatenate(dofs)
return dofs
def clear_qp_base(self):
"""
Remove cached quadrature points and base functions.
"""
self.qp_coors = {}
self.bf = {}
def get_qp(self, key, integral):
"""
Get quadrature points and weights corresponding to the given key
and integral. The key is 'v' or 's#', where # is the number of
face vertices.
"""
qpkey = (integral.order, key)
if qpkey not in self.qp_coors:
if (key[0] == 's') and not self.is_surface:
dim = self.gel.dim - 1
n_fp = self.gel.surface_facet.n_vertex
geometry = '%d_%d' % (dim, n_fp)
else:
geometry = self.gel.name
vals, weights = integral.get_qp(geometry)
self.qp_coors[qpkey] = Struct(vals=vals, weights=weights)
return self.qp_coors[qpkey]
def substitute_dofs(self, subs, restore=False):
"""
Perform facet DOF substitutions according to `subs`.
Modifies `self.econn` in-place and sets `self.econn0`,
`self.unused_dofs` and `self.basis_transform`.
"""
if restore and (self.stored_subs is not None):
self.econn0 = self.econn
self.econn, self.unused_dofs, basis_transform = self.stored_subs
else:
if subs is None:
self.econn0 = self.econn
return
else:
self.econn0 = self.econn.copy()
self._substitute_dofs(subs)
self.unused_dofs = nm.setdiff1d(self.econn0, self.econn)
basis_transform = self._eval_basis_transform(subs)
self.set_basis_transform(basis_transform)
def restore_dofs(self, store=False):
"""
Undoes the effect of :func:`FEField.substitute_dofs()`.
"""
if self.econn0 is None:
raise ValueError('no original DOFs to restore!')
if store:
self.stored_subs = (self.econn,
self.unused_dofs,
self.basis_transform)
else:
self.stored_subs = None
self.econn = self.econn0
self.econn0 = None
self.unused_dofs = None
self.basis_transform = None
def set_basis_transform(self, transform):
"""
Set local element basis transformation.
The basis transformation is applied in :func:`FEField.get_base()` and
:func:`FEField.create_mapping()`.
Parameters
----------
transform : array, shape `(n_cell, n_ep, n_ep)`
The array with `(n_ep, n_ep)` transformation matrices for each cell
in the field's region, where `n_ep` is the number of element DOFs.
"""
self.basis_transform = transform
def restore_substituted(self, vec):
"""
Restore values of the unused DOFs using the transpose of the applied
basis transformation.
"""
if (self.econn0 is None) or (self.basis_transform is None):
raise ValueError('no original DOF values to restore!!')
vec = vec.reshape((self.n_nod, self.n_components)).copy()
evec = vec[self.econn]
vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec)
return vec.ravel()
def get_base(self, key, derivative, integral, iels=None,
from_geometry=False, base_only=True):
qp = self.get_qp(key, integral)
if from_geometry:
ps = self.gel.poly_space
else:
ps = self.poly_space
_key = key if not from_geometry else 'g' + key
bf_key = (integral.order, _key, derivative)
if bf_key not in self.bf:
if (iels is not None) and (self.ori is not None):
ori = self.ori[iels]
else:
ori = self.ori
self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori,
transform=self.basis_transform)
if base_only:
return self.bf[bf_key]
else:
return self.bf[bf_key], qp.weights
def create_bqp(self, region_name, integral):
gel = self.gel
sd = self.surface_data[region_name]
bqpkey = (integral.order, sd.bkey)
if not bqpkey in self.qp_coors:
qp = self.get_qp(sd.face_type, integral)
ps_s = self.gel.surface_facet.poly_space
bf_s = ps_s.eval_base(qp.vals)
coors, faces = gel.coors, gel.get_surface_entities()
vals = _interp_to_faces(coors, bf_s, faces)
self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey,
vals=vals, weights=qp.weights)
def extend_dofs(self, dofs, fill_value=None):
"""
Extend DOFs to the whole domain using the `fill_value`, or the
smallest value in `dofs` if `fill_value` is None.
"""
if fill_value is None:
if nm.isrealobj(dofs):
fill_value = get_min_value(dofs)
else:
# Complex values - treat real and imaginary parts separately.
fill_value = get_min_value(dofs.real)
fill_value += 1j * get_min_value(dofs.imag)
if self.approx_order != 0:
indx = self.get_vertices()
n_nod = self.domain.shape.n_nod
new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype)
new_dofs.fill(fill_value)
new_dofs[indx] = dofs[:indx.size]
else:
new_dofs = extend_cell_data(dofs, self.domain, self.region,
val=fill_value)
return new_dofs
def remove_extra_dofs(self, dofs):
"""
Remove DOFs defined in higher order nodes (order > 1).
"""
if self.approx_order != 0:
new_dofs = dofs[:self.n_vertex_dof]
else:
new_dofs = dofs
return new_dofs
def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4):
"""
Linearize the solution for post-processing.
Parameters
----------
dofs : array, shape (n_nod, n_component)
The array of DOFs reshaped so that each column corresponds
to one component.
min_level : int
The minimum required level of mesh refinement.
max_level : int
The maximum level of mesh refinement.
eps : float
The relative tolerance parameter of mesh adaptivity.
Returns
-------
mesh : Mesh instance
The adapted, nonconforming, mesh.
vdofs : array
The DOFs defined in vertices of `mesh`.
levels : array of ints
The refinement level used for each element group.
"""
assert_(dofs.ndim == 2)
n_nod, dpn = dofs.shape
assert_(n_nod == self.n_nod)
assert_(dpn == self.shape[0])
vertex_coors = self.coors[:self.n_vertex_dof, :]
ps = self.poly_space
gps = self.gel.poly_space
vertex_conn = self.econn[:, :self.gel.n_vertex]
eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori)
eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps)
(level, coors, conn,
vdofs, mat_ids) = create_output(eval_dofs, eval_coors,
vertex_conn.shape[0], ps,
min_level=min_level,
max_level=max_level, eps=eps)
mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids],
self.domain.mesh.descs)
return mesh, vdofs, level
def get_output_approx_order(self):
"""
Get the approximation order used in the output file.
"""
return min(self.approx_order, 1)
def create_output(self, dofs, var_name, dof_names=None,
key=None, extend=True, fill_value=None,
linearization=None):
"""
Convert the DOFs corresponding to the field to a dictionary of
output data usable by Mesh.write().
Parameters
----------
dofs : array, shape (n_nod, n_component)
The array of DOFs reshaped so that each column corresponds
to one component.
var_name : str
The variable name corresponding to `dofs`.
dof_names : tuple of str
The names of DOF components.
key : str, optional
The key to be used in the output dictionary instead of the
variable name.
extend : bool
Extend the DOF values to cover the whole domain.
fill_value : float or complex
The value used to fill the missing DOF values if `extend` is True.
linearization : Struct or None
The linearization configuration for higher order approximations.
Returns
-------
out : dict
The output dictionary.
"""
linearization = get_default(linearization, Struct(kind='strip'))
out = {}
if linearization.kind is None:
out[key] = Struct(name='output_data', mode='full',
data=dofs, var_name=var_name,
dofs=dof_names, field_name=self.name)
elif linearization.kind == 'strip':
if extend:
ext = self.extend_dofs(dofs, fill_value)
else:
ext = self.remove_extra_dofs(dofs)
if ext is not None:
approx_order = self.get_output_approx_order()
if approx_order != 0:
# Has vertex data.
out[key] = Struct(name='output_data', mode='vertex',
data=ext, var_name=var_name,
dofs=dof_names)
else:
ext.shape = (ext.shape[0], 1, ext.shape[1], 1)
out[key] = Struct(name='output_data', mode='cell',
data=ext, var_name=var_name,
dofs=dof_names)
else:
mesh, vdofs, levels = self.linearize(dofs,
linearization.min_level,
linearization.max_level,
linearization.eps)
out[key] = Struct(name='output_data', mode='vertex',
data=vdofs, var_name=var_name, dofs=dof_names,
mesh=mesh, levels=levels)
out = convert_complex_output(out)
return out
def create_mesh(self, extra_nodes=True):
"""
Create a mesh from the field region, optionally including the field
extra nodes.
"""
mesh = self.domain.mesh
if self.approx_order != 0:
if extra_nodes:
conn = self.econn
else:
conn = self.econn[:, :self.gel.n_vertex]
conns = [conn]
mat_ids = [mesh.cmesh.cell_groups]
descs = mesh.descs[:1]
if extra_nodes:
coors = self.coors
else:
coors = self.coors[:self.n_vertex_dof]
mesh = Mesh.from_data(self.name, coors, None, conns,
mat_ids, descs)
return mesh
def get_evaluate_cache(self, cache=None, share_geometry=False,
verbose=False):
"""
Get the evaluate cache for :func:`Variable.evaluate_at()
<sfepy.discrete.variables.Variable.evaluate_at()>`.
Parameters
----------
cache : Struct instance, optional
Optionally, use the provided instance to store the cache data.
share_geometry : bool
Set to True to indicate that all the evaluations will work on the
same region. Certain data are then computed only for the first
probe and cached.
verbose : bool
If False, reduce verbosity.
Returns
-------
cache : Struct instance
The evaluate cache.
"""
import time
try:
from scipy.spatial import cKDTree as KDTree
except ImportError:
from scipy.spatial import KDTree
from sfepy.discrete.fem.geometry_element import create_geometry_elements
if cache is None:
cache = Struct(name='evaluate_cache')
tt = time.clock()
if (cache.get('cmesh', None) is None) or not share_geometry:
mesh = self.create_mesh(extra_nodes=False)
cache.cmesh = cmesh = mesh.cmesh
gels = create_geometry_elements()
cmesh.set_local_entities(gels)
cmesh.setup_entities()
cache.centroids = cmesh.get_centroids(cmesh.tdim)
if self.gel.name != '3_8':
cache.normals0 = cmesh.get_facet_normals()
cache.normals1 = None
else:
cache.normals0 = cmesh.get_facet_normals(0)
cache.normals1 = cmesh.get_facet_normals(1)
output('cmesh setup: %f s' % (time.clock()-tt), verbose=verbose)
tt = time.clock()
if (cache.get('kdtree', None) is None) or not share_geometry:
cache.kdtree = KDTree(cmesh.coors)
output('kdtree: %f s' % (time.clock()-tt), verbose=verbose)
return cache
def interp_to_qp(self, dofs):
"""
Interpolate DOFs into quadrature points.
The quadrature order is given by the field approximation order.
Parameters
----------
dofs : array
The array of DOF values of shape `(n_nod, n_component)`.
Returns
-------
data_qp : array
The values interpolated into the quadrature points.
integral : Integral
The corresponding integral defining the quadrature points.
"""
integral = Integral('i', order=self.approx_order)
bf = self.get_base('v', False, integral)
bf = bf[:,0,:].copy()
data_qp = nm.dot(bf, dofs[self.econn])
data_qp = nm.swapaxes(data_qp, 0, 1)
data_qp.shape = data_qp.shape + (1,)
return data_qp, integral
def get_coor(self, nods=None):
"""
Get coordinates of the field nodes.
Parameters
----------
nods : array, optional
The indices of the required nodes. If not given, the
coordinates of all the nodes are returned.
"""
if nods is None:
return self.coors
else:
return self.coors[nods]
def get_connectivity(self, region, integration, is_trace=False):
"""
Convenience alias to `Field.get_econn()`, that is used in some terms.
"""
return self.get_econn(integration, region, is_trace=is_trace)
def create_mapping(self, region, integral, integration,
return_mapping=True):
"""
Create a new reference mapping.
Compute jacobians, element volumes and base function derivatives
for Volume-type geometries (volume mappings), and jacobians,
normals and base function derivatives for Surface-type
geometries (surface mappings).
Notes
-----
- surface mappings are defined on the surface region
- surface mappings require field order to be > 0
"""
domain = self.domain
coors = domain.get_mesh_coors(actual=True)
dconn = domain.get_conn()
if integration == 'volume':
qp = self.get_qp('v', integral)
iels = region.get_cells()
geo_ps = self.gel.poly_space
ps = self.poly_space
bf = self.get_base('v', 0, integral, iels=iels)
conn = nm.take(dconn, iels.astype(nm.int32), axis=0)
mapping = VolumeMapping(coors, conn, poly_space=geo_ps)
vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps,
ori=self.ori,
transform=self.basis_transform)
out = vg
elif (integration == 'surface') or (integration == 'surface_extra'):
assert_(self.approx_order > 0)
if self.ori is not None:
msg = 'surface integrals do not work yet with the' \
' hierarchical basis!'
raise ValueError(msg)
sd = domain.surface_groups[region.name]
esd = self.surface_data[region.name]
geo_ps = self.gel.poly_space
ps = self.poly_space
conn = sd.get_connectivity()
mapping = SurfaceMapping(coors, conn, poly_space=geo_ps)
if not self.is_surface:
self.create_bqp(region.name, integral)
qp = self.qp_coors[(integral.order, esd.bkey)]
abf = ps.eval_base(qp.vals[0], transform=self.basis_transform)
bf = abf[..., self.efaces[0]]
indx = self.gel.get_surface_entities()[0]
# Fix geometry element's 1st facet orientation for gradients.
indx = nm.roll(indx, -1)[::-1]
mapping.set_basis_indices(indx)
sg = mapping.get_mapping(qp.vals[0], qp.weights,
poly_space=Struct(n_nod=bf.shape[-1]),
mode=integration)
if integration == 'surface_extra':
sg.alloc_extra_data(self.econn.shape[1])
bf_bg = geo_ps.eval_base(qp.vals, diff=True)
ebf_bg = self.get_base(esd.bkey, 1, integral)
sg.evaluate_bfbgm(bf_bg, ebf_bg, coors, sd.fis, dconn)
else:
# Do not use BQP for surface fields.
qp = self.get_qp(sd.face_type, integral)
bf = ps.eval_base(qp.vals, transform=self.basis_transform)
sg = mapping.get_mapping(qp.vals, qp.weights,
poly_space=Struct(n_nod=bf.shape[-1]),
mode=integration)
out = sg
elif integration == 'point':
out = mapping = None
elif integration == 'custom':
raise ValueError('cannot create custom mapping!')
else:
raise ValueError('unknown integration geometry type: %s'
% integration)
if out is not None:
# Store the integral used.
out.integral = integral
out.qp = qp
out.ps = ps
# Update base.
out.bf[:] = bf
if return_mapping:
out = (out, mapping)
return out
class VolumeField(FEField):
"""
Finite element field base class over volume elements (element dimension
equals space dimension).
"""
def _check_region(self, region):
"""
Check whether the `region` can be used for the
field.
Returns
-------
ok : bool
True if the region is usable for the field.
"""
ok = True
domain = region.domain
if region.kind != 'cell':
output("bad region kind! (is: %r, should be: 'cell')"
% region.kind)
ok = False
elif (region.kind_tdim != domain.shape.tdim):
output('cells with a bad topological dimension! (%d == %d)'
% (region.kind_tdim, domain.shape.tdim))
ok = False
return ok
def _setup_geometry(self):
"""
Setup the field region geometry.
"""
cmesh = self.domain.cmesh
for key, gel in six.iteritems(self.domain.geom_els):
ct = cmesh.cell_types
if (ct[self.region.cells] == cmesh.key_to_index[gel.name]).all():
self.gel = gel
break
else:
raise ValueError('region %s of field %s contains multiple'
' reference geometries!'
% (self.region.name, self.name))
self.is_surface = False
def _create_interpolant(self):
name = '%s_%s_%s_%d%s' % (self.gel.name, self.space,
self.poly_space_base, self.approx_order,
'B' * self.force_bubble)
ps = PolySpace.any_from_args(name, self.gel, self.approx_order,
base=self.poly_space_base,
force_bubble=self.force_bubble)
self.poly_space = ps
def _init_econn(self):
"""
Initialize the extended DOF connectivity.
"""
n_ep = self.poly_space.n_nod
n_cell = self.region.get_n_cells()
self.econn = nm.zeros((n_cell, n_ep), nm.int32)
def _setup_vertex_dofs(self):
"""
Setup vertex DOF connectivity.
"""
if self.node_desc.vertex is None:
return 0, None
region = self.region
cmesh = self.domain.cmesh
conn, offsets = cmesh.get_incident(0, region.cells, region.tdim,
ret_offsets=True)
vertices = nm.unique(conn)
remap = prepare_remap(vertices, region.n_v_max)
n_dof = vertices.shape[0]
aux = nm.unique(nm.diff(offsets))
assert_(len(aux) == 1, 'region with multiple reference geometries!')
offset = aux[0]
# Remap vertex node connectivity to field-local numbering.
aux = conn.reshape((-1, offset)).astype(nm.int32)
self.econn[:, :offset] = nm.take(remap, aux)
return n_dof, remap
def setup_extra_data(self, geometry, info, is_trace):
dct = info.dc_type.type
if geometry != None:
geometry_flag = 'surface' in geometry
else:
geometry_flag = False
if (dct == 'surface') or (geometry_flag):
reg = info.get_region()
mreg_name = info.get_region_name(can_trace=False)
self.domain.create_surface_group(reg)
self.setup_surface_data(reg, is_trace, mreg_name)
elif dct == 'edge':
raise NotImplementedError('dof connectivity type %s' % dct)
elif dct == 'point':
self.setup_point_data(self, info.region)
elif dct not in ('volume', 'scalar', 'custom'):
raise ValueError('unknown dof connectivity type! (%s)' % dct)
def setup_point_data(self, field, region):
if region.name not in self.point_data:
conn = field.get_dofs_in_region(region, merge=True)
conn.shape += (1,)
self.point_data[region.name] = conn
def setup_surface_data(self, region, is_trace=False, trace_region=None):
"""nodes[leconn] == econn"""
"""nodes are sorted by node number -> same order as region.vertices"""
if region.name not in self.surface_data:
sd = FESurface('surface_data_%s' % region.name, region,
self.efaces, self.econn, self.region)
self.surface_data[region.name] = sd
if region.name in self.surface_data and is_trace:
sd = self.surface_data[region.name]
sd.setup_mirror_connectivity(region, trace_region)
return self.surface_data[region.name]
def get_econn(self, conn_type, region, is_trace=False, integration=None):
"""
Get extended connectivity of the given type in the given region.
"""
ct = conn_type.type if isinstance(conn_type, Struct) else conn_type
if ct in ('volume', 'custom'):
if region.name == self.region.name:
conn = self.econn
else:
tco = integration in ('volume', 'custom')
cells = region.get_cells(true_cells_only=tco)
ii = self.region.get_cell_indices(cells, true_cells_only=tco)
conn = nm.take(self.econn, ii, axis=0)
elif ct == 'surface':
sd = self.surface_data[region.name]
conn = sd.get_connectivity(is_trace=is_trace)
elif ct == 'edge':
raise NotImplementedError('connectivity type %s' % ct)
elif ct == 'point':
conn = self.point_data[region.name]
else:
raise ValueError('unknown connectivity type! (%s)' % ct)
return conn
def average_qp_to_vertices(self, data_qp, integral):
"""
Average data given in quadrature points in region elements into
region vertices.
.. math::
u_n = \sum_e (u_{e,avg} * volume_e) / \sum_e volume_e
= \sum_e \int_{volume_e} u / \sum volume_e
"""
region = self.region
n_cells = region.get_n_cells()
if n_cells != data_qp.shape[0]:
msg = 'incomatible shape! (%d == %d)' % (n_cells,
data_qp.shape[0])
raise ValueError(msg)
n_vertex = self.n_vertex_dof
nc = data_qp.shape[2]
nod_vol = nm.zeros((n_vertex,), dtype=nm.float64)
data_vertex = nm.zeros((n_vertex, nc), dtype=nm.float64)
vg = self.get_mapping(self.region, integral, 'volume')[0]
volume = nm.squeeze(vg.volume)
iels = self.region.get_cells()
data_e = nm.zeros((volume.shape[0], 1, nc, 1), dtype=nm.float64)
vg.integrate(data_e, data_qp[iels])
ir = nm.arange(nc, dtype=nm.int32)
conn = self.econn[:, :self.gel.n_vertex]
for ii, cc in enumerate(conn):
# Assumes unique nodes in cc!
ind2, ind1 = nm.meshgrid(ir, cc)
data_vertex[ind1,ind2] += data_e[iels[ii],0,:,0]
nod_vol[cc] += volume[ii]
data_vertex /= nod_vol[:,nm.newaxis]
return data_vertex
class SurfaceField(FEField):
"""
Finite element field base class over surface (element dimension is one
less than space dimension).
"""
def _check_region(self, region):
"""
Check whether the `region` can be used for the
field.
Returns
-------
ok : bool
True if the region is usable for the field.
"""
ok1 = ((region.kind_tdim == (region.tdim - 1))
and (region.get_n_cells(True) > 0))
if not ok1:
output('bad region topological dimension and kind! (%d, %s)'
% (region.tdim, region.kind))
n_ns = region.get_facet_indices().shape[0] - region.get_n_cells(True)
ok2 = n_ns == 0
if not ok2:
output('%d region facets are not on the domain surface!' % n_ns)
return ok1 and ok2
def _setup_geometry(self):
"""
Setup the field region geometry.
"""
for key, vgel in six.iteritems(self.domain.geom_els):
self.gel = vgel.surface_facet
break
if self.gel is None:
raise ValueError('cells with no surface!')
self.is_surface = True
def _create_interpolant(self):
name = '%s_%s_%s_%d%s' % (self.gel.name, self.space,
self.poly_space_base, self.approx_order,
'B' * self.force_bubble)
ps = PolySpace.any_from_args(name, self.gel, self.approx_order,
base=self.poly_space_base,
force_bubble=self.force_bubble)
self.poly_space = ps
def setup_extra_data(self, geometry, info, is_trace):
dct = info.dc_type.type
if dct != 'surface':
msg = "dof connectivity type must be 'surface'! (%s)" % dct
raise ValueError(msg)
reg = info.get_region()
if reg.name not in self.surface_data:
# Defined in setup_vertex_dofs()
msg = 'no surface data of surface field! (%s)' % reg.name
raise ValueError(msg)
if reg.name in self.surface_data and is_trace:
sd = self.surface_data[reg.name]
mreg_name = info.get_region_name(can_trace=False)
sd.setup_mirror_connectivity(reg, mreg_name)
def _init_econn(self):
"""
Initialize the extended DOF connectivity.
"""
n_ep = self.poly_space.n_nod
n_cell = self.region.get_n_cells(is_surface=self.is_surface)
self.econn = nm.zeros((n_cell, n_ep), nm.int32)
def _setup_vertex_dofs(self):
"""
Setup vertex DOF connectivity.
"""
if self.node_desc.vertex is None:
return 0, None
region = self.region
remap = prepare_remap(region.vertices, region.n_v_max)
n_dof = region.vertices.shape[0]
# Remap vertex node connectivity to field-local numbering.
conn, gel = self.domain.get_conn(ret_gel=True)
faces = gel.get_surface_entities()
aux = FESurface('aux', region, faces, conn)
self.econn[:, :aux.n_fp] = aux.leconn
self.surface_data[region.name] = aux
return n_dof, remap
def _setup_bubble_dofs(self):
"""
Setup bubble DOF connectivity.
"""
return 0, None, None
def get_econn(self, conn_type, region, is_trace=False,
integration=None):
"""
Get extended connectivity of the given type in the given region.
"""
ct = conn_type.type if isinstance(conn_type, Struct) else conn_type
if ct != 'surface':
msg = 'connectivity type must be "surface"! (%s)' % ct
raise ValueError(msg)
sd = self.surface_data[region.name]
conn = sd.get_connectivity(local=True, is_trace=is_trace)
return conn
def average_qp_to_vertices(self, data_qp, integral):
"""
Average data given in quadrature points in region elements into
region vertices.
.. math::
u_n = \sum_e (u_{e,avg} * area_e) / \sum_e area_e
= \sum_e \int_{area_e} u / \sum area_e
"""
region = self.region
n_cells = region.get_n_cells(True)
if n_cells != data_qp.shape[0]:
msg = 'incomatible shape! (%d == %d)' % (n_cells,
data_qp.shape[0])
raise ValueError(msg)
n_vertex = len(region.vertices)
nc = data_qp.shape[2]
nod_vol = nm.zeros((n_vertex,), dtype=nm.float64)
data_vertex = nm.zeros((n_vertex, nc), dtype=nm.float64)
sg = self.get_mapping(self.region, integral, 'surface')[0]
area = nm.squeeze(sg.volume)
n_cells = region.get_n_cells(True)
iels = nm.arange(n_cells, dtype=nm.int32)
data_e = nm.zeros((area.shape[0], 1, nc, 1), dtype=nm.float64)
sg.integrate(data_e, data_qp[iels])
ir = nm.arange(nc, dtype=nm.int32)
sd = self.domain.surface_groups[region.name]
# Should be vertex connectivity!
conn = sd.get_connectivity(local=True)
for ii, cc in enumerate(conn):
# Assumes unique nodes in cc!
ind2, ind1 = nm.meshgrid(ir, cc)
data_vertex[ind1,ind2] += data_e[iels[ii],0,:,0]
nod_vol[cc] += area[ii]
data_vertex /= nod_vol[:,nm.newaxis]
return data_vertex
class H1Mixin(Struct):
"""
Methods of fields specific to H1 space.
"""
def _setup_shape(self):
"""
Setup the field's shape-related attributes, see :class:`Field`.
"""
self.n_components = nm.prod(self.shape)
self.val_shape = self.shape
| [
"sfepy.discrete.fem.mesh.Mesh.from_data",
"sfepy.discrete.integrals.Integral",
"sfepy.base.base.Struct",
"sfepy.discrete.fem.linearizer.get_eval_coors",
"sfepy.discrete.fem.meshio.convert_complex_output",
"sfepy.discrete.fem.linearizer.create_output",
"sfepy.discrete.fem.poly_spaces.PolySpace.any_from_a... | [((2582, 2610), 'numpy.dot', 'nm.dot', (['bf', 'mesh_coors[conn]'], {}), '(bf, mesh_coors[conn])\n', (2588, 2610), True, 'import numpy as nm\n'), ((2630, 2655), 'numpy.swapaxes', 'nm.swapaxes', (['ecoors', '(0)', '(1)'], {}), '(ecoors, 0, 1)\n', (2641, 2655), True, 'import numpy as nm\n'), ((2805, 2846), 'numpy.zeros', 'nm.zeros', (['(n_face, n_qp, dim)', 'nm.float64'], {}), '((n_face, n_qp, dim), nm.float64)\n', (2813, 2846), True, 'import numpy as nm\n'), ((6368, 6414), 'sfepy.discrete.fem.linearizer.get_eval_coors', 'get_eval_coors', (['vertex_coors', 'vertex_conn', 'gps'], {}), '(vertex_coors, vertex_conn, gps)\n', (6382, 6414), False, 'from sfepy.discrete.fem.linearizer import get_eval_dofs, get_eval_coors, create_output\n'), ((6464, 6582), 'sfepy.discrete.fem.linearizer.create_output', 'create_output', (['eval_dofs', 'eval_coors', 'vertex_conn.shape[0]', 'ps'], {'min_level': 'min_level', 'max_level': 'max_level', 'eps': 'eps'}), '(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=\n min_level, max_level=max_level, eps=eps)\n', (6477, 6582), False, 'from sfepy.discrete.fem.linearizer import get_eval_dofs, get_eval_coors, create_output\n'), ((6701, 6796), 'sfepy.discrete.fem.mesh.Mesh.from_data', 'Mesh.from_data', (['"""linearized_mesh"""', 'coors', 'None', '[conn]', '[mat_ids]', 'field.domain.mesh.descs'], {}), "('linearized_mesh', coors, None, [conn], [mat_ids], field.\n domain.mesh.descs)\n", (6715, 6796), False, 'from sfepy.discrete.fem.mesh import Mesh\n'), ((6848, 6956), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""vertex"""', 'data': 'vdofs', 'var_name': 'name', 'dofs': 'None', 'mesh': 'mesh', 'level': 'level'}), "(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=\n None, mesh=mesh, level=level)\n", (6854, 6956), False, 'from sfepy.base.base import Struct\n'), ((7009, 7036), 'sfepy.discrete.fem.meshio.convert_complex_output', 'convert_complex_output', (['out'], {}), '(out)\n', (7031, 7036), False, 'from sfepy.discrete.fem.meshio import convert_complex_output\n'), ((1598, 1620), 'six.itervalues', 'six.itervalues', (['fields'], {}), '(fields)\n', (1612, 1620), False, 'import six\n'), ((2952, 2978), 'numpy.dot', 'nm.dot', (['bfs[:, 0, :]', 'vals'], {}), '(bfs[:, 0, :], vals)\n', (2958, 2978), True, 'import numpy as nm\n'), ((3463, 3653), 'sfepy.discrete.evaluate.eval_in_els_and_qp', 'eval_in_els_and_qp', (['expression', 'iels', 'coors', 'fields', 'materials', 'variables'], {'functions': 'functions', 'mode': 'mode', 'term_mode': 'term_mode', 'extra_args': 'extra_args', 'verbose': 'verbose', 'kwargs': 'kwargs'}), '(expression, iels, coors, fields, materials, variables,\n functions=functions, mode=mode, term_mode=term_mode, extra_args=\n extra_args, verbose=verbose, kwargs=kwargs)\n', (3481, 3653), False, 'from sfepy.discrete.evaluate import eval_in_els_and_qp\n'), ((8522, 8565), 'sfepy.discrete.common.fields.parse_shape', 'parse_shape', (['shape', 'region.domain.shape.dim'], {}), '(shape, region.domain.shape.dim)\n', (8533, 8565), False, 'from sfepy.discrete.common.fields import parse_shape, Field\n'), ((8738, 8811), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'name': 'name', 'dtype': 'dtype', 'shape': 'shape', 'region': 'region'}), '(self, name=name, dtype=dtype, shape=shape, region=region)\n', (8753, 8811), False, 'from sfepy.base.base import Struct\n'), ((10902, 10933), 'sfepy.discrete.fem.utils.invert_remap', 'invert_remap', (['self.vertex_remap'], {}), '(self.vertex_remap)\n', (10914, 10933), False, 'from sfepy.discrete.fem.utils import extend_cell_data, prepare_remap, invert_remap, get_min_value\n'), ((13667, 13711), 'numpy.empty', 'nm.empty', (['(self.n_nod, mesh.dim)', 'nm.float64'], {}), '((self.n_nod, mesh.dim), nm.float64)\n', (13675, 13711), True, 'import numpy as nm\n'), ((16374, 16404), 'numpy.empty', 'nm.empty', (['(0,)'], {'dtype': 'nm.int32'}), '((0,), dtype=nm.int32)\n', (16382, 16404), True, 'import numpy as nm\n'), ((16583, 16613), 'numpy.empty', 'nm.empty', (['(0,)'], {'dtype': 'nm.int32'}), '((0,), dtype=nm.int32)\n', (16591, 16613), True, 'import numpy as nm\n'), ((16867, 16897), 'numpy.empty', 'nm.empty', (['(0,)'], {'dtype': 'nm.int32'}), '((0,), dtype=nm.int32)\n', (16875, 16897), True, 'import numpy as nm\n'), ((17151, 17181), 'numpy.empty', 'nm.empty', (['(0,)'], {'dtype': 'nm.int32'}), '((0,), dtype=nm.int32)\n', (17159, 17181), True, 'import numpy as nm\n'), ((20721, 20774), 'numpy.einsum', 'nm.einsum', (['"""cji,cjk->cik"""', 'self.basis_transform', 'evec'], {}), "('cji,cjk->cik', self.basis_transform, evec)\n", (20730, 20774), True, 'import numpy as nm\n'), ((24365, 24388), 'sfepy.base.base.assert_', 'assert_', (['(dofs.ndim == 2)'], {}), '(dofs.ndim == 2)\n', (24372, 24388), False, 'from sfepy.base.base import output, get_default, assert_\n'), ((24431, 24459), 'sfepy.base.base.assert_', 'assert_', (['(n_nod == self.n_nod)'], {}), '(n_nod == self.n_nod)\n', (24438, 24459), False, 'from sfepy.base.base import output, get_default, assert_\n'), ((24468, 24497), 'sfepy.base.base.assert_', 'assert_', (['(dpn == self.shape[0])'], {}), '(dpn == self.shape[0])\n', (24475, 24497), False, 'from sfepy.base.base import output, get_default, assert_\n'), ((24698, 24747), 'sfepy.discrete.fem.linearizer.get_eval_dofs', 'get_eval_dofs', (['dofs', 'self.econn', 'ps'], {'ori': 'self.ori'}), '(dofs, self.econn, ps, ori=self.ori)\n', (24711, 24747), False, 'from sfepy.discrete.fem.linearizer import get_eval_dofs, get_eval_coors, create_output\n'), ((24769, 24815), 'sfepy.discrete.fem.linearizer.get_eval_coors', 'get_eval_coors', (['vertex_coors', 'vertex_conn', 'gps'], {}), '(vertex_coors, vertex_conn, gps)\n', (24783, 24815), False, 'from sfepy.discrete.fem.linearizer import get_eval_dofs, get_eval_coors, create_output\n'), ((24873, 24991), 'sfepy.discrete.fem.linearizer.create_output', 'create_output', (['eval_dofs', 'eval_coors', 'vertex_conn.shape[0]', 'ps'], {'min_level': 'min_level', 'max_level': 'max_level', 'eps': 'eps'}), '(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=\n min_level, max_level=max_level, eps=eps)\n', (24886, 24991), False, 'from sfepy.discrete.fem.linearizer import get_eval_dofs, get_eval_coors, create_output\n'), ((25126, 25220), 'sfepy.discrete.fem.mesh.Mesh.from_data', 'Mesh.from_data', (['"""linearized_mesh"""', 'coors', 'None', '[conn]', '[mat_ids]', 'self.domain.mesh.descs'], {}), "('linearized_mesh', coors, None, [conn], [mat_ids], self.\n domain.mesh.descs)\n", (25140, 25220), False, 'from sfepy.discrete.fem.mesh import Mesh\n'), ((28285, 28312), 'sfepy.discrete.fem.meshio.convert_complex_output', 'convert_complex_output', (['out'], {}), '(out)\n', (28307, 28312), False, 'from sfepy.discrete.fem.meshio import convert_complex_output\n'), ((30216, 30228), 'time.clock', 'time.clock', ([], {}), '()\n', (30226, 30228), False, 'import time\n'), ((30951, 30963), 'time.clock', 'time.clock', ([], {}), '()\n', (30961, 30963), False, 'import time\n'), ((31721, 31759), 'sfepy.discrete.integrals.Integral', 'Integral', (['"""i"""'], {'order': 'self.approx_order'}), "('i', order=self.approx_order)\n", (31729, 31759), False, 'from sfepy.discrete.integrals import Integral\n'), ((31859, 31887), 'numpy.dot', 'nm.dot', (['bf', 'dofs[self.econn]'], {}), '(bf, dofs[self.econn])\n', (31865, 31887), True, 'import numpy as nm\n'), ((31906, 31932), 'numpy.swapaxes', 'nm.swapaxes', (['data_qp', '(0)', '(1)'], {}), '(data_qp, 0, 1)\n', (31917, 31932), True, 'import numpy as nm\n'), ((37564, 37599), 'six.iteritems', 'six.iteritems', (['self.domain.geom_els'], {}), '(self.domain.geom_els)\n', (37577, 37599), False, 'import six\n'), ((38245, 38367), 'sfepy.discrete.fem.poly_spaces.PolySpace.any_from_args', 'PolySpace.any_from_args', (['name', 'self.gel', 'self.approx_order'], {'base': 'self.poly_space_base', 'force_bubble': 'self.force_bubble'}), '(name, self.gel, self.approx_order, base=self.\n poly_space_base, force_bubble=self.force_bubble)\n', (38268, 38367), False, 'from sfepy.discrete.fem.poly_spaces import PolySpace\n'), ((38669, 38703), 'numpy.zeros', 'nm.zeros', (['(n_cell, n_ep)', 'nm.int32'], {}), '((n_cell, n_ep), nm.int32)\n', (38677, 38703), True, 'import numpy as nm\n'), ((39090, 39105), 'numpy.unique', 'nm.unique', (['conn'], {}), '(conn)\n', (39099, 39105), True, 'import numpy as nm\n'), ((39122, 39161), 'sfepy.discrete.fem.utils.prepare_remap', 'prepare_remap', (['vertices', 'region.n_v_max'], {}), '(vertices, region.n_v_max)\n', (39135, 39161), False, 'from sfepy.discrete.fem.utils import extend_cell_data, prepare_remap, invert_remap, get_min_value\n'), ((39500, 39519), 'numpy.take', 'nm.take', (['remap', 'aux'], {}), '(remap, aux)\n', (39507, 39519), True, 'import numpy as nm\n'), ((42967, 43006), 'numpy.zeros', 'nm.zeros', (['(n_vertex,)'], {'dtype': 'nm.float64'}), '((n_vertex,), dtype=nm.float64)\n', (42975, 43006), True, 'import numpy as nm\n'), ((43029, 43071), 'numpy.zeros', 'nm.zeros', (['(n_vertex, nc)'], {'dtype': 'nm.float64'}), '((n_vertex, nc), dtype=nm.float64)\n', (43037, 43071), True, 'import numpy as nm\n'), ((43157, 43178), 'numpy.squeeze', 'nm.squeeze', (['vg.volume'], {}), '(vg.volume)\n', (43167, 43178), True, 'import numpy as nm\n'), ((43236, 43291), 'numpy.zeros', 'nm.zeros', (['(volume.shape[0], 1, nc, 1)'], {'dtype': 'nm.float64'}), '((volume.shape[0], 1, nc, 1), dtype=nm.float64)\n', (43244, 43291), True, 'import numpy as nm\n'), ((43350, 43379), 'numpy.arange', 'nm.arange', (['nc'], {'dtype': 'nm.int32'}), '(nc, dtype=nm.int32)\n', (43359, 43379), True, 'import numpy as nm\n'), ((44719, 44754), 'six.iteritems', 'six.iteritems', (['self.domain.geom_els'], {}), '(self.domain.geom_els)\n', (44732, 44754), False, 'import six\n'), ((45177, 45299), 'sfepy.discrete.fem.poly_spaces.PolySpace.any_from_args', 'PolySpace.any_from_args', (['name', 'self.gel', 'self.approx_order'], {'base': 'self.poly_space_base', 'force_bubble': 'self.force_bubble'}), '(name, self.gel, self.approx_order, base=self.\n poly_space_base, force_bubble=self.force_bubble)\n', (45200, 45299), False, 'from sfepy.discrete.fem.poly_spaces import PolySpace\n'), ((46303, 46337), 'numpy.zeros', 'nm.zeros', (['(n_cell, n_ep)', 'nm.int32'], {}), '((n_cell, n_ep), nm.int32)\n', (46311, 46337), True, 'import numpy as nm\n'), ((46552, 46598), 'sfepy.discrete.fem.utils.prepare_remap', 'prepare_remap', (['region.vertices', 'region.n_v_max'], {}), '(region.vertices, region.n_v_max)\n', (46565, 46598), False, 'from sfepy.discrete.fem.utils import extend_cell_data, prepare_remap, invert_remap, get_min_value\n'), ((46820, 46857), 'sfepy.discrete.fem.fe_surface.FESurface', 'FESurface', (['"""aux"""', 'region', 'faces', 'conn'], {}), "('aux', region, faces, conn)\n", (46829, 46857), False, 'from sfepy.discrete.fem.fe_surface import FESurface\n'), ((48320, 48359), 'numpy.zeros', 'nm.zeros', (['(n_vertex,)'], {'dtype': 'nm.float64'}), '((n_vertex,), dtype=nm.float64)\n', (48328, 48359), True, 'import numpy as nm\n'), ((48382, 48424), 'numpy.zeros', 'nm.zeros', (['(n_vertex, nc)'], {'dtype': 'nm.float64'}), '((n_vertex, nc), dtype=nm.float64)\n', (48390, 48424), True, 'import numpy as nm\n'), ((48509, 48530), 'numpy.squeeze', 'nm.squeeze', (['sg.volume'], {}), '(sg.volume)\n', (48519, 48530), True, 'import numpy as nm\n'), ((48589, 48623), 'numpy.arange', 'nm.arange', (['n_cells'], {'dtype': 'nm.int32'}), '(n_cells, dtype=nm.int32)\n', (48598, 48623), True, 'import numpy as nm\n'), ((48642, 48695), 'numpy.zeros', 'nm.zeros', (['(area.shape[0], 1, nc, 1)'], {'dtype': 'nm.float64'}), '((area.shape[0], 1, nc, 1), dtype=nm.float64)\n', (48650, 48695), True, 'import numpy as nm\n'), ((48754, 48783), 'numpy.arange', 'nm.arange', (['nc'], {'dtype': 'nm.int32'}), '(nc, dtype=nm.int32)\n', (48763, 48783), True, 'import numpy as nm\n'), ((49460, 49479), 'numpy.prod', 'nm.prod', (['self.shape'], {}), '(self.shape)\n', (49467, 49479), True, 'import numpy as nm\n'), ((1392, 1424), 'numpy.zeros_like', 'nm.zeros_like', (['domain.mesh.coors'], {}), '(domain.mesh.coors)\n', (1405, 1424), True, 'import numpy as nm\n'), ((12042, 12071), 'numpy.hstack', 'nm.hstack', (['(self.efaces, efs)'], {}), '((self.efaces, efs))\n', (12051, 12071), True, 'import numpy as nm\n'), ((12268, 12297), 'numpy.hstack', 'nm.hstack', (['(self.efaces, efs)'], {}), '((self.efaces, efs))\n', (12277, 12297), True, 'import numpy as nm\n'), ((17423, 17443), 'numpy.concatenate', 'nm.concatenate', (['dofs'], {}), '(dofs)\n', (17437, 17443), True, 'import numpy as nm\n'), ((18283, 18317), 'sfepy.base.base.Struct', 'Struct', ([], {'vals': 'vals', 'weights': 'weights'}), '(vals=vals, weights=weights)\n', (18289, 18317), False, 'from sfepy.base.base import Struct\n'), ((19029, 19066), 'numpy.setdiff1d', 'nm.setdiff1d', (['self.econn0', 'self.econn'], {}), '(self.econn0, self.econn)\n', (19041, 19066), True, 'import numpy as nm\n'), ((22147, 22209), 'sfepy.base.base.Struct', 'Struct', ([], {'name': "('BQP_%s' % sd.bkey)", 'vals': 'vals', 'weights': 'qp.weights'}), "(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights)\n", (22153, 22209), False, 'from sfepy.base.base import Struct\n'), ((22503, 22521), 'numpy.isrealobj', 'nm.isrealobj', (['dofs'], {}), '(dofs)\n', (22515, 22521), True, 'import numpy as nm\n'), ((22926, 22976), 'numpy.empty', 'nm.empty', (['(n_nod, dofs.shape[1])'], {'dtype': 'self.dtype'}), '((n_nod, dofs.shape[1]), dtype=self.dtype)\n', (22934, 22976), True, 'import numpy as nm\n'), ((23099, 23163), 'sfepy.discrete.fem.utils.extend_cell_data', 'extend_cell_data', (['dofs', 'self.domain', 'self.region'], {'val': 'fill_value'}), '(dofs, self.domain, self.region, val=fill_value)\n', (23115, 23163), False, 'from sfepy.discrete.fem.utils import extend_cell_data, prepare_remap, invert_remap, get_min_value\n'), ((26672, 26692), 'sfepy.base.base.Struct', 'Struct', ([], {'kind': '"""strip"""'}), "(kind='strip')\n", (26678, 26692), False, 'from sfepy.base.base import Struct\n'), ((26774, 26886), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""full"""', 'data': 'dofs', 'var_name': 'var_name', 'dofs': 'dof_names', 'field_name': 'self.name'}), "(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=\n dof_names, field_name=self.name)\n", (26780, 26886), False, 'from sfepy.base.base import Struct\n'), ((28974, 29035), 'sfepy.discrete.fem.mesh.Mesh.from_data', 'Mesh.from_data', (['self.name', 'coors', 'None', 'conns', 'mat_ids', 'descs'], {}), '(self.name, coors, None, conns, mat_ids, descs)\n', (28988, 29035), False, 'from sfepy.discrete.fem.mesh import Mesh\n'), ((30172, 30201), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""evaluate_cache"""'}), "(name='evaluate_cache')\n", (30178, 30201), False, 'from sfepy.base.base import Struct\n'), ((30418, 30444), 'sfepy.discrete.fem.geometry_element.create_geometry_elements', 'create_geometry_elements', ([], {}), '()\n', (30442, 30444), False, 'from sfepy.discrete.fem.geometry_element import create_geometry_elements\n'), ((31061, 31080), 'scipy.spatial.KDTree', 'KDTree', (['cmesh.coors'], {}), '(cmesh.coors)\n', (31067, 31080), False, 'from scipy.spatial import KDTree\n'), ((33670, 33715), 'sfepy.discrete.fem.mappings.VolumeMapping', 'VolumeMapping', (['coors', 'conn'], {'poly_space': 'geo_ps'}), '(coors, conn, poly_space=geo_ps)\n', (33683, 33715), False, 'from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping\n'), ((37069, 37137), 'sfepy.base.base.output', 'output', (['("bad region kind! (is: %r, should be: \'cell\')" % region.kind)'], {}), '("bad region kind! (is: %r, should be: \'cell\')" % region.kind)\n', (37075, 37137), False, 'from sfepy.base.base import output, get_default, assert_\n'), ((39221, 39237), 'numpy.diff', 'nm.diff', (['offsets'], {}), '(offsets)\n', (39228, 39237), True, 'import numpy as nm\n'), ((40842, 40934), 'sfepy.discrete.fem.fe_surface.FESurface', 'FESurface', (["('surface_data_%s' % region.name)", 'region', 'self.efaces', 'self.econn', 'self.region'], {}), "('surface_data_%s' % region.name, region, self.efaces, self.econn,\n self.region)\n", (40851, 40934), False, 'from sfepy.discrete.fem.fe_surface import FESurface\n'), ((43536, 43555), 'numpy.meshgrid', 'nm.meshgrid', (['ir', 'cc'], {}), '(ir, cc)\n', (43547, 43555), True, 'import numpy as nm\n'), ((44259, 44353), 'sfepy.base.base.output', 'output', (["('bad region topological dimension and kind! (%d, %s)' % (region.tdim,\n region.kind))"], {}), "('bad region topological dimension and kind! (%d, %s)' % (region.tdim,\n region.kind))\n", (44265, 44353), False, 'from sfepy.base.base import output, get_default, assert_\n'), ((44504, 44568), 'sfepy.base.base.output', 'output', (["('%d region facets are not on the domain surface!' % n_ns)"], {}), "('%d region facets are not on the domain surface!' % n_ns)\n", (44510, 44568), False, 'from sfepy.base.base import output, get_default, assert_\n'), ((49032, 49051), 'numpy.meshgrid', 'nm.meshgrid', (['ir', 'cc'], {}), '(ir, cc)\n', (49043, 49051), True, 'import numpy as nm\n'), ((12586, 12615), 'numpy.hstack', 'nm.hstack', (['(self.eedges, efs)'], {}), '((self.eedges, efs))\n', (12595, 12615), True, 'import numpy as nm\n'), ((22552, 22571), 'sfepy.discrete.fem.utils.get_min_value', 'get_min_value', (['dofs'], {}), '(dofs)\n', (22565, 22571), False, 'from sfepy.discrete.fem.utils import extend_cell_data, prepare_remap, invert_remap, get_min_value\n'), ((22698, 22722), 'sfepy.discrete.fem.utils.get_min_value', 'get_min_value', (['dofs.real'], {}), '(dofs.real)\n', (22711, 22722), False, 'from sfepy.discrete.fem.utils import extend_cell_data, prepare_remap, invert_remap, get_min_value\n'), ((28095, 28213), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""vertex"""', 'data': 'vdofs', 'var_name': 'var_name', 'dofs': 'dof_names', 'mesh': 'mesh', 'levels': 'levels'}), "(name='output_data', mode='vertex', data=vdofs, var_name=var_name,\n dofs=dof_names, mesh=mesh, levels=levels)\n", (28101, 28213), False, 'from sfepy.base.base import Struct\n'), ((34021, 34051), 'sfepy.base.base.assert_', 'assert_', (['(self.approx_order > 0)'], {}), '(self.approx_order > 0)\n', (34028, 34051), False, 'from sfepy.base.base import output, get_default, assert_\n'), ((34483, 34529), 'sfepy.discrete.fem.mappings.SurfaceMapping', 'SurfaceMapping', (['coors', 'conn'], {'poly_space': 'geo_ps'}), '(coors, conn, poly_space=geo_ps)\n', (34497, 34529), False, 'from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping\n'), ((37247, 37352), 'sfepy.base.base.output', 'output', (["('cells with a bad topological dimension! (%d == %d)' % (region.kind_tdim,\n domain.shape.tdim))"], {}), "('cells with a bad topological dimension! (%d == %d)' % (region.\n kind_tdim, domain.shape.tdim))\n", (37253, 37352), False, 'from sfepy.base.base import output, get_default, assert_\n'), ((41837, 41868), 'numpy.take', 'nm.take', (['self.econn', 'ii'], {'axis': '(0)'}), '(self.econn, ii, axis=0)\n', (41844, 41868), True, 'import numpy as nm\n'), ((11864, 11902), 'numpy.concatenate', 'nm.concatenate', (['[nd[ie] for ie in eof]'], {}), '([nd[ie] for ie in eof])\n', (11878, 11902), True, 'import numpy as nm\n'), ((11922, 11935), 'numpy.array', 'nm.array', (['efs'], {}), '(efs)\n', (11930, 11935), True, 'import numpy as nm\n'), ((12148, 12161), 'numpy.array', 'nm.array', (['efs'], {}), '(efs)\n', (12156, 12161), True, 'import numpy as nm\n'), ((22758, 22782), 'sfepy.discrete.fem.utils.get_min_value', 'get_min_value', (['dofs.imag'], {}), '(dofs.imag)\n', (22771, 22782), False, 'from sfepy.discrete.fem.utils import extend_cell_data, prepare_remap, invert_remap, get_min_value\n'), ((30902, 30914), 'time.clock', 'time.clock', ([], {}), '()\n', (30912, 30914), False, 'import time\n'), ((31115, 31127), 'time.clock', 'time.clock', ([], {}), '()\n', (31125, 31127), False, 'import time\n'), ((12454, 12467), 'numpy.array', 'nm.array', (['efs'], {}), '(efs)\n', (12462, 12467), True, 'import numpy as nm\n'), ((27341, 27432), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""vertex"""', 'data': 'ext', 'var_name': 'var_name', 'dofs': 'dof_names'}), "(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs\n =dof_names)\n", (27347, 27432), False, 'from sfepy.base.base import Struct\n'), ((27625, 27714), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'ext', 'var_name': 'var_name', 'dofs': 'dof_names'}), "(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=\n dof_names)\n", (27631, 27714), False, 'from sfepy.base.base import Struct\n'), ((34971, 34988), 'numpy.roll', 'nm.roll', (['indx', '(-1)'], {}), '(indx, -1)\n', (34978, 34988), True, 'import numpy as nm\n'), ((35161, 35187), 'sfepy.base.base.Struct', 'Struct', ([], {'n_nod': 'bf.shape[-1]'}), '(n_nod=bf.shape[-1])\n', (35167, 35187), False, 'from sfepy.base.base import Struct\n'), ((35888, 35914), 'sfepy.base.base.Struct', 'Struct', ([], {'n_nod': 'bf.shape[-1]'}), '(n_nod=bf.shape[-1])\n', (35894, 35914), False, 'from sfepy.base.base import Struct\n')] |
from __future__ import absolute_import
import os.path as op
import shutil
import numpy as nm
from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_
from sfepy.base.base import Struct
from sfepy.homogenization.engine import HomogenizationEngine
from sfepy.homogenization.homogen_app import HomogenizationApp
from sfepy.homogenization.coefficients import Coefficients
from sfepy.homogenization.coefs_base import CoefDummy
from sfepy.applications import PDESolverApp
from sfepy.base.plotutils import plt
import six
from six.moves import range
def try_set_defaults(obj, attr, defaults, recur=False):
try:
values = getattr(obj, attr)
except:
values = defaults
else:
if recur and isinstance(values, dict):
for key, val in six.iteritems(values):
set_defaults(val, defaults)
else:
set_defaults(values, defaults)
return values
def save_raw_bg_logs(filename, logs):
"""
Save raw band gaps `logs` into the `filename` file.
"""
out = {}
iranges = nm.cumsum([0] + [len(ii) for ii in logs.freqs])
out['iranges'] = iranges
for key, log in ordered_iteritems(logs.to_dict()):
out[key] = nm.concatenate(log, axis=0)
with open(filename, 'w') as fd:
nm.savez(fd, **out)
def transform_plot_data(datas, plot_transform, conf):
if plot_transform is not None:
fun = conf.get_function(plot_transform[0])
dmin, dmax = 1e+10, -1e+10
tdatas = []
for data in datas:
tdata = data.copy()
if plot_transform is not None:
tdata = fun(tdata, *plot_transform[1:])
dmin = min(dmin, nm.nanmin(tdata))
dmax = max(dmax, nm.nanmax(tdata))
tdatas.append(tdata)
dmin, dmax = min(dmax - 1e-8, dmin), max(dmin + 1e-8, dmax)
return (dmin, dmax), tdatas
def plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range,
show=False, clear=False, new_axes=False):
"""
Plot resonance/eigen-frequencies.
`valid` must correspond to `freq_range`
resonances : red
masked resonances: dotted red
"""
if plt is None: return
assert_(len(valid) == len(freq_range))
fig = plt.figure(fig_num)
if clear:
fig.clf()
if new_axes:
ax = fig.add_subplot(111)
else:
ax = fig.gca()
l0 = l1 = None
for ii, f in enumerate(freq_range):
if valid[ii]:
l0 = ax.plot([f, f], plot_range, **plot_rsc['resonance'])[0]
else:
l1 = ax.plot([f, f], plot_range, **plot_rsc['masked'])[0]
if l0:
l0.set_label(plot_labels['resonance'])
if l1:
l1.set_label(plot_labels['masked'])
if new_axes:
ax.set_xlim([freq_range[0], freq_range[-1]])
ax.set_ylim(plot_range)
if show:
plt.show()
return fig
def plot_logs(fig_num, plot_rsc, plot_labels,
freqs, logs, valid, freq_range, plot_range,
draw_eigs=True, show_legend=True, show=False,
clear=False, new_axes=False):
"""
Plot logs of min/middle/max eigs of a mass matrix.
"""
if plt is None: return
fig = plt.figure(fig_num)
if clear:
fig.clf()
if new_axes:
ax = fig.add_subplot(111)
else:
ax = fig.gca()
if draw_eigs:
plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range,
plot_range)
for ii, log in enumerate(logs):
l1 = ax.plot(freqs[ii], log[:, -1], **plot_rsc['eig_max'])
if log.shape[1] >= 2:
l2 = ax.plot(freqs[ii], log[:, 0], **plot_rsc['eig_min'])
else:
l2 = None
if log.shape[1] == 3:
l3 = ax.plot(freqs[ii], log[:, 1], **plot_rsc['eig_mid'])
else:
l3 = None
l1[0].set_label(plot_labels['eig_max'])
if l2:
l2[0].set_label(plot_labels['eig_min'])
if l3:
l3[0].set_label(plot_labels['eig_mid'])
fmin, fmax = freqs[0][0], freqs[-1][-1]
ax.plot([fmin, fmax], [0, 0], **plot_rsc['x_axis'])
ax.set_xlabel(plot_labels['x_axis'])
ax.set_ylabel(plot_labels['y_axis'])
if new_axes:
ax.set_xlim([fmin, fmax])
ax.set_ylim(plot_range)
if show_legend:
ax.legend()
if show:
plt.show()
return fig
def plot_gap(ax, ranges, kind, kind_desc, plot_range, plot_rsc):
"""
Plot single band gap frequency ranges as rectangles.
"""
def draw_rect(ax, x, y, rsc):
ax.fill(nm.asarray(x)[[0,1,1,0]],
nm.asarray(y)[[0,0,1,1]],
**rsc)
# Colors.
strong = plot_rsc['strong_gap']
weak = plot_rsc['weak_gap']
propagation = plot_rsc['propagation']
if kind == 'p':
draw_rect(ax, ranges[0], plot_range, propagation)
elif kind == 'w':
draw_rect(ax, ranges[0], plot_range, weak)
elif kind == 'wp':
draw_rect(ax, ranges[0], plot_range, weak)
draw_rect(ax, ranges[1], plot_range, propagation)
elif kind == 's':
draw_rect(ax, ranges[0], plot_range, strong)
elif kind == 'sw':
draw_rect(ax, ranges[0], plot_range, strong)
draw_rect(ax, ranges[1], plot_range, weak)
elif kind == 'swp':
draw_rect(ax, ranges[0], plot_range, strong)
draw_rect(ax, ranges[1], plot_range, weak)
draw_rect(ax, ranges[2], plot_range, propagation)
elif kind == 'is':
draw_rect(ax, ranges[0], plot_range, strong)
elif kind == 'iw':
draw_rect(ax, ranges[0], plot_range, weak)
else:
raise ValueError('unknown band gap kind! (%s)' % kind)
def plot_gaps(fig_num, plot_rsc, gaps, kinds, gap_ranges, freq_range,
plot_range, show=False, clear=False, new_axes=False):
"""
Plot band gaps as rectangles.
"""
if plt is None: return
fig = plt.figure(fig_num)
if clear:
fig.clf()
if new_axes:
ax = fig.add_subplot(111)
else:
ax = fig.gca()
for ii in range(len(freq_range) - 1):
f0, f1 = freq_range[[ii, ii+1]]
gap = gaps[ii]
ranges = gap_ranges[ii]
if isinstance(gap, list):
for ig, (gmin, gmax) in enumerate(gap):
kind, kind_desc = kinds[ii][ig]
plot_gap(ax, ranges[ig], kind, kind_desc, plot_range, plot_rsc)
output(ii, gmin[0], gmax[0], '%.8f' % f0, '%.8f' % f1)
output(' -> %s\n %s' %(kind_desc, ranges[ig]))
else:
gmin, gmax = gap
kind, kind_desc = kinds[ii]
plot_gap(ax, ranges, kind, kind_desc, plot_range, plot_rsc)
output(ii, gmin[0], gmax[0], '%.8f' % f0, '%.8f' % f1)
output(' -> %s\n %s' %(kind_desc, ranges))
if new_axes:
ax.set_xlim([freq_range[0], freq_range[-1]])
ax.set_ylim(plot_range)
if show:
plt.show()
return fig
def _get_fig_name(output_dir, fig_name, key, common, fig_suffix):
"""
Construct the complete name of figure file.
"""
name = key.replace(common, '')
if name and (not name.startswith('_')):
name = '_' + name
fig_name = fig_name + name + fig_suffix
return op.join(output_dir, fig_name)
class AcousticBandGapsApp(HomogenizationApp):
"""
Application for computing acoustic band gaps.
"""
@staticmethod
def process_options(options):
"""
Application options setup. Sets default values for missing
non-compulsory options.
"""
get = options.get
default_plot_options = {'show' : True,'legend' : False,}
aux = {
'resonance' : 'eigenfrequencies',
'masked' : 'masked eigenfrequencies',
'eig_min' : r'min eig($M^*$)',
'eig_mid' : r'mid eig($M^*$)',
'eig_max' : r'max eig($M^*$)',
'x_axis' : r'$\sqrt{\lambda}$, $\omega$',
'y_axis' : r'eigenvalues of mass matrix $M^*$',
}
plot_labels = try_set_defaults(options, 'plot_labels', aux, recur=True)
aux = {
'resonance' : 'eigenfrequencies',
'masked' : 'masked eigenfrequencies',
'eig_min' : r'$\kappa$(min)',
'eig_mid' : r'$\kappa$(mid)',
'eig_max' : r'$\kappa$(max)',
'x_axis' : r'$\sqrt{\lambda}$, $\omega$',
'y_axis' : 'polarization angles',
}
plot_labels_angle = try_set_defaults(options, 'plot_labels_angle', aux)
aux = {
'resonance' : 'eigenfrequencies',
'masked' : 'masked eigenfrequencies',
'eig_min' : r'wave number (min)',
'eig_mid' : r'wave number (mid)',
'eig_max' : r'wave number (max)',
'x_axis' : r'$\sqrt{\lambda}$, $\omega$',
'y_axis' : 'wave numbers',
}
plot_labels_wave = try_set_defaults(options, 'plot_labels_wave', aux)
plot_rsc = {
'resonance' : {'linewidth' : 0.5, 'color' : 'r', 'linestyle' : '-'},
'masked' : {'linewidth' : 0.5, 'color' : 'r', 'linestyle' : ':'},
'x_axis' : {'linewidth' : 0.5, 'color' : 'k', 'linestyle' : '--'},
'eig_min' : {'linewidth' : 2.0, 'color' : (0.0, 0.0, 1.0),
'linestyle' : ':' },
'eig_mid' : {'linewidth' : 2.0, 'color' : (0.0, 0.0, 0.8),
'linestyle' : '--' },
'eig_max' : {'linewidth' : 2.0, 'color' : (0.0, 0.0, 0.6),
'linestyle' : '-' },
'strong_gap' : {'linewidth' : 0, 'facecolor' : (0.2, 0.4, 0.2)},
'weak_gap' : {'linewidth' : 0, 'facecolor' : (0.6, 0.8, 0.6)},
'propagation' : {'linewidth' : 0, 'facecolor' : (1, 1, 1)},
'params' : {'axes.labelsize': 'x-large',
'font.size': 14,
'legend.fontsize': 'large',
'legend.loc': 'best',
'xtick.labelsize': 'large',
'ytick.labelsize': 'large',
'text.usetex': True},
}
plot_rsc = try_set_defaults(options, 'plot_rsc', plot_rsc)
return Struct(incident_wave_dir=get('incident_wave_dir', None),
plot_transform=get('plot_transform', None),
plot_transform_wave=get('plot_transform_wave', None),
plot_transform_angle=get('plot_transform_angle', None),
plot_options=get('plot_options', default_plot_options),
fig_name=get('fig_name', None),
fig_name_wave=get('fig_name_wave', None),
fig_name_angle=get('fig_name_angle', None),
fig_suffix=get('fig_suffix', '.pdf'),
plot_labels=plot_labels,
plot_labels_angle=plot_labels_angle,
plot_labels_wave=plot_labels_wave,
plot_rsc=plot_rsc)
@staticmethod
def process_options_pv(options):
"""
Application options setup for phase velocity computation. Sets default
values for missing non-compulsory options.
"""
get = options.get
incident_wave_dir=get('incident_wave_dir', None,
'missing "incident_wave_dir" in options!')
return Struct(incident_wave_dir=incident_wave_dir)
def __init__(self, conf, options, output_prefix, **kwargs):
PDESolverApp.__init__(self, conf, options, output_prefix,
init_equations=False)
self.setup_options()
if conf._filename:
output_dir = self.problem.output_dir
shutil.copyfile(conf._filename,
op.join(output_dir, op.basename(conf._filename)))
def setup_options(self):
HomogenizationApp.setup_options(self)
if self.options.phase_velocity:
process_options = AcousticBandGapsApp.process_options_pv
else:
process_options = AcousticBandGapsApp.process_options
self.app_options += process_options(self.conf.options)
def call(self):
"""
Construct and call the homogenization engine accoring to options.
"""
options = self.options
opts = self.app_options
conf = self.problem.conf
coefs_name = opts.coefs
coef_info = conf.get(opts.coefs, None,
'missing "%s" in problem description!'
% opts.coefs)
if options.detect_band_gaps:
# Compute band gaps coefficients and data.
keys = [key for key in coef_info if key.startswith('band_gaps')]
elif options.analyze_dispersion or options.phase_velocity:
# Insert incident wave direction to coefficients that need it.
for key, val in six.iteritems(coef_info):
coef_opts = val.get('options', None)
if coef_opts is None: continue
if (('incident_wave_dir' in coef_opts)
and (coef_opts['incident_wave_dir'] is None)):
coef_opts['incident_wave_dir'] = opts.incident_wave_dir
if options.analyze_dispersion:
# Compute dispersion coefficients and data.
keys = [key for key in coef_info
if key.startswith('dispersion')
or key.startswith('polarization_angles')]
else:
# Compute phase velocity and its requirements.
keys = [key for key in coef_info
if key.startswith('phase_velocity')]
else:
# Compute only the eigenvalue problems.
names = [req for req in conf.get(opts.requirements, [''])
if req.startswith('evp')]
coefs = {'dummy' : {'requires' : names,
'class' : CoefDummy,}}
conf.coefs_dummy = coefs
coefs_name = 'coefs_dummy'
keys = ['dummy']
he_options = Struct(coefs=coefs_name, requirements=opts.requirements,
compute_only=keys,
post_process_hook=self.post_process_hook,
multiprocessing=False)
volumes = {}
if hasattr(opts, 'volumes') and (opts.volumes is not None):
volumes.update(opts.volumes)
elif hasattr(opts, 'volume') and (opts.volume is not None):
volumes['total'] = opts.volume
else:
volumes['total'] = 1.0
he = HomogenizationEngine(self.problem, options,
app_options=he_options,
volumes=volumes)
coefs = he()
coefs = Coefficients(**coefs.to_dict())
coefs_filename = op.join(opts.output_dir, opts.coefs_filename)
coefs.to_file_txt(coefs_filename + '.txt',
opts.tex_names,
opts.float_format)
bg_keys = [key for key in coefs.to_dict()
if key.startswith('band_gaps')
or key.startswith('dispersion')]
for ii, key in enumerate(bg_keys):
bg = coefs.get(key)
log_save_name = bg.get('log_save_name', None)
if log_save_name is not None:
filename = op.join(self.problem.output_dir, log_save_name)
bg.save_log(filename, opts.float_format, bg)
raw_log_save_name = bg.get('raw_log_save_name', None)
if raw_log_save_name is not None:
filename = op.join(self.problem.output_dir, raw_log_save_name)
save_raw_bg_logs(filename, bg.logs)
if options.plot:
if options.detect_band_gaps:
self.plot_band_gaps(coefs)
elif options.analyze_dispersion:
self.plot_dispersion(coefs)
elif options.phase_velocity:
keys = [key for key in coefs.to_dict()
if key.startswith('phase_velocity')]
for key in keys:
output('%s:' % key, coefs.get(key))
return coefs
def plot_band_gaps(self, coefs):
opts = self.app_options
bg_keys = [key for key in coefs.to_dict()
if key.startswith('band_gaps')]
plot_opts = opts.plot_options
plot_rsc = opts.plot_rsc
plt.rcParams.update(plot_rsc['params'])
for ii, key in enumerate(bg_keys):
bg = coefs.get(key)
plot_labels = opts.plot_labels.get(key, opts.plot_labels)
plot_range, teigs = transform_plot_data(bg.logs.eigs,
opts.plot_transform,
self.conf)
fig = plot_gaps(ii, plot_rsc, bg.gaps, bg.kinds, bg.gap_ranges,
bg.freq_range_margins, plot_range,
clear=True)
fig = plot_logs(ii, plot_rsc, plot_labels, bg.logs.freqs, teigs,
bg.valid[bg.eig_range],
bg.freq_range_initial,
plot_range,
show_legend=plot_opts['legend'],
new_axes=True)
plt.tight_layout()
if opts.fig_name is not None:
fig_name = _get_fig_name(self.problem.output_dir, opts.fig_name,
key, 'band_gaps', opts.fig_suffix)
fig.savefig(fig_name)
if plot_opts['show']:
plt.show()
def plot_dispersion(self, coefs):
opts = self.app_options
bg_keys = [key for key in coefs.to_dict()
if key.startswith('dispersion')]
plot_rsc = opts.plot_rsc
plot_opts = opts.plot_options
plt.rcParams.update(plot_rsc['params'])
plot_labels = opts.plot_labels_angle
for ii, key in enumerate(bg_keys):
pas_key = key.replace('dispersion', 'polarization_angles')
pas = coefs.get(pas_key)
aux = transform_plot_data(pas,
opts.plot_transform_angle,
self.conf)
plot_range, pas = aux
bg = coefs.get(key)
fig = plot_gaps(1, plot_rsc, bg.gaps, bg.kinds, bg.gap_ranges,
bg.freq_range_margins, plot_range,
clear=True)
fig = plot_logs(1, plot_rsc, plot_labels, bg.logs.freqs, pas,
bg.valid[bg.eig_range],
bg.freq_range_initial,
plot_range,
show_legend=plot_opts['legend'],
new_axes=True)
plt.tight_layout()
fig_name = opts.fig_name_angle
if fig_name is not None:
fig_name = _get_fig_name(self.problem.output_dir, fig_name,
key, 'dispersion', opts.fig_suffix)
fig.savefig(fig_name)
aux = transform_plot_data(bg.logs.eigs,
opts.plot_transform_wave,
self.conf)
plot_range, teigs = aux
plot_labels = opts.plot_labels_wave
fig = plot_gaps(2, plot_rsc, bg.gaps, bg.kinds, bg.gap_ranges,
bg.freq_range_margins, plot_range,
clear=True)
fig = plot_logs(2, plot_rsc, plot_labels, bg.logs.freqs, teigs,
bg.valid[bg.eig_range],
bg.freq_range_initial,
plot_range,
show_legend=plot_opts['legend'],
new_axes=True)
plt.tight_layout()
fig_name = opts.fig_name_wave
if fig_name is not None:
fig_name = _get_fig_name(self.problem.output_dir, fig_name,
key, 'dispersion', opts.fig_suffix)
fig.savefig(fig_name)
if plot_opts['show']:
plt.show()
| [
"sfepy.base.base.set_defaults",
"sfepy.applications.PDESolverApp.__init__",
"sfepy.base.base.output",
"sfepy.base.base.Struct",
"sfepy.homogenization.homogen_app.HomogenizationApp.setup_options",
"sfepy.base.plotutils.plt.rcParams.update",
"sfepy.homogenization.engine.HomogenizationEngine",
"sfepy.bas... | [((2230, 2249), 'sfepy.base.plotutils.plt.figure', 'plt.figure', (['fig_num'], {}), '(fig_num)\n', (2240, 2249), False, 'from sfepy.base.plotutils import plt\n'), ((3188, 3207), 'sfepy.base.plotutils.plt.figure', 'plt.figure', (['fig_num'], {}), '(fig_num)\n', (3198, 3207), False, 'from sfepy.base.plotutils import plt\n'), ((5869, 5888), 'sfepy.base.plotutils.plt.figure', 'plt.figure', (['fig_num'], {}), '(fig_num)\n', (5879, 5888), False, 'from sfepy.base.plotutils import plt\n'), ((7219, 7248), 'os.path.join', 'op.join', (['output_dir', 'fig_name'], {}), '(output_dir, fig_name)\n', (7226, 7248), True, 'import os.path as op\n'), ((1225, 1252), 'numpy.concatenate', 'nm.concatenate', (['log'], {'axis': '(0)'}), '(log, axis=0)\n', (1239, 1252), True, 'import numpy as nm\n'), ((1298, 1317), 'numpy.savez', 'nm.savez', (['fd'], {}), '(fd, **out)\n', (1306, 1317), True, 'import numpy as nm\n'), ((2844, 2854), 'sfepy.base.plotutils.plt.show', 'plt.show', ([], {}), '()\n', (2852, 2854), False, 'from sfepy.base.plotutils import plt\n'), ((4314, 4324), 'sfepy.base.plotutils.plt.show', 'plt.show', ([], {}), '()\n', (4322, 4324), False, 'from sfepy.base.plotutils import plt\n'), ((6901, 6911), 'sfepy.base.plotutils.plt.show', 'plt.show', ([], {}), '()\n', (6909, 6911), False, 'from sfepy.base.plotutils import plt\n'), ((11399, 11442), 'sfepy.base.base.Struct', 'Struct', ([], {'incident_wave_dir': 'incident_wave_dir'}), '(incident_wave_dir=incident_wave_dir)\n', (11405, 11442), False, 'from sfepy.base.base import Struct\n'), ((11516, 11595), 'sfepy.applications.PDESolverApp.__init__', 'PDESolverApp.__init__', (['self', 'conf', 'options', 'output_prefix'], {'init_equations': '(False)'}), '(self, conf, options, output_prefix, init_equations=False)\n', (11537, 11595), False, 'from sfepy.applications import PDESolverApp\n'), ((11893, 11930), 'sfepy.homogenization.homogen_app.HomogenizationApp.setup_options', 'HomogenizationApp.setup_options', (['self'], {}), '(self)\n', (11924, 11930), False, 'from sfepy.homogenization.homogen_app import HomogenizationApp\n'), ((14142, 14286), 'sfepy.base.base.Struct', 'Struct', ([], {'coefs': 'coefs_name', 'requirements': 'opts.requirements', 'compute_only': 'keys', 'post_process_hook': 'self.post_process_hook', 'multiprocessing': '(False)'}), '(coefs=coefs_name, requirements=opts.requirements, compute_only=keys,\n post_process_hook=self.post_process_hook, multiprocessing=False)\n', (14148, 14286), False, 'from sfepy.base.base import Struct\n'), ((14672, 14761), 'sfepy.homogenization.engine.HomogenizationEngine', 'HomogenizationEngine', (['self.problem', 'options'], {'app_options': 'he_options', 'volumes': 'volumes'}), '(self.problem, options, app_options=he_options, volumes\n =volumes)\n', (14692, 14761), False, 'from sfepy.homogenization.engine import HomogenizationEngine\n'), ((14921, 14966), 'os.path.join', 'op.join', (['opts.output_dir', 'opts.coefs_filename'], {}), '(opts.output_dir, opts.coefs_filename)\n', (14928, 14966), True, 'import os.path as op\n'), ((16516, 16555), 'sfepy.base.plotutils.plt.rcParams.update', 'plt.rcParams.update', (["plot_rsc['params']"], {}), "(plot_rsc['params'])\n", (16535, 16555), False, 'from sfepy.base.plotutils import plt\n'), ((17988, 18027), 'sfepy.base.plotutils.plt.rcParams.update', 'plt.rcParams.update', (["plot_rsc['params']"], {}), "(plot_rsc['params'])\n", (18007, 18027), False, 'from sfepy.base.plotutils import plt\n'), ((791, 812), 'six.iteritems', 'six.iteritems', (['values'], {}), '(values)\n', (804, 812), False, 'import six\n'), ((885, 915), 'sfepy.base.base.set_defaults', 'set_defaults', (['values', 'defaults'], {}), '(values, defaults)\n', (897, 915), False, 'from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_\n'), ((1674, 1690), 'numpy.nanmin', 'nm.nanmin', (['tdata'], {}), '(tdata)\n', (1683, 1690), True, 'import numpy as nm\n'), ((1717, 1733), 'numpy.nanmax', 'nm.nanmax', (['tdata'], {}), '(tdata)\n', (1726, 1733), True, 'import numpy as nm\n'), ((6663, 6717), 'sfepy.base.base.output', 'output', (['ii', 'gmin[0]', 'gmax[0]', "('%.8f' % f0)", "('%.8f' % f1)"], {}), "(ii, gmin[0], gmax[0], '%.8f' % f0, '%.8f' % f1)\n", (6669, 6717), False, 'from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_\n'), ((6730, 6776), 'sfepy.base.base.output', 'output', (["(' -> %s\\n %s' % (kind_desc, ranges))"], {}), "(' -> %s\\n %s' % (kind_desc, ranges))\n", (6736, 6776), False, 'from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_\n'), ((17422, 17440), 'sfepy.base.plotutils.plt.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (17438, 17440), False, 'from sfepy.base.plotutils import plt\n'), ((17722, 17732), 'sfepy.base.plotutils.plt.show', 'plt.show', ([], {}), '()\n', (17730, 17732), False, 'from sfepy.base.plotutils import plt\n'), ((18965, 18983), 'sfepy.base.plotutils.plt.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (18981, 18983), False, 'from sfepy.base.plotutils import plt\n'), ((20022, 20040), 'sfepy.base.plotutils.plt.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (20038, 20040), False, 'from sfepy.base.plotutils import plt\n'), ((20355, 20365), 'sfepy.base.plotutils.plt.show', 'plt.show', ([], {}), '()\n', (20363, 20365), False, 'from sfepy.base.plotutils import plt\n'), ((830, 857), 'sfepy.base.base.set_defaults', 'set_defaults', (['val', 'defaults'], {}), '(val, defaults)\n', (842, 857), False, 'from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_\n'), ((4529, 4542), 'numpy.asarray', 'nm.asarray', (['x'], {}), '(x)\n', (4539, 4542), True, 'import numpy as nm\n'), ((4572, 4585), 'numpy.asarray', 'nm.asarray', (['y'], {}), '(y)\n', (4582, 4585), True, 'import numpy as nm\n'), ((6375, 6429), 'sfepy.base.base.output', 'output', (['ii', 'gmin[0]', 'gmax[0]', "('%.8f' % f0)", "('%.8f' % f1)"], {}), "(ii, gmin[0], gmax[0], '%.8f' % f0, '%.8f' % f1)\n", (6381, 6429), False, 'from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_\n'), ((6446, 6496), 'sfepy.base.base.output', 'output', (["(' -> %s\\n %s' % (kind_desc, ranges[ig]))"], {}), "(' -> %s\\n %s' % (kind_desc, ranges[ig]))\n", (6452, 6496), False, 'from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_\n'), ((12932, 12956), 'six.iteritems', 'six.iteritems', (['coef_info'], {}), '(coef_info)\n', (12945, 12956), False, 'import six\n'), ((15460, 15507), 'os.path.join', 'op.join', (['self.problem.output_dir', 'log_save_name'], {}), '(self.problem.output_dir, log_save_name)\n', (15467, 15507), True, 'import os.path as op\n'), ((15709, 15760), 'os.path.join', 'op.join', (['self.problem.output_dir', 'raw_log_save_name'], {}), '(self.problem.output_dir, raw_log_save_name)\n', (15716, 15760), True, 'import os.path as op\n'), ((11825, 11852), 'os.path.basename', 'op.basename', (['conf._filename'], {}), '(conf._filename)\n', (11836, 11852), True, 'import os.path as op\n')] |
#!/usr/bin/env python
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
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
from sfepy.solvers.ls import ScipyDirect
from sfepy.solvers.nls import Newton
from sfepy.postprocess.viewer import Viewer
from sfepy.mechanics.matcoefs import stiffness_from_lame
def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0):
"""
Define a displacement depending on the y coordinate.
"""
val = shift * coors[:,1]**2
return val
helps = {
'show' : 'show the results figure',
}
def main():
from sfepy import data_dir
parser = ArgumentParser()
parser.add_argument('--version', action='version', version='%(prog)s')
parser.add_argument('-s', '--show',
action="store_true", dest='show',
default=False, help=helps['show'])
options = parser.parse_args()
mesh = Mesh.from_file(data_dir + '/meshes/2d/rectangle_tri.mesh')
domain = FEDomain('domain', mesh)
min_x, max_x = domain.get_mesh_bounding_box()[:,0]
eps = 1e-8 * (max_x - min_x)
omega = domain.create_region('Omega', 'all')
gamma1 = domain.create_region('Gamma1',
'vertices in x < %.10f' % (min_x + eps),
'facet')
gamma2 = domain.create_region('Gamma2',
'vertices in x > %.10f' % (max_x - eps),
'facet')
field = Field.from_args('fu', nm.float64, 'vector', omega,
approx_order=2)
u = FieldVariable('u', 'unknown', field)
v = FieldVariable('v', 'test', field, primary_var_name='u')
m = Material('m', D=stiffness_from_lame(dim=2, lam=1.0, mu=1.0))
f = Material('f', val=[[0.02], [0.01]])
integral = Integral('i', order=3)
t1 = Term.new('dw_lin_elastic(m.D, v, u)',
integral, omega, m=m, v=v, u=u)
t2 = Term.new('dw_volume_lvf(f.val, v)', integral, omega, f=f, v=v)
eq = Equation('balance', t1 + t2)
eqs = Equations([eq])
fix_u = EssentialBC('fix_u', gamma1, {'u.all' : 0.0})
bc_fun = Function('shift_u_fun', shift_u_fun,
extra_args={'shift' : 0.01})
shift_u = EssentialBC('shift_u', gamma2, {'u.0' : bc_fun})
ls = ScipyDirect({})
nls_status = IndexedStruct()
nls = Newton({}, lin_solver=ls, status=nls_status)
pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls)
pb.save_regions_as_groups('regions')
pb.time_update(ebcs=Conditions([fix_u, shift_u]))
vec = pb.solve()
print(nls_status)
pb.save_state('linear_elasticity.vtk', vec)
if options.show:
view = Viewer('linear_elasticity.vtk')
view(vector_mode='warp_norm', rel_scaling=2,
is_scalar_bar=True, is_wireframe=True)
if __name__ == '__main__':
main()
| [
"sfepy.discrete.conditions.EssentialBC",
"sfepy.discrete.Integral",
"sfepy.postprocess.viewer.Viewer",
"sfepy.solvers.ls.ScipyDirect",
"sfepy.discrete.Equations",
"sfepy.discrete.fem.Field.from_args",
"sfepy.discrete.Equation",
"sfepy.discrete.fem.Mesh.from_file",
"sfepy.discrete.fem.FEDomain",
"s... | [((166, 186), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (181, 186), False, 'import sys\n'), ((980, 996), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (994, 996), False, 'from argparse import ArgumentParser\n'), ((1275, 1333), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (["(data_dir + '/meshes/2d/rectangle_tri.mesh')"], {}), "(data_dir + '/meshes/2d/rectangle_tri.mesh')\n", (1289, 1333), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1347, 1371), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""domain"""', 'mesh'], {}), "('domain', mesh)\n", (1355, 1371), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1847, 1913), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""fu"""', 'nm.float64', '"""vector"""', 'omega'], {'approx_order': '(2)'}), "('fu', nm.float64, 'vector', omega, approx_order=2)\n", (1862, 1913), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1951, 1987), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""u"""', '"""unknown"""', 'field'], {}), "('u', 'unknown', field)\n", (1964, 1987), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((1996, 2051), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""v"""', '"""test"""', 'field'], {'primary_var_name': '"""u"""'}), "('v', 'test', field, primary_var_name='u')\n", (2009, 2051), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2130, 2165), 'sfepy.discrete.Material', 'Material', (['"""f"""'], {'val': '[[0.02], [0.01]]'}), "('f', val=[[0.02], [0.01]])\n", (2138, 2165), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2182, 2204), 'sfepy.discrete.Integral', 'Integral', (['"""i"""'], {'order': '(3)'}), "('i', order=3)\n", (2190, 2204), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2215, 2284), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_lin_elastic(m.D, v, u)"""', 'integral', 'omega'], {'m': 'm', 'v': 'v', 'u': 'u'}), "('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u)\n", (2223, 2284), False, 'from sfepy.terms import Term\n'), ((2312, 2374), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_volume_lvf(f.val, v)"""', 'integral', 'omega'], {'f': 'f', 'v': 'v'}), "('dw_volume_lvf(f.val, v)', integral, omega, f=f, v=v)\n", (2320, 2374), False, 'from sfepy.terms import Term\n'), ((2384, 2412), 'sfepy.discrete.Equation', 'Equation', (['"""balance"""', '(t1 + t2)'], {}), "('balance', t1 + t2)\n", (2392, 2412), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2423, 2438), 'sfepy.discrete.Equations', 'Equations', (['[eq]'], {}), '([eq])\n', (2432, 2438), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2452, 2496), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""fix_u"""', 'gamma1', "{'u.all': 0.0}"], {}), "('fix_u', gamma1, {'u.all': 0.0})\n", (2463, 2496), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((2512, 2576), 'sfepy.discrete.Function', 'Function', (['"""shift_u_fun"""', 'shift_u_fun'], {'extra_args': "{'shift': 0.01}"}), "('shift_u_fun', shift_u_fun, extra_args={'shift': 0.01})\n", (2520, 2576), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2614, 2661), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""shift_u"""', 'gamma2', "{'u.0': bc_fun}"], {}), "('shift_u', gamma2, {'u.0': bc_fun})\n", (2625, 2661), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((2673, 2688), 'sfepy.solvers.ls.ScipyDirect', 'ScipyDirect', (['{}'], {}), '({})\n', (2684, 2688), False, 'from sfepy.solvers.ls import ScipyDirect\n'), ((2707, 2722), 'sfepy.base.base.IndexedStruct', 'IndexedStruct', ([], {}), '()\n', (2720, 2722), False, 'from sfepy.base.base import IndexedStruct\n'), ((2733, 2777), 'sfepy.solvers.nls.Newton', 'Newton', (['{}'], {'lin_solver': 'ls', 'status': 'nls_status'}), '({}, lin_solver=ls, status=nls_status)\n', (2739, 2777), False, 'from sfepy.solvers.nls import Newton\n'), ((2788, 2840), 'sfepy.discrete.Problem', 'Problem', (['"""elasticity"""'], {'equations': 'eqs', 'nls': 'nls', 'ls': 'ls'}), "('elasticity', equations=eqs, nls=nls, ls=ls)\n", (2795, 2840), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((3067, 3098), 'sfepy.postprocess.viewer.Viewer', 'Viewer', (['"""linear_elasticity.vtk"""'], {}), "('linear_elasticity.vtk')\n", (3073, 3098), False, 'from sfepy.postprocess.viewer import Viewer\n'), ((2077, 2120), 'sfepy.mechanics.matcoefs.stiffness_from_lame', 'stiffness_from_lame', ([], {'dim': '(2)', 'lam': '(1.0)', 'mu': '(1.0)'}), '(dim=2, lam=1.0, mu=1.0)\n', (2096, 2120), False, 'from sfepy.mechanics.matcoefs import stiffness_from_lame\n'), ((2907, 2935), 'sfepy.discrete.conditions.Conditions', 'Conditions', (['[fix_u, shift_u]'], {}), '([fix_u, shift_u])\n', (2917, 2935), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n')] |
from __future__ import absolute_import
import numpy as nm
import numpy.linalg as nla
from sfepy.base.base import output, get_default, pause, Struct
from sfepy.base.log import Log, get_logging_conf
from sfepy.base.timing import Timer
from sfepy.solvers.solvers import OptimizationSolver
import scipy.optimize as sopt
import scipy.optimize.linesearch as linesearch
import six
from six.moves import range
def conv_test(conf, it, of, of0, ofg_norm=None):
"""
Returns
-------
flag : int
* -1 ... continue
* 0 ... small OF -> stop
* 1 ... i_max reached -> stop
* 2 ... small OFG -> stop
* 3 ... small relative decrase of OF
"""
status = -1
output('opt: iter: %d, of: %e (||ofg||: %e)' % (it, of, ofg_norm))
if (abs(of) < conf.eps_of):
status = 0
elif ofg_norm and (ofg_norm < conf.eps_ofg):
status = 2
elif (it > 0) and (abs(of0 - of) < (conf.eps_rd * abs(of0))):
status = 3
if (status == -1) and (it >= conf.i_max):
status = 1
return status
def wrap_function(function, args):
ncalls = [0]
times = []
timer = Timer()
def function_wrapper(x):
ncalls[0] += 1
timer.start()
out = function(x, *args)
times.append(timer.stop())
return out
return ncalls, times, function_wrapper
def check_gradient(xit, aofg, fn_of, delta, check):
dofg = nm.zeros_like(aofg)
xd = xit.copy()
for ii in range(xit.shape[0]):
xd[ii] = xit[ii] + delta
ofp = fn_of(xd)
xd[ii] = xit[ii] - delta
ofm = fn_of(xd)
xd[ii] = xit[ii]
dofg[ii] = 0.5 * (ofp - ofm) / delta
output('**********', ii, aofg[ii], dofg[ii])
diff = abs(aofg - dofg)
aux = nm.concatenate((aofg[:,nm.newaxis], dofg[:,nm.newaxis],
diff[:,nm.newaxis]), 1)
output(aux)
output(nla.norm(diff, nm.Inf))
aofg.tofile('aofg.txt', ' ')
dofg.tofile('dofg.txt', ' ')
diff.tofile('diff.txt', ' ')
if check == 2:
import pylab
pylab.plot(aofg)
pylab.plot(dofg)
pylab.legend(('analytical', 'finite difference'))
pylab.show()
pause('gradient checking done')
class FMinSteepestDescent(OptimizationSolver):
"""
Steepest descent optimization solver.
"""
name = 'opt.fmin_sd'
_parameters = [
('i_max', 'int', 10, False,
'The maximum number of iterations.'),
('eps_rd', 'float', 1e-5, False,
'The relative delta of the objective function.'),
('eps_of', 'float', 1e-4, False,
'The tolerance for the objective function.'),
('eps_ofg', 'float', 1e-8, False,
'The tolerance for the objective function gradient.'),
('norm', 'numpy norm', nm.Inf, False,
'The norm to be used.'),
('ls', 'bool', True, False,
'If True, use a line-search.'),
('ls_method', "{'backtracking', 'full'}", 'backtracking', False,
'The line-search method.'),
('ls_on', 'float', 0.99999, False,
"""Start the backtracking line-search by reducing the step, if
:math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""),
('ls0', '0.0 < float < 1.0', 1.0, False,
'The initial step.'),
('ls_red', '0.0 < float < 1.0', 0.5, False,
'The step reduction factor in case of correct residual assembling.'),
('ls_red_warp', '0.0 < float < 1.0', 0.1, False,
"""The step reduction factor in case of failed residual assembling
(e.g. the "warp violation" error caused by a negative volume
element resulting from too large deformations)."""),
('ls_min', '0.0 < float < 1.0', 1e-5, False,
'The minimum step reduction factor.'),
('check', '0, 1 or 2', 0, False,
"""If >= 1, check the tangent matrix using finite differences. If 2,
plot the resulting sparsity patterns."""),
('delta', 'float', 1e-6, False,
r"""If `check >= 1`, the finite difference matrix is taken as
:math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2
\delta}`."""),
('output', 'function', None, False,
"""If given, use it instead of :func:`output()
<sfepy.base.base.output()>` function."""),
('yscales', 'list of str', ['linear', 'log', 'log', 'linear'], False,
'The list of four convergence log subplot scales.'),
('log', 'dict or None', None, False,
"""If not None, log the convergence according to the configuration in
the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``.
Each of the dict items can be None."""),
]
def __init__(self, conf, **kwargs):
OptimizationSolver.__init__(self, conf, **kwargs)
conf = self.conf
log = get_logging_conf(conf)
conf.log = log = Struct(name='log_conf', **log)
conf.is_any_log = (log.text is not None) or (log.plot is not None)
if conf.is_any_log:
self.log = Log([[r'$||\Psi||$'], [r'$||\nabla \Psi||$'],
[r'$\alpha$'], ['iteration']],
xlabels=['', '', 'all iterations', 'all iterations'],
yscales=conf.yscales,
is_plot=conf.log.plot is not None,
log_filename=conf.log.text,
formats=[['%.8e'], ['%.3e'], ['%.3e'], ['%d']])
else:
self.log = None
def __call__(self, x0, conf=None, obj_fun=None, obj_fun_grad=None,
status=None, obj_args=None):
conf = get_default(conf, self.conf)
obj_fun = get_default(obj_fun, self.obj_fun)
obj_fun_grad = get_default(obj_fun_grad, self.obj_fun_grad)
status = get_default(status, self.status)
obj_args = get_default(obj_args, self.obj_args)
if conf.output:
globals()['output'] = conf.output
output('entering optimization loop...')
nc_of, tt_of, fn_of = wrap_function(obj_fun, obj_args)
nc_ofg, tt_ofg, fn_ofg = wrap_function(obj_fun_grad, obj_args)
timer = Timer()
time_stats = {'of' : tt_of, 'ofg': tt_ofg, 'check' : []}
ofg = None
it = 0
xit = x0.copy()
while 1:
of = fn_of(xit)
if it == 0:
of0 = ofit0 = of_prev = of
of_prev_prev = of + 5000.0
if ofg is None:
ofg = fn_ofg(xit)
if conf.check:
timer.start()
check_gradient(xit, ofg, fn_of, conf.delta, conf.check)
time_stats['check'].append(timer.stop())
ofg_norm = nla.norm(ofg, conf.norm)
ret = conv_test(conf, it, of, ofit0, ofg_norm)
if ret >= 0:
break
ofit0 = of
##
# Backtrack (on errors).
alpha = conf.ls0
can_ls = True
while 1:
xit2 = xit - alpha * ofg
aux = fn_of(xit2)
if self.log is not None:
self.log(of, ofg_norm, alpha, it)
if aux is None:
alpha *= conf.ls_red_warp
can_ls = False
output('warp: reducing step (%f)' % alpha)
elif conf.ls and conf.ls_method == 'backtracking':
if aux < of * conf.ls_on: break
alpha *= conf.ls_red
output('backtracking: reducing step (%f)' % alpha)
else:
of_prev_prev = of_prev
of_prev = aux
break
if alpha < conf.ls_min:
if aux is None:
raise RuntimeError('giving up...')
output('linesearch failed, continuing anyway')
break
# These values are modified by the line search, even if it fails
of_prev_bak = of_prev
of_prev_prev_bak = of_prev_prev
if conf.ls and can_ls and conf.ls_method == 'full':
output('full linesearch...')
alpha, fc, gc, of_prev, of_prev_prev, ofg1 = \
linesearch.line_search(fn_of,fn_ofg,xit,
-ofg,ofg,of_prev,of_prev_prev,
c2=0.4)
if alpha is None: # line search failed -- use different one.
alpha, fc, gc, of_prev, of_prev_prev, ofg1 = \
sopt.line_search(fn_of,fn_ofg,xit,
-ofg,ofg,of_prev_bak,
of_prev_prev_bak)
if alpha is None or alpha == 0:
# This line search also failed to find a better
# solution.
ret = 3
break
output(' -> alpha: %.8e' % alpha)
else:
if conf.ls_method == 'full':
output('full linesearch off (%s and %s)'
% (conf.ls, can_ls))
ofg1 = None
if self.log is not None:
self.log.plot_vlines(color='g', linewidth=0.5)
xit = xit - alpha * ofg
if ofg1 is None:
ofg = None
else:
ofg = ofg1.copy()
for key, val in six.iteritems(time_stats):
if len(val):
output('%10s: %7.2f [s]' % (key, val[-1]))
it = it + 1
output('status: %d' % ret)
output('initial value: %.8e' % of0)
output('current value: %.8e' % of)
output('iterations: %d' % it)
output('function evaluations: %d in %.2f [s]'
% (nc_of[0], nm.sum(time_stats['of'])))
output('gradient evaluations: %d in %.2f [s]'
% (nc_ofg[0], nm.sum(time_stats['ofg'])))
if self.log is not None:
self.log(of, ofg_norm, alpha, it)
if conf.log.plot is not None:
self.log(save_figure=conf.log.plot, finished=True)
else:
self.log(finished=True)
if status is not None:
status['log'] = self.log
status['status'] = status
status['of0'] = of0
status['of'] = of
status['it'] = it
status['nc_of'] = nc_of[0]
status['nc_ofg'] = nc_ofg[0]
status['time_stats'] = time_stats
return xit
class ScipyFMinSolver(OptimizationSolver):
"""
Interface to SciPy optimization solvers scipy.optimize.fmin_*.
"""
name = 'nls.scipy_fmin_like'
_i_max_name = {
'fmin' : 'maxiter',
'fmin_bfgs' : 'maxiter',
'fmin_cg' : 'maxiter',
'fmin_cobyla' : 'maxfun',
'fmin_l_bfgs_b' : 'maxfun',
'fmin_ncg' : 'maxiter',
'fmin_powell' : 'maxiter',
'fmin_slsqp' : 'iter',
'fmin_tnc' : 'maxfun',
}
_has_grad = ('fmin_bfgs', 'fmin_cg', 'fmin_l_bfgs_b', 'fmin_ncg',
'fmin_slsqp', 'fmin_tnc')
_parameters = [
('method',
'{%s}' % ', '.join(sorted(repr(ii) for ii in _i_max_name.keys())),
'fmin', False,
'The actual optimization method to use.'),
('i_max', 'int', 10, False,
'The maximum number of iterations.'),
('*', '*', None, False,
'Additional parameters supported by the method.'),
]
def __init__(self, conf, **kwargs):
OptimizationSolver.__init__(self, conf, **kwargs)
self.set_method(self.conf)
def set_method(self, conf):
import scipy.optimize as so
try:
solver = getattr(so, conf.method)
except AttributeError:
raise ValueError('scipy solver %s does not exist!' % conf.method)
self.solver = solver
def __call__(self, x0, conf=None, obj_fun=None, obj_fun_grad=None,
status=None, obj_args=None):
import inspect
if conf is not None:
self.set_method(conf)
else:
conf = self.conf
obj_fun = get_default(obj_fun, self.obj_fun)
obj_fun_grad = get_default(obj_fun_grad, self.obj_fun_grad)
status = get_default(status, self.status)
obj_args = get_default(obj_args, self.obj_args)
timer = Timer(start=True)
kwargs = {self._i_max_name[conf.method] : conf.i_max,
'args' : obj_args}
if conf.method in self._has_grad:
kwargs['fprime'] = obj_fun_grad
if 'disp' in inspect.getargspec(self.solver)[0]:
kwargs['disp'] = conf.verbose
kwargs.update(self.build_solver_kwargs(conf))
out = self.solver(obj_fun, x0, **kwargs)
if status is not None:
status['time_stats'] = timer.stop()
return out
| [
"sfepy.base.timing.Timer",
"sfepy.base.base.Struct",
"sfepy.base.base.get_default",
"sfepy.base.log.Log",
"sfepy.base.base.output",
"sfepy.solvers.solvers.OptimizationSolver.__init__",
"sfepy.base.log.get_logging_conf",
"sfepy.base.base.pause"
] | [((712, 778), 'sfepy.base.base.output', 'output', (["('opt: iter: %d, of: %e (||ofg||: %e)' % (it, of, ofg_norm))"], {}), "('opt: iter: %d, of: %e (||ofg||: %e)' % (it, of, ofg_norm))\n", (718, 778), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((1149, 1156), 'sfepy.base.timing.Timer', 'Timer', ([], {}), '()\n', (1154, 1156), False, 'from sfepy.base.timing import Timer\n'), ((1426, 1445), 'numpy.zeros_like', 'nm.zeros_like', (['aofg'], {}), '(aofg)\n', (1439, 1445), True, 'import numpy as nm\n'), ((1480, 1499), 'six.moves.range', 'range', (['xit.shape[0]'], {}), '(xit.shape[0])\n', (1485, 1499), False, 'from six.moves import range\n'), ((1781, 1868), 'numpy.concatenate', 'nm.concatenate', (['(aofg[:, nm.newaxis], dofg[:, nm.newaxis], diff[:, nm.newaxis])', '(1)'], {}), '((aofg[:, nm.newaxis], dofg[:, nm.newaxis], diff[:, nm.\n newaxis]), 1)\n', (1795, 1868), True, 'import numpy as nm\n'), ((1891, 1902), 'sfepy.base.base.output', 'output', (['aux'], {}), '(aux)\n', (1897, 1902), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((2210, 2241), 'sfepy.base.base.pause', 'pause', (['"""gradient checking done"""'], {}), "('gradient checking done')\n", (2215, 2241), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((1697, 1741), 'sfepy.base.base.output', 'output', (['"""**********"""', 'ii', 'aofg[ii]', 'dofg[ii]'], {}), "('**********', ii, aofg[ii], dofg[ii])\n", (1703, 1741), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((1914, 1936), 'numpy.linalg.norm', 'nla.norm', (['diff', 'nm.Inf'], {}), '(diff, nm.Inf)\n', (1922, 1936), True, 'import numpy.linalg as nla\n'), ((2085, 2101), 'pylab.plot', 'pylab.plot', (['aofg'], {}), '(aofg)\n', (2095, 2101), False, 'import pylab\n'), ((2110, 2126), 'pylab.plot', 'pylab.plot', (['dofg'], {}), '(dofg)\n', (2120, 2126), False, 'import pylab\n'), ((2135, 2184), 'pylab.legend', 'pylab.legend', (["('analytical', 'finite difference')"], {}), "(('analytical', 'finite difference'))\n", (2147, 2184), False, 'import pylab\n'), ((2193, 2205), 'pylab.show', 'pylab.show', ([], {}), '()\n', (2203, 2205), False, 'import pylab\n'), ((4814, 4863), 'sfepy.solvers.solvers.OptimizationSolver.__init__', 'OptimizationSolver.__init__', (['self', 'conf'], {}), '(self, conf, **kwargs)\n', (4841, 4863), False, 'from sfepy.solvers.solvers import OptimizationSolver\n'), ((4905, 4927), 'sfepy.base.log.get_logging_conf', 'get_logging_conf', (['conf'], {}), '(conf)\n', (4921, 4927), False, 'from sfepy.base.log import Log, get_logging_conf\n'), ((4953, 4983), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""log_conf"""'}), "(name='log_conf', **log)\n", (4959, 4983), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((5713, 5741), 'sfepy.base.base.get_default', 'get_default', (['conf', 'self.conf'], {}), '(conf, self.conf)\n', (5724, 5741), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((5760, 5794), 'sfepy.base.base.get_default', 'get_default', (['obj_fun', 'self.obj_fun'], {}), '(obj_fun, self.obj_fun)\n', (5771, 5794), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((5818, 5862), 'sfepy.base.base.get_default', 'get_default', (['obj_fun_grad', 'self.obj_fun_grad'], {}), '(obj_fun_grad, self.obj_fun_grad)\n', (5829, 5862), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((5880, 5912), 'sfepy.base.base.get_default', 'get_default', (['status', 'self.status'], {}), '(status, self.status)\n', (5891, 5912), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((5932, 5968), 'sfepy.base.base.get_default', 'get_default', (['obj_args', 'self.obj_args'], {}), '(obj_args, self.obj_args)\n', (5943, 5968), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((6049, 6088), 'sfepy.base.base.output', 'output', (['"""entering optimization loop..."""'], {}), "('entering optimization loop...')\n", (6055, 6088), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((6241, 6248), 'sfepy.base.timing.Timer', 'Timer', ([], {}), '()\n', (6246, 6248), False, 'from sfepy.base.timing import Timer\n'), ((9763, 9803), 'sfepy.base.base.output', 'output', (["('status: %d' % ret)"], {}), "('status: %d' % ret)\n", (9769, 9803), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((9812, 9854), 'sfepy.base.base.output', 'output', (["('initial value: %.8e' % of0)"], {}), "('initial value: %.8e' % of0)\n", (9818, 9854), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((9863, 9904), 'sfepy.base.base.output', 'output', (["('current value: %.8e' % of)"], {}), "('current value: %.8e' % of)\n", (9869, 9904), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((9913, 9952), 'sfepy.base.base.output', 'output', (["('iterations: %d' % it)"], {}), "('iterations: %d' % it)\n", (9919, 9952), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((11781, 11830), 'sfepy.solvers.solvers.OptimizationSolver.__init__', 'OptimizationSolver.__init__', (['self', 'conf'], {}), '(self, conf, **kwargs)\n', (11808, 11830), False, 'from sfepy.solvers.solvers import OptimizationSolver\n'), ((12402, 12436), 'sfepy.base.base.get_default', 'get_default', (['obj_fun', 'self.obj_fun'], {}), '(obj_fun, self.obj_fun)\n', (12413, 12436), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((12460, 12504), 'sfepy.base.base.get_default', 'get_default', (['obj_fun_grad', 'self.obj_fun_grad'], {}), '(obj_fun_grad, self.obj_fun_grad)\n', (12471, 12504), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((12522, 12554), 'sfepy.base.base.get_default', 'get_default', (['status', 'self.status'], {}), '(status, self.status)\n', (12533, 12554), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((12574, 12610), 'sfepy.base.base.get_default', 'get_default', (['obj_args', 'self.obj_args'], {}), '(obj_args, self.obj_args)\n', (12585, 12610), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((12628, 12645), 'sfepy.base.timing.Timer', 'Timer', ([], {'start': '(True)'}), '(start=True)\n', (12633, 12645), False, 'from sfepy.base.timing import Timer\n'), ((5111, 5389), 'sfepy.base.log.Log', 'Log', (["[['$||\\\\Psi||$'], ['$||\\\\nabla \\\\Psi||$'], ['$\\\\alpha$'], ['iteration']]"], {'xlabels': "['', '', 'all iterations', 'all iterations']", 'yscales': 'conf.yscales', 'is_plot': '(conf.log.plot is not None)', 'log_filename': 'conf.log.text', 'formats': "[['%.8e'], ['%.3e'], ['%.3e'], ['%d']]"}), "([['$||\\\\Psi||$'], ['$||\\\\nabla \\\\Psi||$'], ['$\\\\alpha$'], ['iteration']\n ], xlabels=['', '', 'all iterations', 'all iterations'], yscales=conf.\n yscales, is_plot=conf.log.plot is not None, log_filename=conf.log.text,\n formats=[['%.8e'], ['%.3e'], ['%.3e'], ['%d']])\n", (5114, 5389), False, 'from sfepy.base.log import Log, get_logging_conf\n'), ((6805, 6829), 'numpy.linalg.norm', 'nla.norm', (['ofg', 'conf.norm'], {}), '(ofg, conf.norm)\n', (6813, 6829), True, 'import numpy.linalg as nla\n'), ((9610, 9635), 'six.iteritems', 'six.iteritems', (['time_stats'], {}), '(time_stats)\n', (9623, 9635), False, 'import six\n'), ((8259, 8287), 'sfepy.base.base.output', 'output', (['"""full linesearch..."""'], {}), "('full linesearch...')\n", (8265, 8287), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((8371, 8459), 'scipy.optimize.linesearch.line_search', 'linesearch.line_search', (['fn_of', 'fn_ofg', 'xit', '(-ofg)', 'ofg', 'of_prev', 'of_prev_prev'], {'c2': '(0.4)'}), '(fn_of, fn_ofg, xit, -ofg, ofg, of_prev, of_prev_prev,\n c2=0.4)\n', (8393, 8459), True, 'import scipy.optimize.linesearch as linesearch\n'), ((9101, 9134), 'sfepy.base.base.output', 'output', (["(' -> alpha: %.8e' % alpha)"], {}), "(' -> alpha: %.8e' % alpha)\n", (9107, 9134), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((12855, 12886), 'inspect.getargspec', 'inspect.getargspec', (['self.solver'], {}), '(self.solver)\n', (12873, 12886), False, 'import inspect\n'), ((7394, 7436), 'sfepy.base.base.output', 'output', (["('warp: reducing step (%f)' % alpha)"], {}), "('warp: reducing step (%f)' % alpha)\n", (7400, 7436), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((7949, 7995), 'sfepy.base.base.output', 'output', (['"""linesearch failed, continuing anyway"""'], {}), "('linesearch failed, continuing anyway')\n", (7955, 7995), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((8706, 8784), 'scipy.optimize.line_search', 'sopt.line_search', (['fn_of', 'fn_ofg', 'xit', '(-ofg)', 'ofg', 'of_prev_bak', 'of_prev_prev_bak'], {}), '(fn_of, fn_ofg, xit, -ofg, ofg, of_prev_bak, of_prev_prev_bak)\n', (8722, 8784), True, 'import scipy.optimize as sopt\n'), ((9218, 9279), 'sfepy.base.base.output', 'output', (["('full linesearch off (%s and %s)' % (conf.ls, can_ls))"], {}), "('full linesearch off (%s and %s)' % (conf.ls, can_ls))\n", (9224, 9279), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((9686, 9728), 'sfepy.base.base.output', 'output', (["('%10s: %7.2f [s]' % (key, val[-1]))"], {}), "('%10s: %7.2f [s]' % (key, val[-1]))\n", (9692, 9728), False, 'from sfepy.base.base import output, get_default, pause, Struct\n'), ((10035, 10059), 'numpy.sum', 'nm.sum', (["time_stats['of']"], {}), "(time_stats['of'])\n", (10041, 10059), True, 'import numpy as nm\n'), ((10145, 10170), 'numpy.sum', 'nm.sum', (["time_stats['ofg']"], {}), "(time_stats['ofg'])\n", (10151, 10170), True, 'import numpy as nm\n'), ((7617, 7667), 'sfepy.base.base.output', 'output', (["('backtracking: reducing step (%f)' % alpha)"], {}), "('backtracking: reducing step (%f)' % alpha)\n", (7623, 7667), False, 'from sfepy.base.base import output, get_default, pause, Struct\n')] |
from sfepy.base.base import Struct
from sfepy.solvers import Solver
class MassOperator(Struct):
"""
Encapsulation of action and inverse action of a mass matrix operator
:math:`M`.
"""
def __init__(self, problem, options):
self.mtx_mass = problem.evaluate(options.mass, mode='weak',
auto_init=True, dw_mode='matrix')
if options.lumped:
raise NotImplementedError
else:
# Initialize solvers (and possibly presolve the matrix).
self.ls = Solver.any_from_conf(problem.ls_conf, mtx=self.mtx_mass,
presolve=True)
def action(self, vec):
"""
Action of mass matrix operator on a vector: :math:`M x`.
"""
return self.mtx_mass * vec
def inverse_action(self, vec):
"""
Inverse action of mass matrix operator on a vector: :math:`M^{-1} x`.
"""
return self.ls(vec)
| [
"sfepy.solvers.Solver.any_from_conf"
] | [((559, 630), 'sfepy.solvers.Solver.any_from_conf', 'Solver.any_from_conf', (['problem.ls_conf'], {'mtx': 'self.mtx_mass', 'presolve': '(True)'}), '(problem.ls_conf, mtx=self.mtx_mass, presolve=True)\n', (579, 630), False, 'from sfepy.solvers import Solver\n')] |
"""
Module for handling state variables.
"""
import numpy as nm
from sfepy.base.base import Struct
class State(Struct):
"""
Class holding/manipulating the state variables and corresponding DOF
vectors.
Manipulating the state class changes the underlying variables, and
hence also the corresponding equations/terms (if any).
Notes
-----
This class allows working with LCBC conditions in time-dependent
problems, as it keeps track of the reduced DOF vector that cannot
be reconstructed from the full DOF vector by using the usual
`variables.strip_state_vector()`.
"""
@staticmethod
def from_variables(variables):
"""
Create a State instance for the given variables.
The DOF vector is created using the DOF data in `variables`.
Parameters
----------
variables : Variables instance
The variables.
"""
parts = variables.get_state_parts()
vec = variables.create_state_vector()
for key, part in parts.iteritems():
indx = variables.get_indx(key)
vec[indx] = part
return State(variables, vec)
def __init__(self, variables, vec=None, preserve_caches=False):
"""
Create a State instance for the given variables.
Parameters
----------
variables : Variables instance
The variables.
vec : array, optional
The (initial) DOF vector corresponding to the variables.
preserve_caches : bool
If True, do not invalidate evaluate caches of variables.
"""
Struct.__init__(self, variables=variables, vec=vec, r_vec=None)
if self.vec is None:
self.vec = variables.create_state_vector()
self.variables.set_data(self.vec, preserve_caches=preserve_caches)
def copy(self, deep=False, preserve_caches=False):
"""
Copy the state. By default, the new state contains the same
variables, and creates new DOF vectors. If `deep` is True, also
the DOF vectors are copied.
Parameters
----------
deep : bool
If True, make a copy of the DOF vectors.
preserve_caches : bool
If True, do not invalidate evaluate caches of variables.
"""
if deep:
other = State(self.variables, self.vec.copy(), preserve_caches=True)
if self.r_vec is not None:
other.r_vec = self.r_vec.copy()
else:
other = State(self.variables, preserve_caches=True)
return other
def fill(self, value):
"""
Fill the DOF vector with given value.
"""
if self.r_vec is not None:
self.r_vec.fill(value)
self.vec.fill(value)
def init_history(self):
"""
Initialize variables with history.
"""
self.variables.init_history()
def apply_ebc(self, force_values=None):
"""
Apply essential (Dirichlet) boundary conditions to the state.
"""
self.variables.apply_ebc(self.vec, force_values=force_values)
def has_ebc(self):
"""
Test whether the essential (Dirichlet) boundary conditions have
been applied to the DOF vector.
"""
return self.variables.has_ebc(self.vec)
def apply_ic(self, force_values=None):
"""
Apply initial conditions to the state.
"""
if self.r_vec is not None:
raise ValueError('cannot re-apply initial conditions with LCBCs!')
self.variables.apply_ic(self.vec, force_values=force_values)
def get_reduced(self, follow_epbc=False):
"""
Get the reduced DOF vector, with EBC and PBC DOFs removed.
"""
strip = self.variables.strip_state_vector
if self.variables.has_lcbc:
if self.r_vec is None:
r_vec = strip(self.vec, follow_epbc=follow_epbc)
r_vec = self.variables.op_lcbc.T * r_vec
else:
r_vec = self.r_vec
else:
r_vec = strip(self.vec, follow_epbc=follow_epbc)
return r_vec
def set_reduced(self, r_vec, preserve_caches=False):
"""
Set the reduced DOF vector, with EBC and PBC DOFs removed.
Parameters
----------
r_vec : array
The reduced DOF vector corresponding to the variables.
preserve_caches : bool
If True, do not invalidate evaluate caches of variables.
"""
self.vec = self.variables.make_full_vec(r_vec)
if self.variables.has_lcbc:
self.r_vec = r_vec
self.variables.set_data(self.vec, preserve_caches=preserve_caches)
def set_full(self, vec, var_name=None, force=False):
"""
Set the full DOF vector (including EBC and PBC DOFs). If
`var_name` is given, set only the DOF sub-vector corresponding
to the given variable. If `force` is True, setting variables
with LCBC DOFs is allowed.
"""
if var_name is None:
if self.variables.has_lcbc and not force:
raise ValueError('cannot set full DOF vector with LCBCs!')
self.vec = vec
self.variables.set_data(self.vec)
else:
var = self.variables[var_name]
if var.has_lcbc and not force:
raise ValueError('cannot set full DOF vector with LCBCs!')
self.variables.set_state_part(self.vec, vec, var_name)
var.set_data(self.vec, self.variables.get_indx(var_name))
def __call__(self, var_name=None):
"""
Get the full DOF vector (including EBC and PBC DOFs). If
`var_name` is given, return only the DOF vector corresponding to
the given variable.
"""
if var_name is None:
out = self.vec
else:
out = self.variables.get_state_part_view(self.vec, var_name)
return out
def set_parts(self, parts, force=False):
"""
Set parts of the DOF vector corresponding to individual state
variables.
Parameters
----------
parts : dict
The dictionary of the DOF vector parts.
"""
if self.variables.has_lcbc and not force:
raise ValueError('cannot set full DOF vector with LCBCs!')
self.variables.set_data(parts)
for key, part in parts.iteritems():
indx = self.variables.get_indx(key)
self.vec[indx] = part
def get_parts(self):
"""
Return parts of the DOF vector corresponding to individual state
variables.
Returns
-------
out : dict
The dictionary of the DOF vector parts.
"""
return self.variables.get_state_parts(self.vec)
def create_output_dict(self, fill_value=None, var_info=None,
extend=True, linearization=None):
"""
Transforms state to an output dictionary, that can be
passed as 'out' kwarg to Mesh.write().
Then the dictionary entries are formed by components of the
state vector corresponding to unknown variables according to
kind of linearization given by `linearization`.
Examples
--------
>>> out = state.create_output_dict()
>>> problem.save_state('file.vtk', out=out)
"""
return self.variables.state_to_output(self.vec, fill_value,
var_info, extend,
linearization=linearization)
def get_weighted_norm(self, vec, weights=None, return_weights=False):
"""
Return the weighted norm of DOF vector `vec`.
By default, each component of `vec` is weighted by the 1/norm of the
corresponding state part, or 1 if the norm is zero. Alternatively, the
weights can be provided explicitly using `weights` argument.
Parameters
----------
vec : array
The DOF vector corresponding to the variables.
weights : dict, optional
If given, the weights are used instead of the norms of the state
parts. Keys of the dictionary must be equal to the names of
variables comprising the DOF vector.
return_weights: bool
If True, return also the used weights.
Returns
-------
norm : float
The weighted norm.
weights : dict, optional
If `return_weights` is True, the used weights.
Examples
--------
>>> err = state0.get_weighted_norm(state() - state0())
"""
if weights is None:
parts = self.get_parts()
weights = {}
for key, part in parts.iteritems():
pnorm = nm.linalg.norm(part)
if pnorm < 10.0 * nm.finfo(nm.float64).eps:
pnorm = 1.0
weights[key] = 1.0 / pnorm
else:
if set(weights.keys()) != self.variables.state:
raise ValueError('weights keys have to be in %s!'
% self.variables.state)
wvec = vec.copy()
for key in weights.iterkeys():
indx = self.variables.get_indx(key)
wvec[indx] *= weights[key]
norm = nm.linalg.norm(wvec)
if return_weights:
return norm, weights
else:
return norm
| [
"sfepy.base.base.Struct.__init__"
] | [((1635, 1698), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'variables': 'variables', 'vec': 'vec', 'r_vec': 'None'}), '(self, variables=variables, vec=vec, r_vec=None)\n', (1650, 1698), False, 'from sfepy.base.base import Struct\n'), ((9457, 9477), 'numpy.linalg.norm', 'nm.linalg.norm', (['wvec'], {}), '(wvec)\n', (9471, 9477), True, 'import numpy as nm\n'), ((8934, 8954), 'numpy.linalg.norm', 'nm.linalg.norm', (['part'], {}), '(part)\n', (8948, 8954), True, 'import numpy as nm\n'), ((8989, 9009), 'numpy.finfo', 'nm.finfo', (['nm.float64'], {}), '(nm.float64)\n', (8997, 9009), True, 'import numpy as nm\n')] |
from sfepy.terms.extmods import terms
from sfepy.terms.cache import DataCache
from sfepy.base.base import nm, pause, debug
class ExpHistoryDataCache(DataCache):
"""History for exponential decay convolution kernels.
The decay argument is F(\Delta t), F(t_0=0) is assumed to be 1.0.
"""
name = 'exp_history'
arg_types = ('decay', 'values')
def __init__(self, name, arg_names, history_sizes=None):
DataCache.__init__(self, name, arg_names,
['history', 'increment', 'decay'], history_sizes)
def init_data(self, key, ckey, term, **kwargs):
decay, values = self.get_args(**kwargs)
shape = values.shape
self.shapes = {
'history' : shape,
'increment' : shape,
'decay' : decay.shape,
}
DataCache.init_datas(self, ckey, self.shapes, zero=True)
def update(self, key, term, ih, **kwargs):
decay, values = self.get_args(**kwargs)
ckey = self.get_key(term)
self.data['increment'][ckey][ih] = values
self.data['decay'][ckey][ih] = decay
self.valid['history'][ckey] = True
self.valid['increment'][ckey] = True
self.valid['decay'][ckey] = True
def custom_advance(self, key, ckey, step):
if key == 'history':
history = self.data['history'][ckey][0]
increment = self.data['increment'][ckey][0]
decay = self.data['decay'][ckey][0]
self.data['history'][ckey][0][:] = decay * (history + increment)
| [
"sfepy.terms.cache.DataCache.init_datas",
"sfepy.terms.cache.DataCache.__init__"
] | [((430, 525), 'sfepy.terms.cache.DataCache.__init__', 'DataCache.__init__', (['self', 'name', 'arg_names', "['history', 'increment', 'decay']", 'history_sizes'], {}), "(self, name, arg_names, ['history', 'increment', 'decay'],\n history_sizes)\n", (448, 525), False, 'from sfepy.terms.cache import DataCache\n'), ((820, 876), 'sfepy.terms.cache.DataCache.init_datas', 'DataCache.init_datas', (['self', 'ckey', 'self.shapes'], {'zero': '(True)'}), '(self, ckey, self.shapes, zero=True)\n', (840, 876), False, 'from sfepy.terms.cache import DataCache\n')] |
from __future__ import absolute_import
import numpy as nm
from sfepy.base.base import assert_
from sfepy.linalg import norm_l2_along_axis as norm
from sfepy.linalg import dot_sequences, insert_strided_axis
from sfepy.discrete.fem.poly_spaces import PolySpace
from sfepy.discrete.fem.mappings import VolumeMapping
from sfepy.mechanics.tensors import dim2sym
from six.moves import range
def create_transformation_matrix(coors):
"""
Create a transposed coordinate transformation matrix, that
transforms 3D coordinates of element face nodes so that the
transformed nodes are in the `x-y` plane. The rotation is performed
w.r.t. the first node of each face.
Parameters
----------
coors : array
The coordinates of element nodes, shape `(n_el, n_ep, dim)`.
Returns
-------
mtx_t : array
The transposed transformation matrix :math:`T`, i.e.
:math:`X_{inplane} = T^T X_{3D}`.
Notes
-----
:math:`T = [t_1, t_2, n]`, where :math:`t_1`, :math:`t_2`, are unit
in-plane (column) vectors and :math:`n` is the unit normal vector,
all mutually orthonormal.
"""
# Local coordinate system.
t1 = coors[:, 1, :] - coors[:, 0, :]
t2 = coors[:, -1, :] - coors[:, 0, :]
n = nm.cross(t1, t2)
t2 = nm.cross(n, t1)
t1 = t1 / norm(t1)[:, None]
t2 = t2 / norm(t2)[:, None]
n = n / norm(n)[:, None]
# Coordinate transformation matrix (transposed!).
mtx_t = nm.concatenate((t1[:, :, None],
t2[:, :, None],
n[:, :, None]), axis=2)
return mtx_t
def transform_asm_vectors(out, mtx_t):
"""
Transform vector assembling contributions to global coordinate system, one
node at a time.
Parameters
----------
out : array
The array of vectors, transformed in-place.
mtx_t : array
The transposed transformation matrix :math:`T`, see
:func:`create_transformation_matrix`.
"""
n_ep = out.shape[2] // mtx_t.shape[2]
for iep in range(n_ep):
ir = slice(iep, None, n_ep)
fn = out[:, 0, ir, 0]
fn[:] = dot_sequences(mtx_t, fn, 'AB')
def transform_asm_matrices(out, mtx_t):
"""
Transform matrix assembling contributions to global coordinate system, one
node at a time.
Parameters
----------
out : array
The array of matrices, transformed in-place.
mtx_t : array
The transposed transformation matrix :math:`T`, see
:func:`create_transformation_matrix`.
"""
n_ep = out.shape[-1] // mtx_t.shape[-1]
for iepr in range(n_ep):
ir = slice(iepr, None, n_ep)
for iepc in range(n_ep):
ic = slice(iepc, None, n_ep)
fn = out[:, 0, ir, ic]
fn[:] = dot_sequences(dot_sequences(mtx_t, fn, 'AB'), mtx_t, 'ABT')
def create_mapping(coors, gel, order):
"""
Create mapping from transformed (in `x-y` plane) element faces to
reference element faces.
Parameters
----------
coors : array
The transformed coordinates of element nodes, shape `(n_el,
n_ep, dim)`. The function verifies that the all `z` components
are zero.
gel : GeometryElement instance
The geometry element corresponding to the faces.
order : int
The polynomial order of the mapping.
Returns
-------
mapping : VolumeMapping instance
The reference element face mapping.
"""
# Strip 'z' component (should be 0 now...).
assert_(nm.allclose(coors[:, :, -1], 0.0, rtol=1e-12, atol=1e-12))
coors = coors[:, :, :-1].copy()
# Mapping from transformed element to reference element.
sh = coors.shape
seq_coors = coors.reshape((sh[0] * sh[1], sh[2]))
seq_conn = nm.arange(seq_coors.shape[0], dtype=nm.int32)
seq_conn.shape = sh[:2]
mapping = VolumeMapping(seq_coors, seq_conn, gel=gel, order=1)
return mapping
def describe_geometry(field, region, integral):
"""
Describe membrane geometry in a given region.
Parameters
----------
field : Field instance
The field defining the FE approximation.
region : Region instance
The surface region to describe.
integral : Integral instance
The integral defining the quadrature points.
Returns
-------
mtx_t : array
The transposed transformation matrix :math:`T`, see
:func:`create_transformation_matrix`.
membrane_geo : CMapping instance
The mapping from transformed elements to a reference elements.
"""
# Coordinates of element vertices.
sg, _ = field.get_mapping(region, integral, 'surface')
sd = field.surface_data[region.name]
coors = field.coors[sd.econn[:, :sg.n_ep]]
# Coordinate transformation matrix (transposed!).
mtx_t = create_transformation_matrix(coors)
# Transform coordinates to the local coordinate system.
coors_loc = dot_sequences((coors - coors[:, 0:1, :]), mtx_t)
# Mapping from transformed elements to reference elements.
gel = field.gel.surface_facet
vm = create_mapping(coors_loc, gel, 1)
qp = integral.get_qp(gel.name)
ps = PolySpace.any_from_args(None, gel, field.approx_order)
membrane_geo = vm.get_mapping(qp[0], qp[1], poly_space=ps)
membrane_geo.bf[:] = ps.eval_base(qp[0])
return mtx_t, membrane_geo
def describe_deformation(el_disps, bfg):
"""
Describe deformation of a thin incompressible 2D membrane in 3D
space, composed of flat finite element faces.
The coordinate system of each element (face), i.e. the membrane
mid-surface, should coincide with the `x`, `y` axes of the `x-y`
plane.
Parameters
----------
el_disps : array
The displacements of element nodes, shape `(n_el, n_ep, dim)`.
bfg : array
The in-plane base function gradients, shape `(n_el, n_qp, dim-1,
n_ep)`.
Returns
-------
mtx_c ; array
The in-plane right Cauchy-Green deformation tensor
:math:`C_{ij}`, :math:`i, j = 1, 2`.
c33 : array
The component :math:`C_{33}` computed from the incompressibility
condition.
mtx_b : array
The discrete Green strain variation operator.
"""
sh = bfg.shape
n_ep = sh[3]
dim = el_disps.shape[2]
sym2 = dim2sym(dim-1)
# Repeat el_disps by number of quadrature points.
el_disps_qp = insert_strided_axis(el_disps, 1, bfg.shape[1])
# Transformed (in-plane) displacement gradient with
# shape (n_el, n_qp, 2 (-> a), 3 (-> i)), du_i/dX_a.
du = dot_sequences(bfg, el_disps_qp)
# Deformation gradient F w.r.t. in plane coordinates.
# F_{ia} = dx_i / dX_a,
# a \in {1, 2} (rows), i \in {1, 2, 3} (columns).
mtx_f = du + nm.eye(dim - 1, dim, dtype=du.dtype)
# Right Cauchy-Green deformation tensor C.
# C_{ab} = F_{ka} F_{kb}, a, b \in {1, 2}.
mtx_c = dot_sequences(mtx_f, mtx_f, 'ABT')
# C_33 from incompressibility.
c33 = 1.0 / (mtx_c[..., 0, 0] * mtx_c[..., 1, 1]
- mtx_c[..., 0, 1]**2)
# Discrete Green strain variation operator.
mtx_b = nm.empty((sh[0], sh[1], sym2, dim * n_ep), dtype=nm.float64)
mtx_b[..., 0, 0*n_ep:1*n_ep] = bfg[..., 0, :] * mtx_f[..., 0, 0:1]
mtx_b[..., 0, 1*n_ep:2*n_ep] = bfg[..., 0, :] * mtx_f[..., 0, 1:2]
mtx_b[..., 0, 2*n_ep:3*n_ep] = bfg[..., 0, :] * mtx_f[..., 0, 2:3]
mtx_b[..., 1, 0*n_ep:1*n_ep] = bfg[..., 1, :] * mtx_f[..., 1, 0:1]
mtx_b[..., 1, 1*n_ep:2*n_ep] = bfg[..., 1, :] * mtx_f[..., 1, 1:2]
mtx_b[..., 1, 2*n_ep:3*n_ep] = bfg[..., 1, :] * mtx_f[..., 1, 2:3]
mtx_b[..., 2, 0*n_ep:1*n_ep] = bfg[..., 1, :] * mtx_f[..., 0, 0:1] \
+ bfg[..., 0, :] * mtx_f[..., 1, 0:1]
mtx_b[..., 2, 1*n_ep:2*n_ep] = bfg[..., 0, :] * mtx_f[..., 1, 1:2] \
+ bfg[..., 1, :] * mtx_f[..., 0, 1:2]
mtx_b[..., 2, 2*n_ep:3*n_ep] = bfg[..., 0, :] * mtx_f[..., 1, 2:3] \
+ bfg[..., 1, :] * mtx_f[..., 0, 2:3]
return mtx_c, c33, mtx_b
def get_tangent_stress_matrix(stress, bfg):
"""
Get the tangent stress matrix of a thin incompressible 2D membrane
in 3D space, given a stress.
Parameters
----------
stress : array
The components `11, 22, 12` of the second Piola-Kirchhoff stress
tensor, shape `(n_el, n_qp, 3, 1)`.
bfg : array
The in-plane base function gradients, shape `(n_el, n_qp, dim-1,
n_ep)`.
Returns
-------
mtx : array
The tangent stress matrix, shape `(n_el, n_qp, dim*n_ep, dim*n_ep)`.
"""
n_el, n_qp, dim, n_ep = bfg.shape
dim += 1
mtx = nm.zeros((n_el, n_qp, dim * n_ep, dim * n_ep), dtype=nm.float64)
g1tg1 = dot_sequences(bfg[..., 0:1, :], bfg[..., 0:1, :], 'ATB')
g1tg2 = dot_sequences(bfg[..., 0:1, :], bfg[..., 1:2, :], 'ATB')
g2tg1 = dot_sequences(bfg[..., 1:2, :], bfg[..., 0:1, :], 'ATB')
g2tg2 = dot_sequences(bfg[..., 1:2, :], bfg[..., 1:2, :], 'ATB')
aux = stress[..., 0:1, :] * g1tg1 + stress[..., 2:3, :] * g1tg2 \
+ stress[..., 2:3, :] * g2tg1 + stress[..., 1:2, :] * g2tg2
mtx[..., 0 * n_ep : 1 * n_ep, 0 * n_ep : 1 * n_ep] = aux
mtx[..., 1 * n_ep : 2 * n_ep, 1 * n_ep : 2 * n_ep] = aux
mtx[..., 2 * n_ep : 3 * n_ep, 2 * n_ep : 3 * n_ep] = aux
return mtx
def get_invariants(mtx_c, c33):
"""
Get the first and second invariants of the right Cauchy-Green
deformation tensor describing deformation of an incompressible
membrane.
Parameters
----------
mtx_c ; array
The in-plane right Cauchy-Green deformation tensor
:math:`C_{ij}`, :math:`i, j = 1, 2`, shape `(n_el, n_qp, dim-1,
dim-1)`.
c33 : array
The component :math:`C_{33}` computed from the incompressibility
condition, shape `(n_el, n_qp)`.
Returns
-------
i1 : array
The first invariant of :math:`C_{ij}`.
i2 : array
The second invariant of :math:`C_{ij}`.
"""
i1 = mtx_c[..., 0, 0] + mtx_c[..., 1, 1] + c33
i2 = mtx_c[..., 0, 0] * mtx_c[..., 1,1] \
+ mtx_c[..., 1, 1] * c33 \
+ mtx_c[..., 0, 0] * c33 \
- mtx_c[..., 0, 1]**2
return i1, i2
def get_green_strain_sym3d(mtx_c, c33):
r"""
Get the 3D Green strain tensor in symmetric storage.
Parameters
----------
mtx_c ; array
The in-plane right Cauchy-Green deformation tensor
:math:`C_{ij}`, :math:`i, j = 1, 2`, shape `(n_el, n_qp, dim-1,
dim-1)`.
c33 : array
The component :math:`C_{33}` computed from the incompressibility
condition, shape `(n_el, n_qp)`.
Returns
-------
mtx_e : array
The membrane Green strain :math:`E_{ij} = \frac{1}{2} (C_{ij}) -
\delta_{ij}`, symmetric storage: items (11, 22, 33, 12, 13, 23),
shape `(n_el, n_qp, sym, 1)`.
"""
n_el, n_qp, dm, _ = mtx_c.shape
dim = dm + 1
sym = dim2sym(dim)
mtx_e = nm.empty((n_el, n_qp, sym, 1), dtype=mtx_c.dtype)
mtx_e[..., 0, 0] = 0.5 * (mtx_c[..., 0, 0] - 1.0)
mtx_e[..., 1, 0] = 0.5 * (mtx_c[..., 1, 1] - 1.0)
mtx_e[..., 2, 0] = 0.5 * (c33 - 1.0)
mtx_e[..., 3, 0] = 0.5 * mtx_c[..., 0, 1]
mtx_e[..., 4:, 0] = 0.0
return mtx_e
| [
"sfepy.linalg.norm_l2_along_axis",
"sfepy.discrete.fem.poly_spaces.PolySpace.any_from_args",
"sfepy.mechanics.tensors.dim2sym",
"sfepy.linalg.insert_strided_axis",
"sfepy.linalg.dot_sequences",
"sfepy.discrete.fem.mappings.VolumeMapping"
] | [((1263, 1279), 'numpy.cross', 'nm.cross', (['t1', 't2'], {}), '(t1, t2)\n', (1271, 1279), True, 'import numpy as nm\n'), ((1289, 1304), 'numpy.cross', 'nm.cross', (['n', 't1'], {}), '(n, t1)\n', (1297, 1304), True, 'import numpy as nm\n'), ((1466, 1537), 'numpy.concatenate', 'nm.concatenate', (['(t1[:, :, None], t2[:, :, None], n[:, :, None])'], {'axis': '(2)'}), '((t1[:, :, None], t2[:, :, None], n[:, :, None]), axis=2)\n', (1480, 1537), True, 'import numpy as nm\n'), ((2047, 2058), 'six.moves.range', 'range', (['n_ep'], {}), '(n_ep)\n', (2052, 2058), False, 'from six.moves import range\n'), ((2613, 2624), 'six.moves.range', 'range', (['n_ep'], {}), '(n_ep)\n', (2618, 2624), False, 'from six.moves import range\n'), ((3779, 3824), 'numpy.arange', 'nm.arange', (['seq_coors.shape[0]'], {'dtype': 'nm.int32'}), '(seq_coors.shape[0], dtype=nm.int32)\n', (3788, 3824), True, 'import numpy as nm\n'), ((3868, 3920), 'sfepy.discrete.fem.mappings.VolumeMapping', 'VolumeMapping', (['seq_coors', 'seq_conn'], {'gel': 'gel', 'order': '(1)'}), '(seq_coors, seq_conn, gel=gel, order=1)\n', (3881, 3920), False, 'from sfepy.discrete.fem.mappings import VolumeMapping\n'), ((4941, 4987), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['(coors - coors[:, 0:1, :])', 'mtx_t'], {}), '(coors - coors[:, 0:1, :], mtx_t)\n', (4954, 4987), False, 'from sfepy.linalg import dot_sequences, insert_strided_axis\n'), ((5176, 5230), 'sfepy.discrete.fem.poly_spaces.PolySpace.any_from_args', 'PolySpace.any_from_args', (['None', 'gel', 'field.approx_order'], {}), '(None, gel, field.approx_order)\n', (5199, 5230), False, 'from sfepy.discrete.fem.poly_spaces import PolySpace\n'), ((6327, 6343), 'sfepy.mechanics.tensors.dim2sym', 'dim2sym', (['(dim - 1)'], {}), '(dim - 1)\n', (6334, 6343), False, 'from sfepy.mechanics.tensors import dim2sym\n'), ((6415, 6461), 'sfepy.linalg.insert_strided_axis', 'insert_strided_axis', (['el_disps', '(1)', 'bfg.shape[1]'], {}), '(el_disps, 1, bfg.shape[1])\n', (6434, 6461), False, 'from sfepy.linalg import dot_sequences, insert_strided_axis\n'), ((6585, 6616), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['bfg', 'el_disps_qp'], {}), '(bfg, el_disps_qp)\n', (6598, 6616), False, 'from sfepy.linalg import dot_sequences, insert_strided_axis\n'), ((6919, 6953), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['mtx_f', 'mtx_f', '"""ABT"""'], {}), "(mtx_f, mtx_f, 'ABT')\n", (6932, 6953), False, 'from sfepy.linalg import dot_sequences, insert_strided_axis\n'), ((7144, 7204), 'numpy.empty', 'nm.empty', (['(sh[0], sh[1], sym2, dim * n_ep)'], {'dtype': 'nm.float64'}), '((sh[0], sh[1], sym2, dim * n_ep), dtype=nm.float64)\n', (7152, 7204), True, 'import numpy as nm\n'), ((8716, 8780), 'numpy.zeros', 'nm.zeros', (['(n_el, n_qp, dim * n_ep, dim * n_ep)'], {'dtype': 'nm.float64'}), '((n_el, n_qp, dim * n_ep, dim * n_ep), dtype=nm.float64)\n', (8724, 8780), True, 'import numpy as nm\n'), ((8794, 8850), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['bfg[..., 0:1, :]', 'bfg[..., 0:1, :]', '"""ATB"""'], {}), "(bfg[..., 0:1, :], bfg[..., 0:1, :], 'ATB')\n", (8807, 8850), False, 'from sfepy.linalg import dot_sequences, insert_strided_axis\n'), ((8863, 8919), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['bfg[..., 0:1, :]', 'bfg[..., 1:2, :]', '"""ATB"""'], {}), "(bfg[..., 0:1, :], bfg[..., 1:2, :], 'ATB')\n", (8876, 8919), False, 'from sfepy.linalg import dot_sequences, insert_strided_axis\n'), ((8932, 8988), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['bfg[..., 1:2, :]', 'bfg[..., 0:1, :]', '"""ATB"""'], {}), "(bfg[..., 1:2, :], bfg[..., 0:1, :], 'ATB')\n", (8945, 8988), False, 'from sfepy.linalg import dot_sequences, insert_strided_axis\n'), ((9001, 9057), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['bfg[..., 1:2, :]', 'bfg[..., 1:2, :]', '"""ATB"""'], {}), "(bfg[..., 1:2, :], bfg[..., 1:2, :], 'ATB')\n", (9014, 9057), False, 'from sfepy.linalg import dot_sequences, insert_strided_axis\n'), ((11024, 11036), 'sfepy.mechanics.tensors.dim2sym', 'dim2sym', (['dim'], {}), '(dim)\n', (11031, 11036), False, 'from sfepy.mechanics.tensors import dim2sym\n'), ((11050, 11099), 'numpy.empty', 'nm.empty', (['(n_el, n_qp, sym, 1)'], {'dtype': 'mtx_c.dtype'}), '((n_el, n_qp, sym, 1), dtype=mtx_c.dtype)\n', (11058, 11099), True, 'import numpy as nm\n'), ((2142, 2172), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['mtx_t', 'fn', '"""AB"""'], {}), "(mtx_t, fn, 'AB')\n", (2155, 2172), False, 'from sfepy.linalg import dot_sequences, insert_strided_axis\n'), ((2683, 2694), 'six.moves.range', 'range', (['n_ep'], {}), '(n_ep)\n', (2688, 2694), False, 'from six.moves import range\n'), ((3532, 3589), 'numpy.allclose', 'nm.allclose', (['coors[:, :, -1]', '(0.0)'], {'rtol': '(1e-12)', 'atol': '(1e-12)'}), '(coors[:, :, -1], 0.0, rtol=1e-12, atol=1e-12)\n', (3543, 3589), True, 'import numpy as nm\n'), ((6775, 6811), 'numpy.eye', 'nm.eye', (['(dim - 1)', 'dim'], {'dtype': 'du.dtype'}), '(dim - 1, dim, dtype=du.dtype)\n', (6781, 6811), True, 'import numpy as nm\n'), ((1320, 1328), 'sfepy.linalg.norm_l2_along_axis', 'norm', (['t1'], {}), '(t1)\n', (1324, 1328), True, 'from sfepy.linalg import norm_l2_along_axis as norm\n'), ((1352, 1360), 'sfepy.linalg.norm_l2_along_axis', 'norm', (['t2'], {}), '(t2)\n', (1356, 1360), True, 'from sfepy.linalg import norm_l2_along_axis as norm\n'), ((1382, 1389), 'sfepy.linalg.norm_l2_along_axis', 'norm', (['n'], {}), '(n)\n', (1386, 1389), True, 'from sfepy.linalg import norm_l2_along_axis as norm\n'), ((2806, 2836), 'sfepy.linalg.dot_sequences', 'dot_sequences', (['mtx_t', 'fn', '"""AB"""'], {}), "(mtx_t, fn, 'AB')\n", (2819, 2836), False, 'from sfepy.linalg import dot_sequences, insert_strided_axis\n')] |
import os.path as op
import numpy as nm
import sfepy
from sfepy.discrete.common import Field
import sfepy.discrete.common.global_interp as gi
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
test = Test(conf=conf, options=options)
return test
def test_ref_coors_fem(self):
from sfepy.discrete.fem import Mesh, FEDomain
mesh = Mesh.from_file('meshes/3d/special/cross3d.mesh',
prefix_dir=sfepy.data_dir)
domain = FEDomain('domain', mesh)
omega = domain.create_region('Omega', 'all')
field = Field.from_args('linear', nm.float64, 'scalar', omega,
approx_order=1)
mcoors = field.domain.get_mesh_coors()
conn = field.domain.get_conn()
bbox = field.domain.get_mesh_bounding_box()
ray = nm.linspace(bbox[0, 0], bbox[1, 0], 7)
coors = nm.zeros((ray.shape[0], 3), dtype=nm.float64)
def gen_rays():
coors[:, 0] = ray
yield coors
coors.fill(0.0)
coors[:, 1] = ray
yield coors
coors.fill(0.0)
coors[:, 2] = ray
yield coors
ok = True
ctx = field.create_basis_context()._geo_ctx
for ir, coors in enumerate(gen_rays()):
self.report('ray %d' % ir)
ref_coors, cells, status = gi.get_ref_coors(field, coors,
strategy='general',
close_limit=0.0,
verbose=False)
self.report(ref_coors)
self.report(cells)
self.report(status)
# In the distorted cell 2, the Newton method finds a solution
# outside of the cell. This will be fixed when box constraints
# are applied.
_ok = nm.all((status == 0) | ((cells == 2) & (status == 3)))
if not _ok:
self.report('wrong status %s for ray %d!' % (status, ir))
ok = ok and _ok
for ic, cell in enumerate(cells):
ctx.iel = cell
bf = ctx.evaluate(ref_coors[ic:ic+1], check_errors=False)
cell_coors = mcoors[conn[cell]]
coor = nm.dot(bf, cell_coors).ravel()
_ok = nm.allclose(coor, coors[ic], atol=1e-14, rtol=0.0)
if not _ok:
self.report('ray %d point %d:' % (ir, ic))
self.report(' - wrong reference coordinates %s!'
% ref_coors[ic])
self.report(' - given point: %s' % coors[ic])
self.report(' - found point: %s' % coor)
ok = ok and _ok
return ok
def test_ref_coors_iga(self):
from sfepy.discrete.iga.domain import IGDomain
domain = IGDomain.from_file(op.join(sfepy.data_dir,
'meshes/iga/block2d.iga'))
omega = domain.create_region('Omega', 'all')
field = Field.from_args('iga', nm.float64, 'scalar', omega,
approx_order='iga', poly_space_base='iga')
mcoors = field.nurbs.cps
conn = field.get_econn('volume', field.region)
bbox = domain.eval_mesh.get_bounding_box()
ray = nm.linspace(bbox[0, 0], bbox[1, 0], 11)
coors = nm.c_[ray, ray]
ref_coors, cells, status = gi.get_ref_coors(field, coors,
strategy='general',
close_limit=0.0,
verbose=False)
self.report(ref_coors)
self.report(cells)
self.report(status)
ok = nm.all(status == 0)
ctx = field.create_basis_context()
for ic, cell in enumerate(cells):
ctx.iel = cell
bf = ctx.evaluate(ref_coors[ic:ic+1])
cell_coors = mcoors[conn[cell]]
coor = nm.dot(bf, cell_coors).ravel()
_ok = nm.allclose(coor, coors[ic], atol=1e-14, rtol=0.0)
if not _ok:
self.report('point %d:' % ic)
self.report(' - wrong reference coordinates %s!'
% ref_coors[ic])
self.report(' - given point: %s' % coors[ic])
self.report(' - found point: %s' % coor)
ok = ok and _ok
return ok
| [
"sfepy.discrete.common.Field.from_args",
"sfepy.discrete.common.global_interp.get_ref_coors",
"sfepy.discrete.fem.Mesh.from_file",
"sfepy.discrete.fem.FEDomain"
] | [((438, 513), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['"""meshes/3d/special/cross3d.mesh"""'], {'prefix_dir': 'sfepy.data_dir'}), "('meshes/3d/special/cross3d.mesh', prefix_dir=sfepy.data_dir)\n", (452, 513), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((561, 585), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""domain"""', 'mesh'], {}), "('domain', mesh)\n", (569, 585), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((657, 727), 'sfepy.discrete.common.Field.from_args', 'Field.from_args', (['"""linear"""', 'nm.float64', '"""scalar"""', 'omega'], {'approx_order': '(1)'}), "('linear', nm.float64, 'scalar', omega, approx_order=1)\n", (672, 727), False, 'from sfepy.discrete.common import Field\n'), ((915, 953), 'numpy.linspace', 'nm.linspace', (['bbox[0, 0]', 'bbox[1, 0]', '(7)'], {}), '(bbox[0, 0], bbox[1, 0], 7)\n', (926, 953), True, 'import numpy as nm\n'), ((970, 1015), 'numpy.zeros', 'nm.zeros', (['(ray.shape[0], 3)'], {'dtype': 'nm.float64'}), '((ray.shape[0], 3), dtype=nm.float64)\n', (978, 1015), True, 'import numpy as nm\n'), ((3195, 3293), 'sfepy.discrete.common.Field.from_args', 'Field.from_args', (['"""iga"""', 'nm.float64', '"""scalar"""', 'omega'], {'approx_order': '"""iga"""', 'poly_space_base': '"""iga"""'}), "('iga', nm.float64, 'scalar', omega, approx_order='iga',\n poly_space_base='iga')\n", (3210, 3293), False, 'from sfepy.discrete.common import Field\n'), ((3477, 3516), 'numpy.linspace', 'nm.linspace', (['bbox[0, 0]', 'bbox[1, 0]', '(11)'], {}), '(bbox[0, 0], bbox[1, 0], 11)\n', (3488, 3516), True, 'import numpy as nm\n'), ((3585, 3672), 'sfepy.discrete.common.global_interp.get_ref_coors', 'gi.get_ref_coors', (['field', 'coors'], {'strategy': '"""general"""', 'close_limit': '(0.0)', 'verbose': '(False)'}), "(field, coors, strategy='general', close_limit=0.0, verbose\n =False)\n", (3601, 3672), True, 'import sfepy.discrete.common.global_interp as gi\n'), ((3924, 3943), 'numpy.all', 'nm.all', (['(status == 0)'], {}), '(status == 0)\n', (3930, 3943), True, 'import numpy as nm\n'), ((1460, 1547), 'sfepy.discrete.common.global_interp.get_ref_coors', 'gi.get_ref_coors', (['field', 'coors'], {'strategy': '"""general"""', 'close_limit': '(0.0)', 'verbose': '(False)'}), "(field, coors, strategy='general', close_limit=0.0, verbose\n =False)\n", (1476, 1547), True, 'import sfepy.discrete.common.global_interp as gi\n'), ((2004, 2056), 'numpy.all', 'nm.all', (['((status == 0) | (cells == 2) & (status == 3))'], {}), '((status == 0) | (cells == 2) & (status == 3))\n', (2010, 2056), True, 'import numpy as nm\n'), ((3029, 3078), 'os.path.join', 'op.join', (['sfepy.data_dir', '"""meshes/iga/block2d.iga"""'], {}), "(sfepy.data_dir, 'meshes/iga/block2d.iga')\n", (3036, 3078), True, 'import os.path as op\n'), ((4222, 4272), 'numpy.allclose', 'nm.allclose', (['coor', 'coors[ic]'], {'atol': '(1e-14)', 'rtol': '(0.0)'}), '(coor, coors[ic], atol=1e-14, rtol=0.0)\n', (4233, 4272), True, 'import numpy as nm\n'), ((2464, 2514), 'numpy.allclose', 'nm.allclose', (['coor', 'coors[ic]'], {'atol': '(1e-14)', 'rtol': '(0.0)'}), '(coor, coors[ic], atol=1e-14, rtol=0.0)\n', (2475, 2514), True, 'import numpy as nm\n'), ((4172, 4194), 'numpy.dot', 'nm.dot', (['bf', 'cell_coors'], {}), '(bf, cell_coors)\n', (4178, 4194), True, 'import numpy as nm\n'), ((2410, 2432), 'numpy.dot', 'nm.dot', (['bf', 'cell_coors'], {}), '(bf, cell_coors)\n', (2416, 2432), True, 'import numpy as nm\n')] |
"""Classes for probing values of Variables, for example, along a line."""
from __future__ import absolute_import
import numpy as nm
import numpy.linalg as nla
from sfepy.base.base import get_default, basestr, Struct
from sfepy.linalg import make_axis_rotation_matrix, norm_l2_along_axis
import six
def write_results(filename, probe, results):
"""
Write probing results into a file.
Parameters
----------
filename : str or file object
The output file name.
probe : Probe subclass instance
The probe used to obtain the results.
results : dict
The dictionary of probing results. Keys are data names, values are
the probed values.
"""
fd = open(filename, 'w') if isinstance(filename, basestr) else filename
fd.write('\n'.join(probe.report()) + '\n')
for key, result in six.iteritems(results):
pars, vals = result
fd.write('\n# %s %d\n' % (key, vals.shape[-1]))
if vals.ndim == 1:
aux = nm.hstack((pars[:,None], vals[:,None]))
else:
aux = nm.hstack((pars[:,None], vals))
nm.savetxt(fd, aux)
if isinstance(filename, basestr):
fd.close()
def read_results(filename, only_names=None):
"""
Read probing results from a file.
Parameters
----------
filename : str or file object
The probe results file name.
Returns
-------
header : Struct instance
The probe data header.
results : dict
The dictionary of probing results. Keys are data names, values are
the probed values.
"""
from sfepy.base.ioutils import read_array
only_names = get_default(only_names, [])
fd = open(filename, 'r') if isinstance(filename, basestr) else filename
header = read_header(fd)
results = {}
for name, nc in get_data_name(fd):
if name not in only_names: continue
result = read_array(fd, header.n_point, nc + 1, nm.float64)
results[name] = result
return header, results
def read_header(fd):
"""
Read the probe data header from file descriptor fd.
Returns
-------
header : Struct instance
The probe data header.
"""
header = Struct(name='probe_data_header')
header.probe_class = fd.readline().strip()
aux = fd.readline().strip().split(':')[1]
header.n_point = int(aux.strip().split()[0])
details = []
while 1:
line = fd.readline().strip()
if line == '-----':
break
else:
details.append(line)
header.details = '\n'.join(details)
return header
def get_data_name(fd):
"""
Try to read next data name in file fd.
Returns
-------
name : str
The data name.
nc : int
The number of data columns.
"""
name = None
while 1:
try:
line = fd.readline()
if (len(line) == 0): break
if len(line) == 1: continue
except:
raise StopIteration
line = line.strip().split()
if (len(line) == 3) and (line[0] == '#'):
name = line[1]
nc = int(line[2])
yield name, nc
class Probe(Struct):
"""
Base class for all point probes. Enforces two points minimum.
"""
cache = Struct(name='probe_shared_evaluate_cache')
is_cyclic = False
def __init__(self, name, share_geometry=True, n_point=None, **kwargs):
"""
Parameters
----------
name : str
The probe name, set automatically by the subclasses.
share_geometry : bool
Set to True to indicate that all the probes will work on the same
domain. Certain data are then computed only for the first probe and
cached.
n_point : int
The (fixed) number of probe points, when positive. When non-positive,
the number of points is adaptively increased starting from -n_point,
until the neighboring point distance is less than the diameter of the
elements enclosing the points. When None, it is set to -10.
For additional parameters see the __init__() docstrings of the
subclasses.
"""
Struct.__init__(self, name=name, share_geometry=share_geometry,
**kwargs)
self.set_n_point(n_point)
self.options = Struct(close_limit=0.1, size_hint=None)
self.cache = Struct(name='probe_local_evaluate_cache')
self.is_refined = False
def get_evaluate_cache(self):
"""
Return the evaluate cache for domain-related data given by
`self.share_geometry`.
"""
return Probe.cache if self.share_geometry else self.cache
def set_n_point(self, n_point):
"""
Set the number of probe points.
Parameters
----------
n_point : int
The (fixed) number of probe points, when positive. When non-positive,
the number of points is adaptively increased starting from -n_point,
until the neighboring point distance is less than the diameter of the
elements enclosing the points. When None, it is set to -10.
"""
if n_point is None:
n_point = -10
if n_point <= 0:
n_point = max(-n_point, 2)
self.n_point_required = -1
else:
n_point = max(n_point, 2)
self.n_point_required = n_point
self.n_point0 = self.n_point = n_point
def set_options(self, close_limit=None, size_hint=None):
"""
Set the probe options.
Parameters
----------
close_limit : float
The maximum limit distance of a point from the closest
element allowed for extrapolation.
size_hint : float
Element size hint for the refinement of probe parametrization.
"""
if close_limit is not None:
self.options.close_limit = close_limit
if size_hint is not None:
self.options.size_hint = size_hint
def report(self):
"""Report the probe parameters."""
out = [self.__class__.__name__]
if self.n_point_required == -1:
aux = 'adaptive'
else:
aux = 'fixed'
out.append('number of points: %s (%s)' % (self.n_point, aux))
return out
def __call__(self, variable, **kwargs):
"""
Probe the given variable. The actual implementation is in self.probe(),
so that it can be overridden in subclasses.
Parameters
----------
variable : Variable instance
The variable to be sampled along the probe.
**kwargs : additional arguments
See :func:`Probe.probe()`.
"""
return self.probe(variable, **kwargs)
def probe(self, variable, mode='val', ret_points=False):
"""
Probe the given variable.
Parameters
----------
variable : Variable instance
The variable to be sampled along the probe.
mode : {'val', 'grad'}, optional
The evaluation mode: the variable value (default) or the
variable value gradient.
ret_points : bool
If True, return also the probe points.
Returns
-------
pars : array
The parametrization of the probe points.
points : array, optional
If `ret_points` is True, the coordinates of points corresponding to
`pars`, where the `variable` is evaluated.
vals : array
The probed values.
"""
refine_flag = None
ev = variable.evaluate_at
field = variable.field
cache = field.get_evaluate_cache(cache=self.get_evaluate_cache(),
share_geometry=self.share_geometry)
self.reset_refinement()
while True:
pars, points = self.get_points(refine_flag)
if not nm.isfinite(points).all():
raise ValueError('Inf/nan in probe points!')
vals, cells = ev(points, mode=mode, strategy='general',
close_limit=self.options.close_limit,
cache=cache, ret_cells=True)
if self.is_refined:
break
else:
refine_flag = self.refine_points(variable, points, cells)
if (refine_flag == False).all():
break
self.is_refined = True
if ret_points:
return pars, points, vals
else:
return pars, vals
def reset_refinement(self):
"""
Reset the probe refinement state.
"""
self.is_refined = False
self.n_point = self.n_point0
def refine_points(self, variable, points, cells):
"""
Mark intervals between points for a refinement, based on element
sizes at those points. Assumes the points to be ordered.
Returns
-------
refine_flag : bool array
True at places corresponding to intervals between subsequent points
that need to be refined.
"""
if self.n_point_required == self.n_point:
refine_flag = nm.array([False])
else:
if self.options.size_hint is None:
ed = variable.get_element_diameters(cells, 0)
pd = 0.5 * (ed[1:] + ed[:-1])
else:
pd = self.options.size_hint
dist = norm_l2_along_axis(points[1:] - points[:-1])
refine_flag = dist > pd
if self.is_cyclic:
pd1 = 0.5 * (ed[0] + ed[-1])
dist1 = nla.norm(points[0] - points[-1])
refine_flag = nm.r_[refine_flag, dist1 > pd1]
return refine_flag
@staticmethod
def refine_pars(pars, refine_flag, cyclic_val=None):
"""
Refine the probe parametrization based on the refine_flag.
"""
ii = nm.where(refine_flag)[0]
ip = ii + 1
if cyclic_val is not None:
cpars = nm.r_[pars, cyclic_val]
pp = 0.5 * (cpars[ip] + cpars[ii])
else:
pp = 0.5 * (pars[ip] + pars[ii])
pars = nm.insert(pars, ip, pp)
return pars
class PointsProbe(Probe):
"""
Probe variables in given points.
"""
def __init__(self, points, share_geometry=True):
"""
Parameters
----------
points : array_like
The coordinates of the points.
"""
points = nm.array(points, dtype=nm.float64, order='C')
if points.ndim == 1:
points.shape = points.shape + (1,)
n_point = points.shape[0]
name = 'points %d' % n_point
Probe.__init__(self, name=name, share_geometry=share_geometry,
points=points, n_point=n_point)
self.n_point_single = n_point
def report(self):
"""Report the probe parameters."""
out = Probe.report(self)
for ii, point in enumerate(self.points):
out.append('point %d: %s' % (ii, point))
out.append('-----')
return out
def refine_points(self, variable, points, cache):
"""No refinement for this probe."""
refine_flag = nm.array([False])
return refine_flag
def get_points(self, refine_flag=None):
"""
Get the probe points.
Returns
-------
pars : array_like
The independent coordinate of the probe.
points : array_like
The probe points, parametrized by pars.
"""
pars = nm.arange(self.n_point, dtype=nm.float64)
return pars, self.points
class LineProbe(Probe):
"""
Probe variables along a line.
If n_point is positive, that number of evenly spaced points is used. If
n_point is None or non-positive, an adaptive refinement based on element
diameters is used and the number of points and their spacing are determined
automatically. If it is negative, -n_point is used as an initial guess.
"""
def __init__(self, p0, p1, n_point, share_geometry=True):
"""
Parameters
----------
p0 : array_like
The coordinates of the start point.
p1 : array_like
The coordinates of the end point.
"""
p0 = nm.array(p0, dtype=nm.float64)
p1 = nm.array(p1, dtype=nm.float64)
name = 'line [%s, %s]' % (p0, p1)
Probe.__init__(self, name=name, share_geometry=share_geometry,
p0=p0, p1=p1, n_point=n_point)
dirvec = self.p1 - self.p0
self.length = nm.linalg.norm(dirvec)
self.dirvec = dirvec / self.length
def report(self):
"""Report the probe parameters."""
out = Probe.report(self)
out.append('point 0: %s' % self.p0)
out.append('point 1: %s' % self.p1)
out.append('-----')
return out
def get_points(self, refine_flag=None):
"""
Get the probe points.
Returns
-------
pars : array_like
The independent coordinate of the probe.
points : array_like
The probe points, parametrized by pars.
"""
if self.is_refined:
return self.pars, self.points
if refine_flag is None:
pars = nm.linspace(0, self.length, self.n_point)
else:
pars = Probe.refine_pars(self.pars, refine_flag)
self.n_point = pars.shape[0]
self.pars = pars
self.points = self.p0 + self.dirvec * pars[:,None]
return pars, self.points
class RayProbe(Probe):
"""
Probe variables along a ray. The points are parametrized by a function of
radial coordinates from a given point in a given direction.
"""
def __init__(self, p0, dirvec, p_fun, n_point, both_dirs,
share_geometry=True):
"""
Parameters
----------
p0 : array_like
The coordinates of the start point.
dirvec : array_like
The probe direction vector.
p_fun : function
The function returning the probe parametrization along the dirvec
direction.
both_dirs : bool
If True, the probe works, starting at p0, symmetrically in both
dirvec and -dirvec directions.
"""
p0 = nm.array(p0, dtype=nm.float64)
dirvec = nm.array(dirvec, dtype=nm.float64)
dirvec /= nla.norm(dirvec)
name = 'ray %s [%s, %s]' % (p_fun.__name__, p0, dirvec)
if both_dirs:
n_point_true = 2 * n_point
else:
n_point_true = n_point
Probe.__init__(self, name=name, share_geometry=share_geometry,
p0=p0, dirvec=dirvec, p_fun=p_fun,
n_point=n_point_true, both_dirs=both_dirs)
self.n_point_single = n_point
def report(self):
"""Report the probe parameters."""
out = Probe.report(self)
out.append('point 0: %s' % self.p0)
out.append('direction vector: %s' % self.dirvec)
out.append('both directions: %s' % self.both_dirs)
out.append('distribution function: %s' % self.p_fun.__name__)
out.append('-----')
return out
def refine_points(self, variable, points, cache):
"""No refinement for this probe."""
refine_flag = nm.array([False])
return refine_flag
def gen_points(self, sign):
"""Generate the probe points and their parametrization."""
pars = self.p_fun(nm.arange(self.n_point_single, dtype=nm.float64))
points = self.p0 + sign * self.dirvec * pars[:,None]
return pars, points
def get_points(self, refine_flag=None):
"""
Get the probe points.
Returns
-------
pars : array_like
The independent coordinate of the probe.
points : array_like
The probe points, parametrized by pars.
"""
pars, points = self.gen_points(1.0)
if self.both_dirs:
pars0, points0 = self.gen_points(-1.0)
pars = nm.concatenate((-pars0[::-1], pars))
points = nm.concatenate((points0[::-1], points))
return pars, points
class CircleProbe(Probe):
"""
Probe variables along a circle.
If n_point is positive, that number of evenly spaced points is used. If
n_point is None or non-positive, an adaptive refinement based on element
diameters is used and the number of points and their spacing are determined
automatically. If it is negative, -n_point is used as an initial guess.
"""
is_cyclic = True
def __init__(self, centre, normal, radius, n_point, share_geometry=True):
"""
Parameters
----------
centre : array_like
The coordinates of the circle centre.
normal : array_like
The normal vector perpendicular to the circle plane.
radius : float
The radius of the circle.
"""
centre = nm.array(centre, dtype=nm.float64)
normal = nm.array(normal, dtype=nm.float64)
normal /= nla.norm(normal)
name = 'circle [%s, %s, %s]' % (centre, normal, radius)
Probe.__init__(self, name=name, share_geometry=share_geometry,
centre=centre, normal=normal,
radius=radius, n_point=n_point)
def report(self):
"""Report the probe parameters."""
out = Probe.report(self)
out.append('centre: %s' % self.centre)
out.append('normal: %s' % self.normal)
out.append('radius: %s' % self.radius)
out.append('-----')
return out
def get_points(self, refine_flag=None):
"""
Get the probe points.
Returns
-------
pars : array_like
The independent coordinate of the probe.
points : array_like
The probe points, parametrized by pars.
"""
# Vector of angles.
if self.is_refined:
return self.pars, self.points
if refine_flag is None:
pars = nm.linspace(0.0, 2.0*nm.pi, self.n_point + 1)[:-1]
else:
pars = Probe.refine_pars(self.pars, refine_flag,
cyclic_val=2.0 * nm.pi)
self.n_point = pars.shape[0]
self.pars = pars
# Create the points in xy plane, centered at the origin.
x = self.radius * nm.cos(pars[:,None])
y = self.radius * nm.sin(pars[:,None])
if len(self.centre) == 3:
z = nm.zeros((self.n_point, 1), dtype=nm.float64)
points = nm.c_[x, y, z]
# Rotate to satisfy the normal, shift to the centre.
n1 = nm.array([0.0, 0.0, 1.0], dtype=nm.float64)
axis = nm.cross(n1, self.normal)
angle = nm.arccos(nm.dot(n1, self.normal))
if nla.norm(axis) < 0.1:
# n1 == self.normal
rot_mtx = nm.eye(3, dtype=nm.float64)
else:
rot_mtx = make_axis_rotation_matrix(axis, angle)
points = nm.dot(points, rot_mtx)
else:
points = nm.c_[x, y]
points += self.centre
self.points = points
return pars, points
class IntegralProbe(Struct):
"""Evaluate integral expressions."""
def __init__(self, name, problem, expressions, labels):
Struct.__init__(self, name=name, problem=problem,
expressions=expressions, labels=labels)
def __call__(self, ip, state=None, **kwargs):
return self.problem.evaluate(self.expressions[ip], state, **kwargs)
| [
"sfepy.base.base.Struct",
"sfepy.linalg.make_axis_rotation_matrix",
"sfepy.base.base.get_default",
"sfepy.base.base.Struct.__init__",
"sfepy.linalg.norm_l2_along_axis",
"sfepy.base.ioutils.read_array"
] | [((845, 867), 'six.iteritems', 'six.iteritems', (['results'], {}), '(results)\n', (858, 867), False, 'import six\n'), ((1663, 1690), 'sfepy.base.base.get_default', 'get_default', (['only_names', '[]'], {}), '(only_names, [])\n', (1674, 1690), False, 'from sfepy.base.base import get_default, basestr, Struct\n'), ((2218, 2250), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""probe_data_header"""'}), "(name='probe_data_header')\n", (2224, 2250), False, 'from sfepy.base.base import get_default, basestr, Struct\n'), ((3300, 3342), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""probe_shared_evaluate_cache"""'}), "(name='probe_shared_evaluate_cache')\n", (3306, 3342), False, 'from sfepy.base.base import get_default, basestr, Struct\n'), ((1113, 1132), 'numpy.savetxt', 'nm.savetxt', (['fd', 'aux'], {}), '(fd, aux)\n', (1123, 1132), True, 'import numpy as nm\n'), ((1916, 1966), 'sfepy.base.ioutils.read_array', 'read_array', (['fd', 'header.n_point', '(nc + 1)', 'nm.float64'], {}), '(fd, header.n_point, nc + 1, nm.float64)\n', (1926, 1966), False, 'from sfepy.base.ioutils import read_array\n'), ((4230, 4303), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'name': 'name', 'share_geometry': 'share_geometry'}), '(self, name=name, share_geometry=share_geometry, **kwargs)\n', (4245, 4303), False, 'from sfepy.base.base import get_default, basestr, Struct\n'), ((4387, 4426), 'sfepy.base.base.Struct', 'Struct', ([], {'close_limit': '(0.1)', 'size_hint': 'None'}), '(close_limit=0.1, size_hint=None)\n', (4393, 4426), False, 'from sfepy.base.base import get_default, basestr, Struct\n'), ((4448, 4489), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""probe_local_evaluate_cache"""'}), "(name='probe_local_evaluate_cache')\n", (4454, 4489), False, 'from sfepy.base.base import get_default, basestr, Struct\n'), ((10325, 10348), 'numpy.insert', 'nm.insert', (['pars', 'ip', 'pp'], {}), '(pars, ip, pp)\n', (10334, 10348), True, 'import numpy as nm\n'), ((10654, 10699), 'numpy.array', 'nm.array', (['points'], {'dtype': 'nm.float64', 'order': '"""C"""'}), "(points, dtype=nm.float64, order='C')\n", (10662, 10699), True, 'import numpy as nm\n'), ((11382, 11399), 'numpy.array', 'nm.array', (['[False]'], {}), '([False])\n', (11390, 11399), True, 'import numpy as nm\n'), ((11731, 11772), 'numpy.arange', 'nm.arange', (['self.n_point'], {'dtype': 'nm.float64'}), '(self.n_point, dtype=nm.float64)\n', (11740, 11772), True, 'import numpy as nm\n'), ((12471, 12501), 'numpy.array', 'nm.array', (['p0'], {'dtype': 'nm.float64'}), '(p0, dtype=nm.float64)\n', (12479, 12501), True, 'import numpy as nm\n'), ((12515, 12545), 'numpy.array', 'nm.array', (['p1'], {'dtype': 'nm.float64'}), '(p1, dtype=nm.float64)\n', (12523, 12545), True, 'import numpy as nm\n'), ((12772, 12794), 'numpy.linalg.norm', 'nm.linalg.norm', (['dirvec'], {}), '(dirvec)\n', (12786, 12794), True, 'import numpy as nm\n'), ((14532, 14562), 'numpy.array', 'nm.array', (['p0'], {'dtype': 'nm.float64'}), '(p0, dtype=nm.float64)\n', (14540, 14562), True, 'import numpy as nm\n'), ((14580, 14614), 'numpy.array', 'nm.array', (['dirvec'], {'dtype': 'nm.float64'}), '(dirvec, dtype=nm.float64)\n', (14588, 14614), True, 'import numpy as nm\n'), ((14633, 14649), 'numpy.linalg.norm', 'nla.norm', (['dirvec'], {}), '(dirvec)\n', (14641, 14649), True, 'import numpy.linalg as nla\n'), ((15558, 15575), 'numpy.array', 'nm.array', (['[False]'], {}), '([False])\n', (15566, 15575), True, 'import numpy as nm\n'), ((17224, 17258), 'numpy.array', 'nm.array', (['centre'], {'dtype': 'nm.float64'}), '(centre, dtype=nm.float64)\n', (17232, 17258), True, 'import numpy as nm\n'), ((17276, 17310), 'numpy.array', 'nm.array', (['normal'], {'dtype': 'nm.float64'}), '(normal, dtype=nm.float64)\n', (17284, 17310), True, 'import numpy as nm\n'), ((17329, 17345), 'numpy.linalg.norm', 'nla.norm', (['normal'], {}), '(normal)\n', (17337, 17345), True, 'import numpy.linalg as nla\n'), ((19627, 19720), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'name': 'name', 'problem': 'problem', 'expressions': 'expressions', 'labels': 'labels'}), '(self, name=name, problem=problem, expressions=expressions,\n labels=labels)\n', (19642, 19720), False, 'from sfepy.base.base import get_default, basestr, Struct\n'), ((999, 1040), 'numpy.hstack', 'nm.hstack', (['(pars[:, None], vals[:, None])'], {}), '((pars[:, None], vals[:, None]))\n', (1008, 1040), True, 'import numpy as nm\n'), ((1072, 1104), 'numpy.hstack', 'nm.hstack', (['(pars[:, None], vals)'], {}), '((pars[:, None], vals))\n', (1081, 1104), True, 'import numpy as nm\n'), ((9320, 9337), 'numpy.array', 'nm.array', (['[False]'], {}), '([False])\n', (9328, 9337), True, 'import numpy as nm\n'), ((9591, 9635), 'sfepy.linalg.norm_l2_along_axis', 'norm_l2_along_axis', (['(points[1:] - points[:-1])'], {}), '(points[1:] - points[:-1])\n', (9609, 9635), False, 'from sfepy.linalg import make_axis_rotation_matrix, norm_l2_along_axis\n'), ((10077, 10098), 'numpy.where', 'nm.where', (['refine_flag'], {}), '(refine_flag)\n', (10085, 10098), True, 'import numpy as nm\n'), ((13483, 13524), 'numpy.linspace', 'nm.linspace', (['(0)', 'self.length', 'self.n_point'], {}), '(0, self.length, self.n_point)\n', (13494, 13524), True, 'import numpy as nm\n'), ((15729, 15777), 'numpy.arange', 'nm.arange', (['self.n_point_single'], {'dtype': 'nm.float64'}), '(self.n_point_single, dtype=nm.float64)\n', (15738, 15777), True, 'import numpy as nm\n'), ((16298, 16334), 'numpy.concatenate', 'nm.concatenate', (['(-pars0[::-1], pars)'], {}), '((-pars0[::-1], pars))\n', (16312, 16334), True, 'import numpy as nm\n'), ((16356, 16395), 'numpy.concatenate', 'nm.concatenate', (['(points0[::-1], points)'], {}), '((points0[::-1], points))\n', (16370, 16395), True, 'import numpy as nm\n'), ((18665, 18686), 'numpy.cos', 'nm.cos', (['pars[:, None]'], {}), '(pars[:, None])\n', (18671, 18686), True, 'import numpy as nm\n'), ((18712, 18733), 'numpy.sin', 'nm.sin', (['pars[:, None]'], {}), '(pars[:, None])\n', (18718, 18733), True, 'import numpy as nm\n'), ((18784, 18829), 'numpy.zeros', 'nm.zeros', (['(self.n_point, 1)'], {'dtype': 'nm.float64'}), '((self.n_point, 1), dtype=nm.float64)\n', (18792, 18829), True, 'import numpy as nm\n'), ((18949, 18992), 'numpy.array', 'nm.array', (['[0.0, 0.0, 1.0]'], {'dtype': 'nm.float64'}), '([0.0, 0.0, 1.0], dtype=nm.float64)\n', (18957, 18992), True, 'import numpy as nm\n'), ((19012, 19037), 'numpy.cross', 'nm.cross', (['n1', 'self.normal'], {}), '(n1, self.normal)\n', (19020, 19037), True, 'import numpy as nm\n'), ((19326, 19349), 'numpy.dot', 'nm.dot', (['points', 'rot_mtx'], {}), '(points, rot_mtx)\n', (19332, 19349), True, 'import numpy as nm\n'), ((9773, 9805), 'numpy.linalg.norm', 'nla.norm', (['(points[0] - points[-1])'], {}), '(points[0] - points[-1])\n', (9781, 9805), True, 'import numpy.linalg as nla\n'), ((18317, 18364), 'numpy.linspace', 'nm.linspace', (['(0.0)', '(2.0 * nm.pi)', '(self.n_point + 1)'], {}), '(0.0, 2.0 * nm.pi, self.n_point + 1)\n', (18328, 18364), True, 'import numpy as nm\n'), ((19068, 19091), 'numpy.dot', 'nm.dot', (['n1', 'self.normal'], {}), '(n1, self.normal)\n', (19074, 19091), True, 'import numpy as nm\n'), ((19109, 19123), 'numpy.linalg.norm', 'nla.norm', (['axis'], {}), '(axis)\n', (19117, 19123), True, 'import numpy.linalg as nla\n'), ((19193, 19220), 'numpy.eye', 'nm.eye', (['(3)'], {'dtype': 'nm.float64'}), '(3, dtype=nm.float64)\n', (19199, 19220), True, 'import numpy as nm\n'), ((19265, 19303), 'sfepy.linalg.make_axis_rotation_matrix', 'make_axis_rotation_matrix', (['axis', 'angle'], {}), '(axis, angle)\n', (19290, 19303), False, 'from sfepy.linalg import make_axis_rotation_matrix, norm_l2_along_axis\n'), ((8032, 8051), 'numpy.isfinite', 'nm.isfinite', (['points'], {}), '(points)\n', (8043, 8051), True, 'import numpy as nm\n')] |
#!/usr/bin/env python
"""
Compare various elastic materials w.r.t. uniaxial tension/compression test.
Requires Matplotlib.
"""
from optparse import OptionParser
import sys
sys.path.append('.')
import numpy as nm
def define():
"""Define the problem to solve."""
from sfepy.discrete.fem.meshio import UserMeshIO
from sfepy.mesh.mesh_generators import gen_block_mesh
from sfepy.mechanics.matcoefs import stiffness_from_lame
def mesh_hook(mesh, mode):
"""
Generate the block mesh.
"""
if mode == 'read':
mesh = gen_block_mesh([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3',
verbose=False)
return mesh
elif mode == 'write':
pass
filename_mesh = UserMeshIO(mesh_hook)
options = {
'nls' : 'newton',
'ls' : 'ls',
'ts' : 'ts',
'save_steps' : -1,
}
functions = {
'linear_tension' : (linear_tension,),
'linear_compression' : (linear_compression,),
'empty' : (lambda ts, coor, mode, region, ig: None,),
}
fields = {
'displacement' : ('real', 3, 'Omega', 1),
}
# Coefficients are chosen so that the tangent stiffness is the same for all
# material for zero strains.
# Young modulus = 10 kPa, Poisson's ratio = 0.3
materials = {
'solid' : ({
'K' : 8.333, # bulk modulus
'mu_nh' : 3.846, # shear modulus of neoHookean term
'mu_mr' : 1.923, # shear modulus of Mooney-Rivlin term
'kappa' : 1.923, # second modulus of Mooney-Rivlin term
# elasticity for LE term
'D' : stiffness_from_lame(dim=3, lam=5.769, mu=3.846),
},),
'load' : 'empty',
}
variables = {
'u' : ('unknown field', 'displacement', 0),
'v' : ('test field', 'displacement', 'u'),
}
regions = {
'Omega' : 'all',
'Bottom' : ('vertices in (z < 0.1)', 'facet'),
'Top' : ('vertices in (z > 2.9)', 'facet'),
}
ebcs = {
'fixb' : ('Bottom', {'u.all' : 0.0}),
'fixt' : ('Top', {'u.[0,1]' : 0.0}),
}
integrals = {
'i' : 1,
'isurf' : 2,
}
equations = {
'linear' : """dw_lin_elastic.i.Omega(solid.D, v, u)
= dw_surface_ltr.isurf.Top(load.val, v)""",
'neo-Hookean' : """dw_tl_he_neohook.i.Omega(solid.mu_nh, v, u)
+ dw_tl_bulk_penalty.i.Omega(solid.K, v, u)
= dw_surface_ltr.isurf.Top(load.val, v)""",
'Mooney-Rivlin' : """dw_tl_he_neohook.i.Omega(solid.mu_mr, v, u)
+ dw_tl_he_mooney_rivlin.i.Omega(solid.kappa, v, u)
+ dw_tl_bulk_penalty.i.Omega(solid.K, v, u)
= dw_surface_ltr.isurf.Top(load.val, v)""",
}
solvers = {
'ls' : ('ls.scipy_direct', {}),
'newton' : ('nls.newton', {
'i_max' : 5,
'eps_a' : 1e-10,
'eps_r' : 1.0,
}),
'ts' : ('ts.simple', {
't0' : 0,
't1' : 1,
'dt' : None,
'n_step' : 101, # has precedence over dt!
}),
}
return locals()
##
# Pressure tractions.
def linear_tension(ts, coor, mode=None, **kwargs):
if mode == 'qp':
val = nm.tile(0.1 * ts.step, (coor.shape[0], 1, 1))
return {'val' : val}
def linear_compression(ts, coor, mode=None, **kwargs):
if mode == 'qp':
val = nm.tile(-0.1 * ts.step, (coor.shape[0], 1, 1))
return {'val' : val}
def store_top_u(displacements):
"""Function _store() will be called at the end of each loading step. Top
displacements will be stored into `displacements`."""
def _store(problem, ts, state):
top = problem.domain.regions['Top']
top_u = problem.get_variables()['u'].get_state_in_region(top)
displacements.append(nm.mean(top_u[:,-1]))
return _store
def solve_branch(problem, branch_function):
displacements = {}
for key, eq in problem.conf.equations.iteritems():
problem.set_equations({key : eq})
load = problem.get_materials()['load']
load.set_function(branch_function)
time_solver = problem.get_time_solver()
time_solver.init_time()
out = []
for _ in time_solver(save_results=False, step_hook=store_top_u(out)):
pass
displacements[key] = nm.array(out, dtype=nm.float64)
return displacements
usage = '%prog [options]\n' + __doc__.rstrip()
helps = {
'no_plot' : 'do not show plot window',
}
def main():
from sfepy.base.base import output
from sfepy.base.conf import ProblemConf, get_standard_keywords
from sfepy.discrete import Problem
from sfepy.base.plotutils import plt
parser = OptionParser(usage=usage, version='%prog')
parser.add_option('-n', '--no-plot',
action="store_true", dest='no_plot',
default=False, help=helps['no_plot'])
options, args = parser.parse_args()
required, other = get_standard_keywords()
# Use this file as the input file.
conf = ProblemConf.from_file(__file__, required, other)
# Create problem instance, but do not set equations.
problem = Problem.from_conf(conf, init_equations=False)
# Solve the problem. Output is ignored, results stored by using the
# step_hook.
u_t = solve_branch(problem, linear_tension)
u_c = solve_branch(problem, linear_compression)
# Get pressure load by calling linear_*() for each time step.
ts = problem.get_timestepper()
load_t = nm.array([linear_tension(ts, nm.array([[0.0]]), 'qp')['val']
for aux in ts.iter_from(0)],
dtype=nm.float64).squeeze()
load_c = nm.array([linear_compression(ts, nm.array([[0.0]]), 'qp')['val']
for aux in ts.iter_from(0)],
dtype=nm.float64).squeeze()
# Join the branches.
displacements = {}
for key in u_t.keys():
displacements[key] = nm.r_[u_c[key][::-1], u_t[key]]
load = nm.r_[load_c[::-1], load_t]
if plt is None:
output('matplotlib cannot be imported, printing raw data!')
output(displacements)
output(load)
else:
legend = []
for key, val in displacements.iteritems():
plt.plot(load, val)
legend.append(key)
plt.legend(legend, loc = 2)
plt.xlabel('tension [kPa]')
plt.ylabel('displacement [mm]')
plt.grid(True)
plt.gcf().savefig('pressure_displacement.png')
if not options.no_plot:
plt.show()
if __name__ == '__main__':
main()
| [
"sfepy.base.plotutils.plt.ylabel",
"sfepy.mesh.mesh_generators.gen_block_mesh",
"sfepy.base.plotutils.plt.xlabel",
"sfepy.base.plotutils.plt.legend",
"sfepy.base.conf.ProblemConf.from_file",
"sfepy.discrete.fem.meshio.UserMeshIO",
"sfepy.base.plotutils.plt.grid",
"sfepy.base.plotutils.plt.plot",
"sf... | [((173, 193), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (188, 193), False, 'import sys\n'), ((779, 800), 'sfepy.discrete.fem.meshio.UserMeshIO', 'UserMeshIO', (['mesh_hook'], {}), '(mesh_hook)\n', (789, 800), False, 'from sfepy.discrete.fem.meshio import UserMeshIO\n'), ((4880, 4922), 'optparse.OptionParser', 'OptionParser', ([], {'usage': 'usage', 'version': '"""%prog"""'}), "(usage=usage, version='%prog')\n", (4892, 4922), False, 'from optparse import OptionParser\n'), ((5146, 5169), 'sfepy.base.conf.get_standard_keywords', 'get_standard_keywords', ([], {}), '()\n', (5167, 5169), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((5220, 5268), 'sfepy.base.conf.ProblemConf.from_file', 'ProblemConf.from_file', (['__file__', 'required', 'other'], {}), '(__file__, required, other)\n', (5241, 5268), False, 'from sfepy.base.conf import ProblemConf, get_standard_keywords\n'), ((5341, 5386), 'sfepy.discrete.Problem.from_conf', 'Problem.from_conf', (['conf'], {'init_equations': '(False)'}), '(conf, init_equations=False)\n', (5358, 5386), False, 'from sfepy.discrete import Problem\n'), ((3395, 3440), 'numpy.tile', 'nm.tile', (['(0.1 * ts.step)', '(coor.shape[0], 1, 1)'], {}), '(0.1 * ts.step, (coor.shape[0], 1, 1))\n', (3402, 3440), True, 'import numpy as nm\n'), ((3561, 3607), 'numpy.tile', 'nm.tile', (['(-0.1 * ts.step)', '(coor.shape[0], 1, 1)'], {}), '(-0.1 * ts.step, (coor.shape[0], 1, 1))\n', (3568, 3607), True, 'import numpy as nm\n'), ((4506, 4537), 'numpy.array', 'nm.array', (['out'], {'dtype': 'nm.float64'}), '(out, dtype=nm.float64)\n', (4514, 4537), True, 'import numpy as nm\n'), ((6241, 6300), 'sfepy.base.base.output', 'output', (['"""matplotlib cannot be imported, printing raw data!"""'], {}), "('matplotlib cannot be imported, printing raw data!')\n", (6247, 6300), False, 'from sfepy.base.base import output\n'), ((6309, 6330), 'sfepy.base.base.output', 'output', (['displacements'], {}), '(displacements)\n', (6315, 6330), False, 'from sfepy.base.base import output\n'), ((6339, 6351), 'sfepy.base.base.output', 'output', (['load'], {}), '(load)\n', (6345, 6351), False, 'from sfepy.base.base import output\n'), ((6505, 6530), 'sfepy.base.plotutils.plt.legend', 'plt.legend', (['legend'], {'loc': '(2)'}), '(legend, loc=2)\n', (6515, 6530), False, 'from sfepy.base.plotutils import plt\n'), ((6541, 6568), 'sfepy.base.plotutils.plt.xlabel', 'plt.xlabel', (['"""tension [kPa]"""'], {}), "('tension [kPa]')\n", (6551, 6568), False, 'from sfepy.base.plotutils import plt\n'), ((6577, 6608), 'sfepy.base.plotutils.plt.ylabel', 'plt.ylabel', (['"""displacement [mm]"""'], {}), "('displacement [mm]')\n", (6587, 6608), False, 'from sfepy.base.plotutils import plt\n'), ((6617, 6631), 'sfepy.base.plotutils.plt.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (6625, 6631), False, 'from sfepy.base.plotutils import plt\n'), ((575, 651), 'sfepy.mesh.mesh_generators.gen_block_mesh', 'gen_block_mesh', (['[2, 2, 3]', '[2, 2, 4]', '[0, 0, 1.5]'], {'name': '"""el3"""', 'verbose': '(False)'}), "([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3', verbose=False)\n", (589, 651), False, 'from sfepy.mesh.mesh_generators import gen_block_mesh\n'), ((3986, 4007), 'numpy.mean', 'nm.mean', (['top_u[:, -1]'], {}), '(top_u[:, -1])\n', (3993, 4007), True, 'import numpy as nm\n'), ((6445, 6464), 'sfepy.base.plotutils.plt.plot', 'plt.plot', (['load', 'val'], {}), '(load, val)\n', (6453, 6464), False, 'from sfepy.base.plotutils import plt\n'), ((6733, 6743), 'sfepy.base.plotutils.plt.show', 'plt.show', ([], {}), '()\n', (6741, 6743), False, 'from sfepy.base.plotutils import plt\n'), ((1678, 1725), 'sfepy.mechanics.matcoefs.stiffness_from_lame', 'stiffness_from_lame', ([], {'dim': '(3)', 'lam': '(5.769)', 'mu': '(3.846)'}), '(dim=3, lam=5.769, mu=3.846)\n', (1697, 1725), False, 'from sfepy.mechanics.matcoefs import stiffness_from_lame\n'), ((6641, 6650), 'sfepy.base.plotutils.plt.gcf', 'plt.gcf', ([], {}), '()\n', (6648, 6650), False, 'from sfepy.base.plotutils import plt\n'), ((5721, 5738), 'numpy.array', 'nm.array', (['[[0.0]]'], {}), '([[0.0]])\n', (5729, 5738), True, 'import numpy as nm\n'), ((5901, 5918), 'numpy.array', 'nm.array', (['[[0.0]]'], {}), '([[0.0]])\n', (5909, 5918), True, 'import numpy as nm\n')] |
r"""
Thermo-elasticity with a computed temperature demonstrating equation sequence
solver.
Uses `dw_biot` term with an isotropic coefficient for thermo-elastic coupling.
The equation sequence solver (``'ess'`` in ``solvers``) automatically solves
first the temperature distribution and then the elasticity problem with the
already computed temperature.
Find :math:`\ul{u}`, :math:`T` such that:
.. math::
\int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u})
- \int_{\Omega} (T - T_0)\ \alpha_{ij} e_{ij}(\ul{v})
= 0
\;, \quad \forall \ul{v} \;,
\int_{\Omega} \nabla s \cdot \nabla T
= 0
\;, \quad \forall s \;.
where
.. math::
D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) +
\lambda \ \delta_{ij} \delta_{kl}
\;, \\
\alpha_{ij} = (3 \lambda + 2 \mu) \alpha \delta_{ij} \;,
:math:`T_0` is the background temperature and :math:`\alpha` is the thermal
expansion coefficient.
Notes
-----
The gallery image was produced by (plus proper view settings)::
./postproc.py block.vtk -d'u,plot_displacements,rel_scaling=1000,color_kind="scalars",color_name="T"' --wireframe --only-names=u -b
"""
import numpy as np
from sfepy.mechanics.matcoefs import stiffness_from_lame
from sfepy import data_dir
# Material parameters.
lam = 10.0
mu = 5.0
thermal_expandability = 1.25e-5
T0 = 20.0 # Background temperature.
filename_mesh = data_dir + '/meshes/3d/block.mesh'
options = {
'ts' : 'ess',
'nls' : 'newton',
'ls' : 'ls',
}
regions = {
'Omega' : 'all',
'Left' : ('vertices in (x < -4.99)', 'facet'),
'Right' : ('vertices in (x > 4.99)', 'facet'),
'Bottom' : ('vertices in (z < -0.99)', 'facet'),
}
fields = {
'displacement': ('real', 3, 'Omega', 1),
'temperature': ('real', 1, 'Omega', 1),
}
variables = {
'u' : ('unknown field', 'displacement', 0),
'v' : ('test field', 'displacement', 'u'),
'T' : ('unknown field', 'temperature', 1),
's' : ('test field', 'temperature', 'T'),
}
ebcs = {
'u0' : ('Left', {'u.all' : 0.0}),
't0' : ('Left', {'T.0' : 20.0}),
't2' : ('Bottom', {'T.0' : 0.0}),
't1' : ('Right', {'T.0' : 30.0}),
}
eye_sym = np.array([[1], [1], [1], [0], [0], [0]], dtype=np.float64)
materials = {
'solid' : ({
'D' : stiffness_from_lame(3, lam=lam, mu=mu),
'alpha' : (3.0 * lam + 2.0 * mu) * thermal_expandability * eye_sym
},),
}
equations = {
'balance_of_forces' : """
+ dw_lin_elastic.2.Omega(solid.D, v, u)
- dw_biot.2.Omega(solid.alpha, v, T)
= 0
""",
'temperature' : """
+ dw_laplace.1.Omega(s, T)
= 0
"""
}
solvers = {
'ls' : ('ls.scipy_direct', {}),
'newton' : ('nls.newton', {
'i_max' : 1,
'eps_a' : 1e-10,
'problem' : 'nonlinear',
}),
'ess' : ('ts.equation_sequence', {}),
}
| [
"sfepy.mechanics.matcoefs.stiffness_from_lame"
] | [((2177, 2235), 'numpy.array', 'np.array', (['[[1], [1], [1], [0], [0], [0]]'], {'dtype': 'np.float64'}), '([[1], [1], [1], [0], [0], [0]], dtype=np.float64)\n', (2185, 2235), True, 'import numpy as np\n'), ((2281, 2319), 'sfepy.mechanics.matcoefs.stiffness_from_lame', 'stiffness_from_lame', (['(3)'], {'lam': 'lam', 'mu': 'mu'}), '(3, lam=lam, mu=mu)\n', (2300, 2319), False, 'from sfepy.mechanics.matcoefs import stiffness_from_lame\n')] |
from copy import copy
from sfepy.base.base import output, get_default, Struct
from sfepy.applications import PDESolverApp, Application
from coefs_base import MiniAppBase
def insert_sub_reqs(reqs, levels, req_info):
"""Recursively build all requirements in correct order."""
all_reqs = []
for _, req in enumerate(reqs):
# Coefficients are referenced as 'c.<name>'...
areq = req
if req.startswith('c.'):
areq = req[2:]
try:
rargs = req_info[areq]
except KeyError:
raise ValueError('requirement "%s" is not defined!' % req)
sub_reqs = rargs.get('requires', [])
if req in levels:
raise ValueError('circular requirement "%s"!' % (req))
if sub_reqs:
levels.append(req)
all_reqs.extend(insert_sub_reqs(sub_reqs, levels, req_info))
levels.pop()
if req in all_reqs:
raise ValueError('circular requirement "%s"!' % (req))
else:
all_reqs.append(req)
return all_reqs
class HomogenizationEngine(PDESolverApp):
@staticmethod
def process_options(options):
get = options.get
return Struct(coefs=get('coefs', None,
'missing "coefs" in options!'),
requirements=get('requirements', None,
'missing "requirements" in options!'),
compute_only=get('compute_only', None),
save_format=get('save_format', 'vtk'),
dump_format=get('dump_format', 'h5'),
coefs_info=get('coefs_info', None))
def __init__(self, problem, options, app_options=None,
volume=None, output_prefix='he:', **kwargs):
"""Bypasses PDESolverApp.__init__()!"""
Application.__init__(self, problem.conf, options, output_prefix,
**kwargs)
self.problem = problem
self.setup_options(app_options=app_options)
self.setup_output_info(self.problem, self.options)
if volume is None:
self.volume = self.problem.evaluate(self.app_options.total_volume)
else:
self.volume = volume
def setup_options(self, app_options=None):
PDESolverApp.setup_options(self)
app_options = get_default(app_options, self.conf.options)
po = HomogenizationEngine.process_options
self.app_options += po(app_options)
def compute_requirements(self, requirements, dependencies, store):
problem = self.problem
opts = self.app_options
req_info = getattr(self.conf, opts.requirements)
requires = insert_sub_reqs(copy(requirements), [], req_info)
for req in requires:
if req in dependencies and (dependencies[req] is not None):
continue
output('computing dependency %s...' % req)
rargs = req_info[req]
mini_app = MiniAppBase.any_from_conf(req, problem, rargs)
mini_app.setup_output(save_format=opts.save_format,
dump_format=opts.dump_format,
post_process_hook=self.post_process_hook,
file_per_var=opts.file_per_var)
store(mini_app)
problem.clear_equations()
# Pass only the direct dependencies, not the indirect ones.
dep_requires = rargs.get('requires', [])
data = {}
for key in dep_requires:
data[key] = dependencies[key]
dep = mini_app(data=data)
dependencies[req] = dep
output('...done')
return dependencies
def call(self, ret_all=False):
problem = self.problem
opts = self.app_options
coef_info = getattr(self.conf, opts.coefs)
compute_names = set(get_default(opts.compute_only, coef_info.keys()))
compute_names = ['c.' + key for key in compute_names]
is_store_filenames = coef_info.pop('filenames', None) is not None
try:
compute_names.remove('c.filenames')
except:
pass
dependencies = {}
save_names = {}
dump_names = {}
def store_filenames(app):
if not '(not_set)' in app.get_save_name_base():
save_names[app.name] = app.get_save_name_base()
if not '(not_set)' in app.get_dump_name_base():
dump_names[app.name] = app.get_dump_name_base()
# Some coefficients can require other coefficients - resolve their
# order here.
req_info = self.conf.get(opts.requirements, {})
info = copy(coef_info)
info.update(req_info)
all_deps = set(compute_names)
sorted_names = []
for coef_name in compute_names:
cargs = coef_info[coef_name[2:]]
requires = cargs.get('requires', [])
deps = insert_sub_reqs(copy(requires), [], info)
all_deps.update(deps)
aux = [key for key in deps if key.startswith('c.')] + [coef_name]
sorted_names.extend(aux)
sorted_coef_names = []
for name in sorted_names:
if name[2:] not in sorted_coef_names:
sorted_coef_names.append(name[2:])
coefs = Struct()
for coef_name in sorted_coef_names:
cargs = coef_info[coef_name]
output('computing %s...' % coef_name)
requires = cargs.get('requires', [])
requirements = [name for name in requires if not
name.startswith('c.')]
self.compute_requirements(requirements, dependencies,
store_filenames)
for name in requires:
if name.startswith('c.'):
dependencies[name] = getattr(coefs, name[2:])
mini_app = MiniAppBase.any_from_conf(coef_name, problem, cargs)
problem.clear_equations()
# Pass only the direct dependencies, not the indirect ones.
data = {}
for key in requires:
data[key] = dependencies[key]
val = mini_app(self.volume, data=data)
setattr(coefs, coef_name, val)
output('...done')
# remove "auxiliary" coefs
for coef_name in sorted_coef_names:
cstat = coef_info[coef_name].get('status', 'main')
if cstat == 'auxiliary':
delattr(coefs, coef_name)
# Store filenames of all requirements as a "coefficient".
if is_store_filenames:
coefs.save_names = save_names
coefs.dump_names = dump_names
if opts.coefs_info is not None:
coefs.info = opts.coefs_info
if ret_all:
return coefs, dependencies
else:
return coefs
| [
"sfepy.base.base.output",
"sfepy.applications.Application.__init__",
"sfepy.base.base.Struct",
"sfepy.applications.PDESolverApp.setup_options",
"sfepy.base.base.get_default"
] | [((1859, 1933), 'sfepy.applications.Application.__init__', 'Application.__init__', (['self', 'problem.conf', 'options', 'output_prefix'], {}), '(self, problem.conf, options, output_prefix, **kwargs)\n', (1879, 1933), False, 'from sfepy.applications import PDESolverApp, Application\n'), ((2316, 2348), 'sfepy.applications.PDESolverApp.setup_options', 'PDESolverApp.setup_options', (['self'], {}), '(self)\n', (2342, 2348), False, 'from sfepy.applications import PDESolverApp, Application\n'), ((2371, 2414), 'sfepy.base.base.get_default', 'get_default', (['app_options', 'self.conf.options'], {}), '(app_options, self.conf.options)\n', (2382, 2414), False, 'from sfepy.base.base import output, get_default, Struct\n'), ((4753, 4768), 'copy.copy', 'copy', (['coef_info'], {}), '(coef_info)\n', (4757, 4768), False, 'from copy import copy\n'), ((5392, 5400), 'sfepy.base.base.Struct', 'Struct', ([], {}), '()\n', (5398, 5400), False, 'from sfepy.base.base import output, get_default, Struct\n'), ((2739, 2757), 'copy.copy', 'copy', (['requirements'], {}), '(requirements)\n', (2743, 2757), False, 'from copy import copy\n'), ((2913, 2955), 'sfepy.base.base.output', 'output', (["('computing dependency %s...' % req)"], {}), "('computing dependency %s...' % req)\n", (2919, 2955), False, 'from sfepy.base.base import output, get_default, Struct\n'), ((3015, 3061), 'coefs_base.MiniAppBase.any_from_conf', 'MiniAppBase.any_from_conf', (['req', 'problem', 'rargs'], {}), '(req, problem, rargs)\n', (3040, 3061), False, 'from coefs_base import MiniAppBase\n'), ((3718, 3735), 'sfepy.base.base.output', 'output', (['"""...done"""'], {}), "('...done')\n", (3724, 3735), False, 'from sfepy.base.base import output, get_default, Struct\n'), ((5498, 5535), 'sfepy.base.base.output', 'output', (["('computing %s...' % coef_name)"], {}), "('computing %s...' % coef_name)\n", (5504, 5535), False, 'from sfepy.base.base import output, get_default, Struct\n'), ((5986, 6038), 'coefs_base.MiniAppBase.any_from_conf', 'MiniAppBase.any_from_conf', (['coef_name', 'problem', 'cargs'], {}), '(coef_name, problem, cargs)\n', (6011, 6038), False, 'from coefs_base import MiniAppBase\n'), ((6359, 6376), 'sfepy.base.base.output', 'output', (['"""...done"""'], {}), "('...done')\n", (6365, 6376), False, 'from sfepy.base.base import output, get_default, Struct\n'), ((5032, 5046), 'copy.copy', 'copy', (['requires'], {}), '(requires)\n', (5036, 5046), False, 'from copy import copy\n')] |
# 26.02.2007, c
# last revision: 25.02.2008
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/3d/elbow2.mesh'
options = {
'nls' : 'newton',
'ls' : 'ls',
'post_process_hook' : 'verify_incompressibility',
}
field_1 = {
'name' : '3_velocity',
'dtype' : 'real',
'shape' : (3,),
'region' : 'Omega',
'approx_order' : '1B',
}
field_2 = {
'name' : 'pressure',
'dtype' : 'real',
'shape' : (1,),
'region' : 'Omega',
'approx_order' : 1,
}
# Can use logical operations '&' (and), '|' (or).
region_1000 = {
'name' : 'Omega',
'select' : 'elements of group 6',
}
region_0 = {
'name' : 'Walls',
'select' : 'nodes of surface -n (r.Outlet +n r.Inlet)',
'can_cells' : False,
}
region_1 = {
'name' : 'Inlet',
'select' : 'nodes by cinc0', # In
'can_cells' : False,
}
region_2 = {
'name' : 'Outlet',
'select' : 'nodes by cinc1', # Out
'can_cells' : False,
}
ebc_1 = {
'name' : 'Walls',
'region' : 'Walls',
'dofs' : {'u.all' : 0.0},
}
ebc_2 = {
'name' : 'Inlet',
'region' : 'Inlet',
'dofs' : {'u.1' : 1.0, 'u.[0,2]' : 0.0},
}
material_1 = {
'name' : 'fluid',
'values' : {
'viscosity' : 1.25e-3,
'density' : 1e0,
},
}
variable_1 = {
'name' : 'u',
'kind' : 'unknown field',
'field' : '3_velocity',
'order' : 0,
}
variable_2 = {
'name' : 'v',
'kind' : 'test field',
'field' : '3_velocity',
'dual' : 'u',
}
variable_3 = {
'name' : 'p',
'kind' : 'unknown field',
'field' : 'pressure',
'order' : 1,
}
variable_4 = {
'name' : 'q',
'kind' : 'test field',
'field' : 'pressure',
'dual' : 'p',
}
variable_5 = {
'name' : 'pp',
'kind' : 'parameter field',
'field' : 'pressure',
'like' : 'p',
}
integral_1 = {
'name' : 'i1',
'kind' : 'v',
'quadrature' : 'gauss_o2_d3',
}
integral_2 = {
'name' : 'i2',
'kind' : 'v',
'quadrature' : 'gauss_o3_d3',
}
##
# Stationary Navier-Stokes equations.
equations = {
'balance' :
"""+ dw_div_grad.i2.Omega( fluid.viscosity, v, u )
+ dw_convect.i2.Omega( v, u )
- dw_stokes.i1.Omega( v, p ) = 0""",
'incompressibility' :
"""dw_stokes.i1.Omega( u, q ) = 0""",
}
##
# FE assembling parameters.
fe = {
'chunk_size' : 1000
}
solver_0 = {
'name' : 'ls',
'kind' : 'ls.scipy_direct',
}
solver_1 = {
'name' : 'newton',
'kind' : 'nls.newton',
'i_max' : 5,
'eps_a' : 1e-8,
'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' : 0.99999,
'ls_min' : 1e-5,
'check' : 0,
'delta' : 1e-6,
'is_plot' : False,
'problem' : 'nonlinear', # 'nonlinear' or 'linear' (ignore i_max)
}
def verify_incompressibility( out, problem, state, extend = False ):
"""This hook is normally used for post-processing (additional results can
be inserted into `out` dictionary), but here we just verify the weak
incompressibility condition."""
from sfepy.base.base import Struct, debug, nm, output, assert_
vv = problem.get_variables()
one = nm.ones( (vv['p'].field.n_nod,), dtype = nm.float64 )
vv['p'].data_from_any( one )
zero = problem.evaluate('dw_stokes.i1.Omega( u, p )', p=one, u=vv['u'](),
call_mode='d_eval')
output('div( u ) = %.3e' % zero)
assert_(abs(zero) < 1e-14)
return out
##
# Functions.
import os.path as op
import utils
cinc_name = 'cinc_' + op.splitext(op.basename(filename_mesh))[0]
cinc = getattr(utils, cinc_name)
functions = {
'cinc0' : (lambda coors, domain=None: cinc(coors, 0),),
'cinc1' : (lambda coors, domain=None: cinc(coors, 1),),
}
| [
"sfepy.base.base.output",
"sfepy.base.base.nm.ones"
] | [((3241, 3290), 'sfepy.base.base.nm.ones', 'nm.ones', (["(vv['p'].field.n_nod,)"], {'dtype': 'nm.float64'}), "((vv['p'].field.n_nod,), dtype=nm.float64)\n", (3248, 3290), False, 'from sfepy.base.base import Struct, debug, nm, output, assert_\n'), ((3458, 3490), 'sfepy.base.base.output', 'output', (["('div( u ) = %.3e' % zero)"], {}), "('div( u ) = %.3e' % zero)\n", (3464, 3490), False, 'from sfepy.base.base import Struct, debug, nm, output, assert_\n'), ((3625, 3651), 'os.path.basename', 'op.basename', (['filename_mesh'], {}), '(filename_mesh)\n', (3636, 3651), True, 'import os.path as op\n')] |
from __future__ import absolute_import
import numpy as nm
import sfepy.linalg as la
from sfepy.discrete.integrals import Integral
from sfepy.discrete import PolySpace
from six.moves import range
def prepare_remap(indices, n_full):
"""
Prepare vector for remapping range `[0, n_full]` to its subset given
by `indices`.
"""
remap = nm.empty((n_full,), dtype=nm.int32)
remap.fill(-1)
remap[indices] = nm.arange(indices.shape[0], dtype=nm.int32)
return remap
def invert_remap(remap):
"""
Return the inverse of `remap`, i.e. a mapping from a sub-range
indices to a full range, see :func:`prepare_remap()`.
"""
if remap is not None:
inverse = nm.where(remap >= 0)[0].astype(nm.int32)
else:
inverse = None
return inverse
def prepare_translate(old_indices, new_indices):
"""
Prepare vector for translating `old_indices` to `new_indices`.
Returns
-------
translate : array
The translation vector. Then `new_ar = translate[old_ar]`.
"""
old_indices = nm.asarray(old_indices)
new_indices = nm.asarray(new_indices)
translate = nm.zeros(old_indices.max() + 1, dtype=new_indices.dtype)
translate[old_indices] = new_indices
return translate
def compute_nodal_normals(nodes, region, field, return_imap=False):
"""
Nodal normals are computed by simple averaging of element normals of
elements every node is contained in.
"""
dim = region.dim
field.domain.create_surface_group(region)
field.setup_surface_data(region)
# Custom integral with quadrature points in nodes.
ps = PolySpace.any_from_args('', field.gel.surface_facet,
field.approx_order)
qp_coors = ps.node_coors
# Unit normals -> weights = ones.
qp_weights = nm.ones(qp_coors.shape[0], dtype=nm.float64)
integral = Integral('aux', coors=qp_coors, weights=qp_weights)
normals = nm.zeros((nodes.shape[0], dim), dtype=nm.float64)
mask = nm.zeros((nodes.max() + 1,), dtype=nm.int32)
imap = nm.empty_like(mask)
imap.fill(nodes.shape[0]) # out-of-range index for normals.
imap[nodes] = nm.arange(nodes.shape[0], dtype=nm.int32)
cmap, _ = field.get_mapping(region, integral, 'surface')
e_normals = cmap.normal[..., 0]
sd = field.surface_data[region.name]
econn = sd.get_connectivity()
mask[econn] += 1
# normals[imap[econn]] += e_normals
im = imap[econn]
for ii, en in enumerate(e_normals):
normals[im[ii]] += en
# All nodes must have a normal.
if not nm.all(mask[nodes] > 0):
raise ValueError('region %s has not complete faces!' % region.name)
norm = la.norm_l2_along_axis(normals)[:, nm.newaxis]
if (norm < 1e-15).any():
raise ValueError('zero nodal normal! (a node in volume?)')
normals /= norm
if return_imap:
return normals, imap
else:
return normals
def _get_edge_path(graph, seed, mask, cycle=False):
"""
Get a path in an edge graph starting with seed. The mask is incremented by
one at positions of the path vertices.
"""
if mask[seed]:
return []
path = [seed]
mask[seed] = 1
row = graph[seed].indices
nv = len(row)
while nv:
if nv == 2:
if mask[row[0]]:
if mask[row[1]]:
if cycle:
path.append(seed)
break
else:
vert = row[1]
else:
vert = row[0]
elif mask[row[0]]:
break
else:
vert = row[0]
path.append(vert)
mask[vert] = 1
row = graph[vert].indices
nv = len(row)
path = nm.array(path, dtype=nm.int32)
return path
def get_edge_paths(graph, mask):
"""
Get all edge paths in a graph with non-masked vertices. The mask is
updated.
"""
nodes = nm.unique(graph.indices)
npv = nm.diff(graph.indptr)
if npv.max() > 2:
raise ValueError('more than 2 edges sharing a vertex!')
seeds = nm.where(npv == 1)[0]
# 1. get paths.
paths = []
for seed in seeds:
path = _get_edge_path(graph, seed, mask)
if len(path):
paths.append(path)
# 2. get possible remaing cycles.
while 1:
ii = nm.where(mask[nodes] == 0)[0]
if not len(ii):
break
path = _get_edge_path(graph, nodes[ii[0]], mask, cycle=True)
if len(path):
paths.append(path)
return paths
def compute_nodal_edge_dirs(nodes, region, field, return_imap=False):
"""
Nodal edge directions are computed by simple averaging of direction vectors
of edges a node is contained in. Edges are assumed to be straight and a
node must be on a single edge (a border node) or shared by exactly two
edges.
"""
coors = region.domain.mesh.coors
dim = coors.shape[1]
graph = region.get_edge_graph()
imap = prepare_remap(nodes, nodes.max() + 1)
mask = nm.zeros_like(imap)
try:
paths = get_edge_paths(graph, mask)
except ValueError:
raise ValueError('more than 2 edges sharing a vertex in region %s!'
% region.name)
# All nodes must have an edge direction.
if not nm.all(mask[nodes]):
raise ValueError('region %s has not complete edges!' % region.name)
edge_dirs = nm.zeros((nodes.shape[0], dim), dtype=nm.float64)
for path in paths:
pcoors = coors[path]
edirs = nm.diff(pcoors, axis=0)
la.normalize_vectors(edirs, eps=1e-12)
im = imap[nm.c_[path[:-1], path[1:]]]
for ii, edir in enumerate(edirs):
edge_dirs[im[ii]] += edir
la.normalize_vectors(edge_dirs, eps=1e-12)
if return_imap:
return edge_dirs, imap
else:
return edge_dirs
def get_min_value(dofs):
"""
Get a reasonable minimal value of DOFs suitable for extending over a
whole domain.
"""
if dofs.shape[1] > 1: # Vector.
val = 0.0
else: # Scalar.
val = dofs.min()
return val
def extend_cell_data(data, domain, rname, val=None, is_surface=False,
average_surface=True):
"""
Extend cell data defined in a region to the whole domain.
Parameters
----------
data : array
The data defined in the region.
domain : FEDomain instance
The FE domain.
rname : str
The region name.
val : float, optional
The value for filling cells not covered by the region. If not given,
the smallest value in data is used.
is_surface : bool
If True, the data are defined on a surface region. In that case the
values are averaged or summed into the cells containing the region
surface faces (a cell can have several faces of the surface), see
`average_surface`.
average_surface : bool
If True, the data defined on a surface region are averaged, otherwise
the data are summed.
Returns
-------
edata : array
The data extended to all domain elements.
"""
n_el = domain.shape.n_el
if data.shape[0] == n_el: return data
if val is None:
if data.shape[2] > 1: # Vector.
val = nm.amin(nm.abs(data))
else: # Scalar.
val = nm.amin(data)
edata = nm.empty((n_el,) + data.shape[1:], dtype=data.dtype)
edata.fill(val)
region = domain.regions[rname]
if not is_surface:
edata[region.get_cells()] = data
else:
cells = region.get_cells(true_cells_only=False)
ucells = nm.unique(cells)
if len(cells) != len(region.facets):
raise ValueError('region %s has an inner face!'
% region.name)
if average_surface:
avg = nm.bincount(cells, minlength=n_el)[ucells]
else:
avg = 1.0
for ic in range(data.shape[2]):
if nm.isrealobj(data):
evals = nm.bincount(cells, weights=data[:, 0, ic, 0],
minlength=n_el)[ucells]
else:
evals = (nm.bincount(cells, weights=data[:, 0, ic, 0].real,
minlength=n_el)[ucells]
+ 1j *
nm.bincount(cells, weights=data[:, 0, ic, 0].imag,
minlength=n_el)[ucells])
edata[ucells, 0, ic, 0] = evals / avg
return edata
def refine_mesh(filename, level):
"""
Uniformly refine `level`-times a mesh given by `filename`.
The refined mesh is saved to a file with name constructed from base
name of `filename` and `level`-times appended `'_r'` suffix.
Parameters
----------
filename : str
The mesh file name.
level : int
The refinement level.
"""
import os
from sfepy.base.base import output
from sfepy.discrete.fem import Mesh, FEDomain
if level > 0:
mesh = Mesh.from_file(filename)
domain = FEDomain(mesh.name, mesh)
for ii in range(level):
output('refine %d...' % ii)
domain = domain.refine()
output('... %d nodes %d elements'
% (domain.shape.n_nod, domain.shape.n_el))
suffix = os.path.splitext(filename)[1]
filename = domain.name + suffix
domain.mesh.write(filename, io='auto')
return filename
| [
"sfepy.discrete.integrals.Integral",
"sfepy.linalg.normalize_vectors",
"sfepy.discrete.PolySpace.any_from_args",
"sfepy.linalg.norm_l2_along_axis",
"sfepy.discrete.fem.Mesh.from_file",
"sfepy.discrete.fem.FEDomain",
"sfepy.base.base.output"
] | [((352, 387), 'numpy.empty', 'nm.empty', (['(n_full,)'], {'dtype': 'nm.int32'}), '((n_full,), dtype=nm.int32)\n', (360, 387), True, 'import numpy as nm\n'), ((428, 471), 'numpy.arange', 'nm.arange', (['indices.shape[0]'], {'dtype': 'nm.int32'}), '(indices.shape[0], dtype=nm.int32)\n', (437, 471), True, 'import numpy as nm\n'), ((1061, 1084), 'numpy.asarray', 'nm.asarray', (['old_indices'], {}), '(old_indices)\n', (1071, 1084), True, 'import numpy as nm\n'), ((1103, 1126), 'numpy.asarray', 'nm.asarray', (['new_indices'], {}), '(new_indices)\n', (1113, 1126), True, 'import numpy as nm\n'), ((1633, 1705), 'sfepy.discrete.PolySpace.any_from_args', 'PolySpace.any_from_args', (['""""""', 'field.gel.surface_facet', 'field.approx_order'], {}), "('', field.gel.surface_facet, field.approx_order)\n", (1656, 1705), False, 'from sfepy.discrete import PolySpace\n'), ((1823, 1867), 'numpy.ones', 'nm.ones', (['qp_coors.shape[0]'], {'dtype': 'nm.float64'}), '(qp_coors.shape[0], dtype=nm.float64)\n', (1830, 1867), True, 'import numpy as nm\n'), ((1884, 1935), 'sfepy.discrete.integrals.Integral', 'Integral', (['"""aux"""'], {'coors': 'qp_coors', 'weights': 'qp_weights'}), "('aux', coors=qp_coors, weights=qp_weights)\n", (1892, 1935), False, 'from sfepy.discrete.integrals import Integral\n'), ((1951, 2000), 'numpy.zeros', 'nm.zeros', (['(nodes.shape[0], dim)'], {'dtype': 'nm.float64'}), '((nodes.shape[0], dim), dtype=nm.float64)\n', (1959, 2000), True, 'import numpy as nm\n'), ((2068, 2087), 'numpy.empty_like', 'nm.empty_like', (['mask'], {}), '(mask)\n', (2081, 2087), True, 'import numpy as nm\n'), ((2170, 2211), 'numpy.arange', 'nm.arange', (['nodes.shape[0]'], {'dtype': 'nm.int32'}), '(nodes.shape[0], dtype=nm.int32)\n', (2179, 2211), True, 'import numpy as nm\n'), ((3767, 3797), 'numpy.array', 'nm.array', (['path'], {'dtype': 'nm.int32'}), '(path, dtype=nm.int32)\n', (3775, 3797), True, 'import numpy as nm\n'), ((3962, 3986), 'numpy.unique', 'nm.unique', (['graph.indices'], {}), '(graph.indices)\n', (3971, 3986), True, 'import numpy as nm\n'), ((3997, 4018), 'numpy.diff', 'nm.diff', (['graph.indptr'], {}), '(graph.indptr)\n', (4004, 4018), True, 'import numpy as nm\n'), ((5069, 5088), 'numpy.zeros_like', 'nm.zeros_like', (['imap'], {}), '(imap)\n', (5082, 5088), True, 'import numpy as nm\n'), ((5454, 5503), 'numpy.zeros', 'nm.zeros', (['(nodes.shape[0], dim)'], {'dtype': 'nm.float64'}), '((nodes.shape[0], dim), dtype=nm.float64)\n', (5462, 5503), True, 'import numpy as nm\n'), ((5776, 5818), 'sfepy.linalg.normalize_vectors', 'la.normalize_vectors', (['edge_dirs'], {'eps': '(1e-12)'}), '(edge_dirs, eps=1e-12)\n', (5796, 5818), True, 'import sfepy.linalg as la\n'), ((7421, 7473), 'numpy.empty', 'nm.empty', (['((n_el,) + data.shape[1:])'], {'dtype': 'data.dtype'}), '((n_el,) + data.shape[1:], dtype=data.dtype)\n', (7429, 7473), True, 'import numpy as nm\n'), ((2587, 2610), 'numpy.all', 'nm.all', (['(mask[nodes] > 0)'], {}), '(mask[nodes] > 0)\n', (2593, 2610), True, 'import numpy as nm\n'), ((2700, 2730), 'sfepy.linalg.norm_l2_along_axis', 'la.norm_l2_along_axis', (['normals'], {}), '(normals)\n', (2721, 2730), True, 'import sfepy.linalg as la\n'), ((4119, 4137), 'numpy.where', 'nm.where', (['(npv == 1)'], {}), '(npv == 1)\n', (4127, 4137), True, 'import numpy as nm\n'), ((5340, 5359), 'numpy.all', 'nm.all', (['mask[nodes]'], {}), '(mask[nodes])\n', (5346, 5359), True, 'import numpy as nm\n'), ((5573, 5596), 'numpy.diff', 'nm.diff', (['pcoors'], {'axis': '(0)'}), '(pcoors, axis=0)\n', (5580, 5596), True, 'import numpy as nm\n'), ((5605, 5643), 'sfepy.linalg.normalize_vectors', 'la.normalize_vectors', (['edirs'], {'eps': '(1e-12)'}), '(edirs, eps=1e-12)\n', (5625, 5643), True, 'import sfepy.linalg as la\n'), ((7679, 7695), 'numpy.unique', 'nm.unique', (['cells'], {}), '(cells)\n', (7688, 7695), True, 'import numpy as nm\n'), ((7992, 8012), 'six.moves.range', 'range', (['data.shape[2]'], {}), '(data.shape[2])\n', (7997, 8012), False, 'from six.moves import range\n'), ((9087, 9111), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['filename'], {}), '(filename)\n', (9101, 9111), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((9129, 9154), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['mesh.name', 'mesh'], {}), '(mesh.name, mesh)\n', (9137, 9154), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((9173, 9185), 'six.moves.range', 'range', (['level'], {}), '(level)\n', (9178, 9185), False, 'from six.moves import range\n'), ((4367, 4393), 'numpy.where', 'nm.where', (['(mask[nodes] == 0)'], {}), '(mask[nodes] == 0)\n', (4375, 4393), True, 'import numpy as nm\n'), ((7394, 7407), 'numpy.amin', 'nm.amin', (['data'], {}), '(data)\n', (7401, 7407), True, 'import numpy as nm\n'), ((8029, 8047), 'numpy.isrealobj', 'nm.isrealobj', (['data'], {}), '(data)\n', (8041, 8047), True, 'import numpy as nm\n'), ((9199, 9226), 'sfepy.base.base.output', 'output', (["('refine %d...' % ii)"], {}), "('refine %d...' % ii)\n", (9205, 9226), False, 'from sfepy.base.base import output\n'), ((9276, 9352), '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", (9282, 9352), False, 'from sfepy.base.base import output\n'), ((9390, 9416), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (9406, 9416), False, 'import os\n'), ((7338, 7350), 'numpy.abs', 'nm.abs', (['data'], {}), '(data)\n', (7344, 7350), True, 'import numpy as nm\n'), ((7893, 7927), 'numpy.bincount', 'nm.bincount', (['cells'], {'minlength': 'n_el'}), '(cells, minlength=n_el)\n', (7904, 7927), True, 'import numpy as nm\n'), ((701, 721), 'numpy.where', 'nm.where', (['(remap >= 0)'], {}), '(remap >= 0)\n', (709, 721), True, 'import numpy as nm\n'), ((8073, 8134), 'numpy.bincount', 'nm.bincount', (['cells'], {'weights': 'data[:, 0, ic, 0]', 'minlength': 'n_el'}), '(cells, weights=data[:, 0, ic, 0], minlength=n_el)\n', (8084, 8134), True, 'import numpy as nm\n'), ((8223, 8289), 'numpy.bincount', 'nm.bincount', (['cells'], {'weights': 'data[:, 0, ic, 0].real', 'minlength': 'n_el'}), '(cells, weights=data[:, 0, ic, 0].real, minlength=n_el)\n', (8234, 8289), True, 'import numpy as nm\n'), ((8392, 8458), 'numpy.bincount', 'nm.bincount', (['cells'], {'weights': 'data[:, 0, ic, 0].imag', 'minlength': 'n_el'}), '(cells, weights=data[:, 0, ic, 0].imag, minlength=n_el)\n', (8403, 8458), True, 'import numpy as nm\n')] |
import numpy as np
import itertools
import os
import scipy.linalg
from sfepy.discrete import fem
from .algo_core import generalized_courant_fischer, spring_energy_matrix_accelerate_3D
import util.geometry_util as geo_util
import util.meshgen as meshgen
from util.timer import SimpleTimer
from visualization.model_visualizer import visualize_hinges, visualize_3D
import visualization.model_visualizer as vis
from .constraints_3d import select_non_colinear_points, direction_for_relative_disallowed_motions
from .internal_structure import tetrahedron
from .stiffness_matrix import stiffness_matrix_from_mesh
class Model:
"""
Represent an assembly
"""
def __init__(self):
self.beams = []
self.joints = []
def point_matrix(self) -> np.ndarray:
beam_points = np.vstack([b.points for b in self.beams]).reshape(-1, 3)
# joint_points = np.array([j.virtual_points for j in self.joints]).reshape(-1, 3)
return np.vstack((
beam_points,
))
def point_indices(self):
beam_point_count = np.array([b.point_count for b in self.beams])
end_indices = np.cumsum(beam_point_count)
start_indices = end_indices - beam_point_count
return [np.arange(start, end) for start, end in zip(start_indices, end_indices)]
def edge_matrix(self) -> np.ndarray:
edge_indices = []
index_offset = 0
for beam in self.beams:
edge_indices.append(beam.edges + index_offset)
index_offset += beam.point_count
matrix = np.vstack([edges for edges in edge_indices if edges.size > 0])
return matrix
def constraint_matrix(self) -> np.ndarray:
matrix = []
# collect constraints for each joint and stack them
for joint in self.joints:
constraints = joint.linear_constraints(self)
matrix.append(constraints)
numpy_matrix = np.vstack(matrix) if len(matrix) > 0 else np.empty(0)
return numpy_matrix
def constraints_fixing_first_part(self):
count = len(self.beams[0].points)
fixed_coordinates = np.zeros((count * 3, self.point_count * 3))
for r, c in enumerate(range(count * 3)):
fixed_coordinates[r, c] = 1
return fixed_coordinates
@property
def point_count(self):
return sum(beam.point_count for beam in self.beams)
def add_beam(self, beam):
self.beams.append(beam)
def add_beams(self, beams):
for beam in beams:
self.add_beam(beam)
def add_joint(self, joint):
self.joints.append(joint)
def add_joints(self, joints):
for joint in joints:
self.add_joint(joint)
def beam_point_index(self, beam):
beam_index = self.beams.index(beam)
return sum(b.point_count for b in self.beams[:beam_index])
def joint_point_indices(self):
indices = []
for joint in self.joints:
offset_part_1 = self.beam_point_index(joint.part1)
offset_part_2 = self.beam_point_index(joint.part2)
indice_on_part_1 = select_non_colinear_points(joint.part1.points, near=joint.pivot_point)[1] + offset_part_1
indice_on_part_2 = select_non_colinear_points(joint.part2.points, near=joint.pivot_point)[1] + offset_part_2
indices.append((indice_on_part_1, indice_on_part_2))
return np.array(indices)
def save_json(self, filename: str, **kwargs):
import json
from util.json_encoder import ModelEncoder
with open(filename, "w") as f:
json.dump(self, f, cls=ModelEncoder, **kwargs)
def visualize(self, arrows=None, show_axis=True, show_hinge=True, arrow_style=None):
defaults = {
"length_coeff": 0.2,
"radius_coeff": 0.2,
}
if arrow_style is not None:
arrow_style = {
**defaults,
**arrow_style,
}
else:
arrow_style = defaults
geometries = []
model_mesh = vis.get_lineset_for_edges(self.point_matrix(), self.edge_matrix())
geometries.append(model_mesh)
if show_hinge:
rotation_axes_pairs = [(j.pivot, j.rotation_axes[0]) for j in self.joints if j.rotation_axes is not None]
if len(rotation_axes_pairs) > 0:
rotation_pivots, rotation_axes = zip(*rotation_axes_pairs)
axes_arrows = vis.get_mesh_for_arrows(
rotation_pivots,
geo_util.normalize(rotation_axes),
length_coeff=0.01, radius_coeff=0.4)
axes_arrows.paint_uniform_color([0.5, 0.2, 0.8])
geometries.append(axes_arrows)
translation_vector_pairs = [(j.pivot, j.translation_vectors[0]) for j in self.joints if j.translation_vectors is not None]
if len(translation_vector_pairs) > 0:
translation_pivots, translation_vector = zip(*translation_vector_pairs)
vector_arrows = vis.get_mesh_for_arrows(translation_pivots, translation_vector, length_coeff=0.01, radius_coeff=0.4)
vector_arrows.paint_uniform_color([0.2, 0.8, 0.5])
geometries.append(vector_arrows)
melded_points = [j.pivot for j in self.joints if j.translation_vectors is None and j.rotation_axes is None]
if len(melded_points) > 0:
point_meshes = vis.get_mesh_for_points(melded_points)
geometries.append(point_meshes)
mesh_frame = vis.o3d.geometry.TriangleMesh.create_coordinate_frame(size=10, origin=[0, 0, 0])
geometries.append(mesh_frame)
if arrows is not None:
points = self.point_matrix()
arrow_mesh = vis.get_mesh_for_arrows(points, arrows.reshape(-1, points.shape[1]), **arrow_style)
model_meshes = vis.get_geometries_3D(self.point_matrix(), edges=self.edge_matrix(), show_axis=False, show_point=False)
geometries.extend([arrow_mesh, *model_meshes])
vis.o3d.visualization.draw_geometries(geometries)
def joint_stiffness_matrix(self):
from functools import reduce
matrix = reduce(lambda x, y: x + y, [j.joint_stiffness(self) for j in self.joints])
return matrix
def soft_solve(self, num_pairs=-1, extra_constr=None, verbose=False):
points = self.point_matrix()
edges = self.edge_matrix()
part_stiffness = spring_energy_matrix_accelerate_3D(points, edges, abstract_edges=[])
joint_stiffness = self.joint_stiffness_matrix()
K = part_stiffness + joint_stiffness # global stiffness
eigenpairs = geo_util.eigen(K, symmetric=True)
if verbose:
print(self.report())
if num_pairs == -1:
return [(e, v) for e, v in eigenpairs]
else:
return [(e, v) for e, v in eigenpairs[:num_pairs]]
def eigen_solve(self, num_pairs=-1, extra_constr=None, verbose=False):
points = self.point_matrix()
edges = self.edge_matrix()
timer = SimpleTimer()
stiffness = spring_energy_matrix_accelerate_3D(points, edges, abstract_edges=[])
timer.checkpoint("K")
constraints = self.constraint_matrix()
if extra_constr is not None:
constraints = np.vstack((constraints, extra_constr))
K, B = generalized_courant_fischer(stiffness, constraints)
eigenpairs = geo_util.eigen(K, symmetric=True)
timer.checkpoint("eig")
if verbose:
print(self.report())
timer.report()
if num_pairs == -1:
return [(e, B @ v) for e, v in eigenpairs[:]]
else:
return [(e, B @ v) for e, v in eigenpairs[:num_pairs]]
def __str__(self):
return str(self.report())
def report(self) -> dict:
return {
**{
"#parts": len(self.beams),
"#points": self.point_count,
"#joints": len(self.joints),
"#constraints": len(self.constraint_matrix())
},
**vars(self)
}
class Beam:
def __init__(self, points, edges=None, principle_points=None):
if edges is None:
index_range = range(len(points))
edges = np.array(list(itertools.combinations(index_range, 2)))
self._edges = edges
self.points = points
self.principle_points = principle_points
@classmethod
def crystal(cls, p1, p2, crystal_counts):
from solvers.rigidity_solver.internal_structure import get_crystal_vertices
orient = (p2 - p1) / np.linalg.norm(p2 - p1)
crystals = [get_crystal_vertices(c, orient) for c in np.linspace(p1, p2, num=crystal_counts)]
points = np.vstack(crystals)
return Beam(points)
@classmethod
def tetra(cls, p, q, thickness=1, density=0.333333, ori=None):
points, edges = tetrahedron(p, q, thickness=thickness, density=density, ori=ori)
return Beam(points, edges, principle_points=(p, q))
@classmethod
def dense_tetra(cls, p, q, density=0.333333, thickness=1, ori=None):
points, _ = tetrahedron(p, q, density=density, thickness=thickness, ori=ori)
return Beam(points, principle_points=(p, q))
@classmethod
def vertices(cls, points, orient):
orient = orient / np.linalg.norm(orient) * 10
points = np.vstack((points, points + orient))
return Beam(points)
@classmethod
def cube_as_mesh(cls, pivot, u, v, w):
hashes = hash((tuple(pivot), tuple(u), tuple(v), tuple(w)))
soup_filename = f"data/{hashes}.stl"
mesh_filename = f"data/{hashes}.mesh"
import os
if not os.path.exists(mesh_filename):
meshgen.cube_surface_mesh(soup_filename, pivot, u, v, w)
meshgen.tetrahedralize(soup_filename, mesh_filename)
mesh = fem.Mesh.from_file(mesh_filename)
points = mesh.coors
nonzero_x, nonzero_y = mesh.create_conn_graph().nonzero()
edges = np.hstack((nonzero_x.reshape(-1, 1), nonzero_y.reshape(-1, 1)))
beam = Beam(points, edges)
beam.stiffness = stiffness_matrix_from_mesh(mesh_filename)
beam.mesh_filename = mesh_filename
return beam
@classmethod
def from_soup_file(cls, soup_filename: str):
mesh_filename = soup_filename.replace(".obj", ".mesh")
if not os.path.exists(mesh_filename):
meshgen.tetrahedralize(soup_filename, mesh_filename)
beam = cls.from_mesh_file(mesh_filename)
return beam
@classmethod
def from_mesh_file(cls, mesh_filename):
mesh = fem.Mesh.from_file(mesh_filename)
points = mesh.coors
nonzero_x, nonzero_y = mesh.create_conn_graph().nonzero()
edges = np.hstack((nonzero_x.reshape(-1, 1), nonzero_y.reshape(-1, 1)))
beam = Beam(points, edges)
beam.stiffness = stiffness_matrix_from_mesh(mesh_filename)
beam.mesh_filename = mesh_filename
return beam
@property
def edges(self) -> np.ndarray:
return self._edges
@property
def point_count(self):
return len(self.points)
class Joint:
def __init__(self, part1, part2, pivot,
rotation_axes=None, translation_vectors=None,
soft_translation=None, soft_rotation=None,
soft_translation_coeff=None, soft_rotation_coeff=None,
):
self.part1 = part1
self.part2 = part2
self.soft_translation = soft_translation
self.soft_rotation = soft_rotation
self.soft_translation_coeff = soft_translation_coeff
self.soft_rotation_coeff = soft_rotation_coeff
self.pivot = np.array(pivot)
assert self.pivot.shape == (3,), f"received pivot {self.pivot}, shape {self.pivot.shape}"
if rotation_axes is not None:
self.rotation_axes = np.array(rotation_axes).reshape(-1, 3)
assert np.linalg.matrix_rank(self.rotation_axes) == len(self.rotation_axes)
else:
self.rotation_axes = None
if translation_vectors is not None:
self.translation_vectors = np.array(translation_vectors).reshape(-1, 3)
assert self.translation_vectors.shape[1] == 3
assert np.linalg.matrix_rank(self.translation_vectors) == len(self.translation_vectors)
else:
self.translation_vectors = None
if soft_rotation is not None:
self.soft_rotation = np.array(soft_rotation).reshape(-1, 3)
assert np.linalg.matrix_rank(self.soft_rotation) == len(self.soft_rotation)
else:
self.soft_rotation = None
if soft_translation is not None:
self.soft_translation = np.array(soft_translation).reshape(-1, 3)
assert self.soft_translation.shape[1] == 3
assert np.linalg.matrix_rank(self.soft_translation) == len(self.soft_translation)
else:
self.soft_translation = None
def joint_stiffness(self, model: Model) -> np.ndarray:
dim = 3
source, target = self.part1, self.part2 # aliases
source_points, source_point_indices = select_non_colinear_points(source.points, num=3, near=self.pivot)
target_points, target_point_indices = select_non_colinear_points(target.points, num=3, near=self.pivot)
source_point_indices += model.beam_point_index(source)
target_point_indices += model.beam_point_index(target)
# (n x 18) matrix, standing for prohibitive motion space
soft_allowed_translation = np.vstack([vectors for vectors in (self.translation_vectors, self.soft_translation) if vectors is not None])
soft_allowed_rotation = np.vstack([vectors for vectors in (self.rotation_axes, self.soft_rotation) if vectors is not None])
prohibitive = direction_for_relative_disallowed_motions(
source_points,
target_points,
rotation_pivot=self.pivot,
rotation_axes=soft_allowed_rotation,
translation_vectors=soft_allowed_translation,
)
prohibitive = geo_util.rowwise_normalize(prohibitive)
motion_basis = [prohibitive]
coefficients = [np.ones(prohibitive.shape[0])]
if self.soft_translation is not None:
relative_translation = np.vstack([direction_for_relative_disallowed_motions(source_points, target_points, rotation_pivot=self.pivot,
translation_vectors=scipy.linalg.null_space(translation.reshape(-1, 3)).T,
rotation_axes=np.eye(3))
for translation in self.soft_translation])
assert relative_translation.shape == (len(self.soft_translation_coeff), 18), f"number of soft translation ({relative_translation.shape} and coefficient don't match ({len(self.soft_translation_coeff), 18})"
motion_basis.append(relative_translation)
coefficients.append(self.soft_translation_coeff)
if self.soft_rotation is not None:
relative_rotation = np.vstack([direction_for_relative_disallowed_motions(source_points, target_points, rotation_pivot=self.pivot,
rotation_axes=scipy.linalg.null_space(rotation.reshape(-1, 3)).T,
translation_vectors=np.eye(3))
for rotation in self.soft_rotation])
assert relative_rotation.shape == (len(self.soft_rotation_coeff), 18)
motion_basis.append(relative_rotation)
coefficients.append(self.soft_rotation_coeff)
# cast to numpy array
motion_basis = np.vstack(motion_basis)
coefficients = np.concatenate(coefficients)
# (18 x m) @ (m x m) @ (m x 18) matrix
local_stiffness = motion_basis.T @ np.diag(coefficients) @ motion_basis
assert local_stiffness.shape == (18, 18)
# clip the stiffness matrix to a zero matrix of the same size as the global stiffness matrix
global_indices = np.concatenate((source_point_indices, target_point_indices))
stiffness_at_global = np.zeros((model.point_count * dim, model.point_count * dim))
for local_row_index, global_row_index in enumerate(global_indices):
for local_col_index, global_col_index in enumerate(global_indices):
l_row_slice = slice(local_row_index * 3, local_row_index * 3 + 3)
l_col_slice = slice(local_col_index * 3, local_col_index * 3 + 3)
g_row_slice = slice(global_row_index * 3, global_row_index * 3 + 3)
g_col_slice = slice(global_col_index * 3, global_col_index * 3 + 3)
stiffness_at_global[g_row_slice, g_col_slice] = local_stiffness[l_row_slice, l_col_slice]
return stiffness_at_global
def linear_constraints(self, model: Model) -> np.ndarray:
dim = 3
constraint_matrices = []
for source, target in [
(self.part1, self.part2),
(self.part2, self.part1)
]:
source_points, source_point_indices = select_non_colinear_points(source.points, num=3, near=self.pivot)
target_points, target_point_indices = select_non_colinear_points(target.points, num=3, near=self.pivot)
source_point_indices += model.beam_point_index(source)
target_point_indices += model.beam_point_index(target)
constraints = direction_for_relative_disallowed_motions(
source_points,
target_points,
rotation_pivot=self.pivot,
rotation_axes=self.rotation_axes,
translation_vectors=self.translation_vectors,
)
i, j, k = source_point_indices
t1, t2, t3 = target_point_indices
zero_constraint = np.zeros((constraints.shape[0], model.point_count * dim))
for index, target_index in enumerate(target_point_indices):
l = target_index
zero_constraint[:, i * 3: (i + 1) * 3] = constraints[:, 0: 3]
zero_constraint[:, j * 3: (j + 1) * 3] = constraints[:, 3: 6]
zero_constraint[:, k * 3: (k + 1) * 3] = constraints[:, 6: 9]
zero_constraint[:, l * 3: (l + 1) * 3] = constraints[:, (index + 3) * 3: (index + 4) * 3]
constraint_matrices.append(zero_constraint)
matrix = np.vstack(constraint_matrices)
return matrix
| [
"sfepy.discrete.fem.Mesh.from_file"
] | [((965, 990), 'numpy.vstack', 'np.vstack', (['(beam_points,)'], {}), '((beam_points,))\n', (974, 990), True, 'import numpy as np\n'), ((1070, 1115), 'numpy.array', 'np.array', (['[b.point_count for b in self.beams]'], {}), '([b.point_count for b in self.beams])\n', (1078, 1115), True, 'import numpy as np\n'), ((1138, 1165), 'numpy.cumsum', 'np.cumsum', (['beam_point_count'], {}), '(beam_point_count)\n', (1147, 1165), True, 'import numpy as np\n'), ((1558, 1620), 'numpy.vstack', 'np.vstack', (['[edges for edges in edge_indices if edges.size > 0]'], {}), '([edges for edges in edge_indices if edges.size > 0])\n', (1567, 1620), True, 'import numpy as np\n'), ((2125, 2168), 'numpy.zeros', 'np.zeros', (['(count * 3, self.point_count * 3)'], {}), '((count * 3, self.point_count * 3))\n', (2133, 2168), True, 'import numpy as np\n'), ((3406, 3423), 'numpy.array', 'np.array', (['indices'], {}), '(indices)\n', (3414, 3423), True, 'import numpy as np\n'), ((6078, 6127), 'visualization.model_visualizer.o3d.visualization.draw_geometries', 'vis.o3d.visualization.draw_geometries', (['geometries'], {}), '(geometries)\n', (6115, 6127), True, 'import visualization.model_visualizer as vis\n'), ((6704, 6737), 'util.geometry_util.eigen', 'geo_util.eigen', (['K'], {'symmetric': '(True)'}), '(K, symmetric=True)\n', (6718, 6737), True, 'import util.geometry_util as geo_util\n'), ((7114, 7127), 'util.timer.SimpleTimer', 'SimpleTimer', ([], {}), '()\n', (7125, 7127), False, 'from util.timer import SimpleTimer\n'), ((7485, 7518), 'util.geometry_util.eigen', 'geo_util.eigen', (['K'], {'symmetric': '(True)'}), '(K, symmetric=True)\n', (7499, 7518), True, 'import util.geometry_util as geo_util\n'), ((8820, 8839), 'numpy.vstack', 'np.vstack', (['crystals'], {}), '(crystals)\n', (8829, 8839), True, 'import numpy as np\n'), ((9459, 9495), 'numpy.vstack', 'np.vstack', (['(points, points + orient)'], {}), '((points, points + orient))\n', (9468, 9495), True, 'import numpy as np\n'), ((9959, 9992), 'sfepy.discrete.fem.Mesh.from_file', 'fem.Mesh.from_file', (['mesh_filename'], {}), '(mesh_filename)\n', (9977, 9992), False, 'from sfepy.discrete import fem\n'), ((10722, 10755), 'sfepy.discrete.fem.Mesh.from_file', 'fem.Mesh.from_file', (['mesh_filename'], {}), '(mesh_filename)\n', (10740, 10755), False, 'from sfepy.discrete import fem\n'), ((11808, 11823), 'numpy.array', 'np.array', (['pivot'], {}), '(pivot)\n', (11816, 11823), True, 'import numpy as np\n'), ((13681, 13794), 'numpy.vstack', 'np.vstack', (['[vectors for vectors in (self.translation_vectors, self.soft_translation) if\n vectors is not None]'], {}), '([vectors for vectors in (self.translation_vectors, self.\n soft_translation) if vectors is not None])\n', (13690, 13794), True, 'import numpy as np\n'), ((13822, 13925), 'numpy.vstack', 'np.vstack', (['[vectors for vectors in (self.rotation_axes, self.soft_rotation) if vectors\n is not None]'], {}), '([vectors for vectors in (self.rotation_axes, self.soft_rotation) if\n vectors is not None])\n', (13831, 13925), True, 'import numpy as np\n'), ((14220, 14259), 'util.geometry_util.rowwise_normalize', 'geo_util.rowwise_normalize', (['prohibitive'], {}), '(prohibitive)\n', (14246, 14259), True, 'import util.geometry_util as geo_util\n'), ((15905, 15928), 'numpy.vstack', 'np.vstack', (['motion_basis'], {}), '(motion_basis)\n', (15914, 15928), True, 'import numpy as np\n'), ((15952, 15980), 'numpy.concatenate', 'np.concatenate', (['coefficients'], {}), '(coefficients)\n', (15966, 15980), True, 'import numpy as np\n'), ((16285, 16345), 'numpy.concatenate', 'np.concatenate', (['(source_point_indices, target_point_indices)'], {}), '((source_point_indices, target_point_indices))\n', (16299, 16345), True, 'import numpy as np\n'), ((16376, 16436), 'numpy.zeros', 'np.zeros', (['(model.point_count * dim, model.point_count * dim)'], {}), '((model.point_count * dim, model.point_count * dim))\n', (16384, 16436), True, 'import numpy as np\n'), ((18668, 18698), 'numpy.vstack', 'np.vstack', (['constraint_matrices'], {}), '(constraint_matrices)\n', (18677, 18698), True, 'import numpy as np\n'), ((1237, 1258), 'numpy.arange', 'np.arange', (['start', 'end'], {}), '(start, end)\n', (1246, 1258), True, 'import numpy as np\n'), ((1926, 1943), 'numpy.vstack', 'np.vstack', (['matrix'], {}), '(matrix)\n', (1935, 1943), True, 'import numpy as np\n'), ((1968, 1979), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (1976, 1979), True, 'import numpy as np\n'), ((3597, 3643), 'json.dump', 'json.dump', (['self', 'f'], {'cls': 'ModelEncoder'}), '(self, f, cls=ModelEncoder, **kwargs)\n', (3606, 3643), False, 'import json\n'), ((5574, 5659), 'visualization.model_visualizer.o3d.geometry.TriangleMesh.create_coordinate_frame', 'vis.o3d.geometry.TriangleMesh.create_coordinate_frame', ([], {'size': '(10)', 'origin': '[0, 0, 0]'}), '(size=10, origin=[0, 0, 0]\n )\n', (5627, 5659), True, 'import visualization.model_visualizer as vis\n'), ((7358, 7396), 'numpy.vstack', 'np.vstack', (['(constraints, extra_constr)'], {}), '((constraints, extra_constr))\n', (7367, 7396), True, 'import numpy as np\n'), ((8677, 8700), 'numpy.linalg.norm', 'np.linalg.norm', (['(p2 - p1)'], {}), '(p2 - p1)\n', (8691, 8700), True, 'import numpy as np\n'), ((8721, 8752), 'solvers.rigidity_solver.internal_structure.get_crystal_vertices', 'get_crystal_vertices', (['c', 'orient'], {}), '(c, orient)\n', (8741, 8752), False, 'from solvers.rigidity_solver.internal_structure import get_crystal_vertices\n'), ((9778, 9807), 'os.path.exists', 'os.path.exists', (['mesh_filename'], {}), '(mesh_filename)\n', (9792, 9807), False, 'import os\n'), ((9821, 9877), 'util.meshgen.cube_surface_mesh', 'meshgen.cube_surface_mesh', (['soup_filename', 'pivot', 'u', 'v', 'w'], {}), '(soup_filename, pivot, u, v, w)\n', (9846, 9877), True, 'import util.meshgen as meshgen\n'), ((9890, 9942), 'util.meshgen.tetrahedralize', 'meshgen.tetrahedralize', (['soup_filename', 'mesh_filename'], {}), '(soup_filename, mesh_filename)\n', (9912, 9942), True, 'import util.meshgen as meshgen\n'), ((10479, 10508), 'os.path.exists', 'os.path.exists', (['mesh_filename'], {}), '(mesh_filename)\n', (10493, 10508), False, 'import os\n'), ((10522, 10574), 'util.meshgen.tetrahedralize', 'meshgen.tetrahedralize', (['soup_filename', 'mesh_filename'], {}), '(soup_filename, mesh_filename)\n', (10544, 10574), True, 'import util.meshgen as meshgen\n'), ((14322, 14351), 'numpy.ones', 'np.ones', (['prohibitive.shape[0]'], {}), '(prohibitive.shape[0])\n', (14329, 14351), True, 'import numpy as np\n'), ((18087, 18144), 'numpy.zeros', 'np.zeros', (['(constraints.shape[0], model.point_count * dim)'], {}), '((constraints.shape[0], model.point_count * dim))\n', (18095, 18144), True, 'import numpy as np\n'), ((803, 844), 'numpy.vstack', 'np.vstack', (['[b.points for b in self.beams]'], {}), '([b.points for b in self.beams])\n', (812, 844), True, 'import numpy as np\n'), ((5053, 5157), 'visualization.model_visualizer.get_mesh_for_arrows', 'vis.get_mesh_for_arrows', (['translation_pivots', 'translation_vector'], {'length_coeff': '(0.01)', 'radius_coeff': '(0.4)'}), '(translation_pivots, translation_vector,\n length_coeff=0.01, radius_coeff=0.4)\n', (5076, 5157), True, 'import visualization.model_visualizer as vis\n'), ((5461, 5499), 'visualization.model_visualizer.get_mesh_for_points', 'vis.get_mesh_for_points', (['melded_points'], {}), '(melded_points)\n', (5484, 5499), True, 'import visualization.model_visualizer as vis\n'), ((8762, 8801), 'numpy.linspace', 'np.linspace', (['p1', 'p2'], {'num': 'crystal_counts'}), '(p1, p2, num=crystal_counts)\n', (8773, 8801), True, 'import numpy as np\n'), ((9414, 9436), 'numpy.linalg.norm', 'np.linalg.norm', (['orient'], {}), '(orient)\n', (9428, 9436), True, 'import numpy as np\n'), ((12052, 12093), 'numpy.linalg.matrix_rank', 'np.linalg.matrix_rank', (['self.rotation_axes'], {}), '(self.rotation_axes)\n', (12073, 12093), True, 'import numpy as np\n'), ((12379, 12426), 'numpy.linalg.matrix_rank', 'np.linalg.matrix_rank', (['self.translation_vectors'], {}), '(self.translation_vectors)\n', (12400, 12426), True, 'import numpy as np\n'), ((12648, 12689), 'numpy.linalg.matrix_rank', 'np.linalg.matrix_rank', (['self.soft_rotation'], {}), '(self.soft_rotation)\n', (12669, 12689), True, 'import numpy as np\n'), ((12963, 13007), 'numpy.linalg.matrix_rank', 'np.linalg.matrix_rank', (['self.soft_translation'], {}), '(self.soft_translation)\n', (12984, 13007), True, 'import numpy as np\n'), ((16072, 16093), 'numpy.diag', 'np.diag', (['coefficients'], {}), '(coefficients)\n', (16079, 16093), True, 'import numpy as np\n'), ((4543, 4576), 'util.geometry_util.normalize', 'geo_util.normalize', (['rotation_axes'], {}), '(rotation_axes)\n', (4561, 4576), True, 'import util.geometry_util as geo_util\n'), ((8352, 8390), 'itertools.combinations', 'itertools.combinations', (['index_range', '(2)'], {}), '(index_range, 2)\n', (8374, 8390), False, 'import itertools\n'), ((11994, 12017), 'numpy.array', 'np.array', (['rotation_axes'], {}), '(rotation_axes)\n', (12002, 12017), True, 'import numpy as np\n'), ((12257, 12286), 'numpy.array', 'np.array', (['translation_vectors'], {}), '(translation_vectors)\n', (12265, 12286), True, 'import numpy as np\n'), ((12590, 12613), 'numpy.array', 'np.array', (['soft_rotation'], {}), '(soft_rotation)\n', (12598, 12613), True, 'import numpy as np\n'), ((12847, 12873), 'numpy.array', 'np.array', (['soft_translation'], {}), '(soft_translation)\n', (12855, 12873), True, 'import numpy as np\n'), ((14749, 14758), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (14755, 14758), True, 'import numpy as np\n'), ((15569, 15578), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (15575, 15578), True, 'import numpy as np\n')] |
from sfepy.base.testing import TestCommon, assert_, debug
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
return Test(conf=conf, options=options)
def test_tensors(self):
import numpy as nm
import sfepy.mechanics.tensors as tn
ok = True
a_full = 2.0 * nm.ones((5,3,3), dtype=nm.float64)
a_sym = 2.0 * nm.ones((5,6), dtype=nm.float64)
_tr = nm.array([6.0] * 5, dtype=nm.float64)
_vt_full = 2.0 * nm.tile(nm.eye(3, dtype=nm.float64), (5,1,1))
_vt_sym = nm.tile(nm.array([2, 2, 2, 0, 0, 0], dtype=nm.float64),
(5,1,1))
_dev_full = a_full - _vt_full
_dev_sym = a_sym - _vt_sym
_vms = 6.0 * nm.ones((5,1), dtype=nm.float64)
tr = tn.get_trace(a_full, sym_storage=False)
_ok = nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace full: %s' % _ok)
ok = ok and _ok
tr = tn.get_trace(a_sym, sym_storage=True)
ok = ok and nm.allclose(tr, _tr, rtol=0.0, atol=1e-14)
self.report('trace sym: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_full, sym_storage=False)
_ok = nm.allclose(vt, _vt_full, rtol=0.0, atol=1e-14)
self.report('volumetric tensor full: %s' % _ok)
ok = ok and _ok
vt = tn.get_volumetric_tensor(a_sym, sym_storage=True)
_ok = nm.allclose(vt, _vt_sym, rtol=0.0, atol=1e-14)
self.report('volumetric tensor sym: %s' % _ok)
ok = ok and _ok
dev = tn.get_deviator(a_full, sym_storage=False)
_ok = nm.allclose(dev, _dev_full, rtol=0.0, atol=1e-14)
self.report('deviator full: %s' % _ok)
ok = ok and _ok
aux = (dev * nm.transpose(dev, (0, 2, 1))).sum(axis=1).sum(axis=1)
vms2 = nm.sqrt((3.0/2.0) * aux)[:,None]
dev = tn.get_deviator(a_sym, sym_storage=True)
_ok = nm.allclose(dev, _dev_sym, rtol=0.0, atol=1e-14)
self.report('deviator sym: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_full, sym_storage=False)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress full: %s' % _ok)
ok = ok and _ok
vms = tn.get_von_mises_stress(a_sym, sym_storage=True)
_ok = nm.allclose(vms, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress sym: %s' % _ok)
ok = ok and _ok
_ok = nm.allclose(vms2, _vms, rtol=0.0, atol=1e-14)
self.report('von Mises stress via deviator: %s' % _ok)
ok = ok and _ok
return ok
| [
"sfepy.mechanics.tensors.get_volumetric_tensor",
"sfepy.mechanics.tensors.get_deviator",
"sfepy.mechanics.tensors.get_trace",
"sfepy.mechanics.tensors.get_von_mises_stress"
] | [((433, 470), 'numpy.array', 'nm.array', (['([6.0] * 5)'], {'dtype': 'nm.float64'}), '([6.0] * 5, dtype=nm.float64)\n', (441, 470), True, 'import numpy as nm\n'), ((792, 831), 'sfepy.mechanics.tensors.get_trace', 'tn.get_trace', (['a_full'], {'sym_storage': '(False)'}), '(a_full, sym_storage=False)\n', (804, 831), True, 'import sfepy.mechanics.tensors as tn\n'), ((846, 888), 'numpy.allclose', 'nm.allclose', (['tr', '_tr'], {'rtol': '(0.0)', 'atol': '(1e-14)'}), '(tr, _tr, rtol=0.0, atol=1e-14)\n', (857, 888), True, 'import numpy as nm\n'), ((979, 1016), 'sfepy.mechanics.tensors.get_trace', 'tn.get_trace', (['a_sym'], {'sym_storage': '(True)'}), '(a_sym, sym_storage=True)\n', (991, 1016), True, 'import sfepy.mechanics.tensors as tn\n'), ((1161, 1212), 'sfepy.mechanics.tensors.get_volumetric_tensor', 'tn.get_volumetric_tensor', (['a_full'], {'sym_storage': '(False)'}), '(a_full, sym_storage=False)\n', (1185, 1212), True, 'import sfepy.mechanics.tensors as tn\n'), ((1227, 1274), 'numpy.allclose', 'nm.allclose', (['vt', '_vt_full'], {'rtol': '(0.0)', 'atol': '(1e-14)'}), '(vt, _vt_full, rtol=0.0, atol=1e-14)\n', (1238, 1274), True, 'import numpy as nm\n'), ((1377, 1426), 'sfepy.mechanics.tensors.get_volumetric_tensor', 'tn.get_volumetric_tensor', (['a_sym'], {'sym_storage': '(True)'}), '(a_sym, sym_storage=True)\n', (1401, 1426), True, 'import sfepy.mechanics.tensors as tn\n'), ((1441, 1487), 'numpy.allclose', 'nm.allclose', (['vt', '_vt_sym'], {'rtol': '(0.0)', 'atol': '(1e-14)'}), '(vt, _vt_sym, rtol=0.0, atol=1e-14)\n', (1452, 1487), True, 'import numpy as nm\n'), ((1590, 1632), 'sfepy.mechanics.tensors.get_deviator', 'tn.get_deviator', (['a_full'], {'sym_storage': '(False)'}), '(a_full, sym_storage=False)\n', (1605, 1632), True, 'import sfepy.mechanics.tensors as tn\n'), ((1647, 1696), 'numpy.allclose', 'nm.allclose', (['dev', '_dev_full'], {'rtol': '(0.0)', 'atol': '(1e-14)'}), '(dev, _dev_full, rtol=0.0, atol=1e-14)\n', (1658, 1696), True, 'import numpy as nm\n'), ((1915, 1955), 'sfepy.mechanics.tensors.get_deviator', 'tn.get_deviator', (['a_sym'], {'sym_storage': '(True)'}), '(a_sym, sym_storage=True)\n', (1930, 1955), True, 'import sfepy.mechanics.tensors as tn\n'), ((1970, 2018), 'numpy.allclose', 'nm.allclose', (['dev', '_dev_sym'], {'rtol': '(0.0)', 'atol': '(1e-14)'}), '(dev, _dev_sym, rtol=0.0, atol=1e-14)\n', (1981, 2018), True, 'import numpy as nm\n'), ((2112, 2162), 'sfepy.mechanics.tensors.get_von_mises_stress', 'tn.get_von_mises_stress', (['a_full'], {'sym_storage': '(False)'}), '(a_full, sym_storage=False)\n', (2135, 2162), True, 'import sfepy.mechanics.tensors as tn\n'), ((2177, 2221), 'numpy.allclose', 'nm.allclose', (['vms', '_vms'], {'rtol': '(0.0)', 'atol': '(1e-14)'}), '(vms, _vms, rtol=0.0, atol=1e-14)\n', (2188, 2221), True, 'import numpy as nm\n'), ((2316, 2364), 'sfepy.mechanics.tensors.get_von_mises_stress', 'tn.get_von_mises_stress', (['a_sym'], {'sym_storage': '(True)'}), '(a_sym, sym_storage=True)\n', (2339, 2364), True, 'import sfepy.mechanics.tensors as tn\n'), ((2379, 2423), 'numpy.allclose', 'nm.allclose', (['vms', '_vms'], {'rtol': '(0.0)', 'atol': '(1e-14)'}), '(vms, _vms, rtol=0.0, atol=1e-14)\n', (2390, 2423), True, 'import numpy as nm\n'), ((2517, 2562), 'numpy.allclose', 'nm.allclose', (['vms2', '_vms'], {'rtol': '(0.0)', 'atol': '(1e-14)'}), '(vms2, _vms, rtol=0.0, atol=1e-14)\n', (2528, 2562), True, 'import numpy as nm\n'), ((328, 364), 'numpy.ones', 'nm.ones', (['(5, 3, 3)'], {'dtype': 'nm.float64'}), '((5, 3, 3), dtype=nm.float64)\n', (335, 364), True, 'import numpy as nm\n'), ((385, 418), 'numpy.ones', 'nm.ones', (['(5, 6)'], {'dtype': 'nm.float64'}), '((5, 6), dtype=nm.float64)\n', (392, 418), True, 'import numpy as nm\n'), ((568, 614), 'numpy.array', 'nm.array', (['[2, 2, 2, 0, 0, 0]'], {'dtype': 'nm.float64'}), '([2, 2, 2, 0, 0, 0], dtype=nm.float64)\n', (576, 614), True, 'import numpy as nm\n'), ((745, 778), 'numpy.ones', 'nm.ones', (['(5, 1)'], {'dtype': 'nm.float64'}), '((5, 1), dtype=nm.float64)\n', (752, 778), True, 'import numpy as nm\n'), ((1037, 1079), 'numpy.allclose', 'nm.allclose', (['tr', '_tr'], {'rtol': '(0.0)', 'atol': '(1e-14)'}), '(tr, _tr, rtol=0.0, atol=1e-14)\n', (1048, 1079), True, 'import numpy as nm\n'), ((1859, 1883), 'numpy.sqrt', 'nm.sqrt', (['(3.0 / 2.0 * aux)'], {}), '(3.0 / 2.0 * aux)\n', (1866, 1883), True, 'import numpy as nm\n'), ((504, 531), 'numpy.eye', 'nm.eye', (['(3)'], {'dtype': 'nm.float64'}), '(3, dtype=nm.float64)\n', (510, 531), True, 'import numpy as nm\n'), ((1790, 1818), 'numpy.transpose', 'nm.transpose', (['dev', '(0, 2, 1)'], {}), '(dev, (0, 2, 1))\n', (1802, 1818), True, 'import numpy as nm\n')] |
# AtrialFibrePlugin
# Copyright (C) 2018 <NAME>, King's College London, all rights reserved, see LICENSE file
'''
Atrial fibre generation plugin.
'''
import os
import stat
import ast
import shutil
import datetime
import zipfile
import warnings
from itertools import starmap
from collections import defaultdict
try:
import configparser
except ImportError:
import ConfigParser as configparser
try:
from sfepy.base.conf import ProblemConf
from sfepy.applications import solve_pde
from sfepy.base.base import output
except ImportError:
warnings.warn('SfePy needs to be installed or in PYTHONPATH to generate fiber directions.')
from eidolon import ( ui,
ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType,
listToMatrix,MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush
)
import eidolon
import numpy as np
from scipy.spatial import cKDTree
plugindir= os.path.dirname(os.path.abspath(__file__)) # this file's directory
# directory/file names
uifile=os.path.join(plugindir,'AtrialFibrePlugin.ui')
deformDir=os.path.join(plugindir,'deformetricaC')
deformExe=os.path.join(deformDir,'deformetrica')
architecture=os.path.join(plugindir,'architecture.ini')
problemFile=os.path.join(plugindir,'problemfile.py')
# registration file names
decimatedFile='subject.vtk'
targetFile='target.vtk'
datasetFile='data_set.xml'
modelFile='model.xml'
optimFile='optimization_parameters.xml'
registeredFile='Registration_subject_to_subject_0__t_9.vtk'
decimate='decimate-surface'
# deformetrica parameters
kernelWidthSub=5000
kernelWidthDef=8000
kernelType='cudaexact'
dataSigma=0.1
stepSize=0.000001
# field names
#regionField='regions'
#landmarkField='landmarks'
#directionField='directions'
#gradientDirField='gradientDirs'
#elemDirField='elemDirs'
#elemRegionField='elemRegions'
#elemthickness='elemThickness'
#elemGradient='elemGradient'
fieldNames=eidolon.enum(
'regions','landmarks',
'directions','gradientDirs',
'elemDirs','elemRegions','elemThickness',
'nodeGradient'
)
objNames=eidolon.enum(
'atlasmesh',
'origmesh',
'epimesh','epinodes',
'endomesh','endonodes',
'architecture'
)
regTypes=eidolon.enum('endo','epi')
# load the UI file into the ui namespace, this is subtyped below
ui.loadUI(open(uifile).read())
def showLines(nodes,lines,name='Lines',matname='Default'):
mgr=eidolon.getSceneMgr()
lineds=eidolon.LineDataSet(name+'DS',nodes,lines)
obj=MeshSceneObject(name,lineds)
mgr.addSceneObject(obj)
rep=obj.createRepr(eidolon.ReprType._line,matname=matname)
mgr.addSceneObjectRepr(rep)
return obj,rep
def showElemDirs(obj,glyphscale,mgr):
ds=obj.datasets[0]
nodes=ds.getNodes()
tets=first(i for i in ds.enumIndexSets() if i.getType()==ElemType._Tet1NL)
elemdirfield=ds.getDataField(fieldNames._elemDirs)
mid=ElemType.Tet1NL.basis(0.25,0.25,0.25)
elemnodes=[ElemType.Tet1NL.applyCoeffs([nodes[e] for e in elem],mid) for elem in tets]
elemobj=MeshSceneObject('elemobj',PyDataSet('elemobjds',elemnodes,[],[elemdirfield]))
mgr.addSceneObject(elemobj)
rep=elemobj.createRepr(eidolon.ReprType._glyph,0,externalOnly=False,drawInternal=True,glyphname='arrow',
glyphscale=glyphscale,dfield=elemdirfield.getName(),vecfunc=eidolon.VecFunc._Linear)
mgr.addSceneObjectRepr(rep)
class initdict(defaultdict):
def __init__(self,initfunc,*args,**kwargs):
defaultdict.__init__(self,None,*args,**kwargs)
self.initfunc=initfunc
def __missing__(self,key):
value=self.initfunc(key)
self.__setitem__(key,value)
return value
class plane(object):
def __init__(self,center,norm):
self.center=center
self.norm=norm.norm()
def dist(self,pt):
return pt.planeDist(self.center,self.norm)
def moveUp(self,dist):
self.center+=self.norm*dist
def numPointsAbove(self,nodes):
return sum(1 for n in nodes if self.dist(n)>=0)
def between(self,nodes,otherplane):
numnodes=len(nodes)
return self.numPointsAbove(nodes)==numnodes and otherplane.numPointsAbove(nodes)==numnodes
def findIntersects(self,nodes,inds):
numnodes=inds.m()
result=[]
for n in range(inds.n()):
if 0<self.numPointsAbove(nodes.mapIndexRow(inds,n))<numnodes:
result.append(n)
return result
class TriMeshGraph(object):
def __init__(self,nodes,tris,ocdepth=3):
self.nodes=nodes if isinstance(nodes,eidolon.Vec3Matrix) else listToMatrix(nodes,'nodes')
self.tris=tris if isinstance(tris,eidolon.IndexMatrix) else listToMatrix(tris,'tris')
self.tricenters=[avg(self.getTriNodes(r),vec3()) for r in range(self.tris.n())]
self.adj,self.ragged=generateTriAdj(self.tris) # elem -> elems
self.nodeelem=generateNodeElemMap(self.nodes.n(),self.tris) # node -> elems
self.edges=generateSimplexEdgeMap(self.nodes.n(),self.tris) # node -> nodes
self.boundbox=BoundBox(nodes)
# self.octree=eidolon.Octree(ocdepth,self.boundbox.getDimensions(),self.boundbox.center)
# self.octree.addMesh(self.nodes,self.tris)
def computeDist(key):
i,j=key
return self.tricenters[i].distTo(self.tricenters[j])
self.tridists=initdict(computeDist)
# def getIntersectedTri(self,start,end):
# '''
# Returns the triangle index and the (t,u,v) triple if the line from `start' to `end' intersects the indexed triangle
# at a distance of `t' from `start' with xi coord (u,v). Returns None if no triangle intersected.
# '''
# startoc=self.octree.getLeaf(start)
# endoc=self.octree.getLeaf(end)
# inds=(startoc.leafdata if startoc is not None else []) + (endoc.leafdata if endoc is not None else [])
#
# r=eidolon.Ray(start,end-start)
#
# for tri in inds:
# d=r.intersectsTri(*self.getTriNodes(tri))
# if d:# and d[0]<=start.distTo(end):
# return tri,d
#
# return None
def getPathSubgraph(self,starttri,endtri):
return getAdjTo(self.adj,starttri,endtri)
def getTriNodes(self,triindex):
return self.nodes.mapIndexRow(self.tris,triindex)
def getTriNorm(self,triindex):
a,b,c=self.getTriNodes(triindex)
return a.planeNorm(b,c)
def getSharedNodeTris(self,triindex):
tris=set()
for n in self.tris[triindex]:
tris.update(self.nodeelem[n])
tris.remove(triindex)
return list(sorted(tris))
def getNearestTri(self,pt):
def triDist(tri):
norm=self.getTriNorm(tri)
pt=self.tricenters[tri]
return abs(pt.planeDist(pt,norm))
nearestnode=min([n for n in range(self.nodes.n()) if self.nodeelem[n]],key=lambda n:self.nodes[n].distToSq(pt))
tris=self.nodeelem[nearestnode]
return min(tris,key=triDist)
def getPath(self,starttri,endtri,acceptTri=None):
return dijkstra(self.adj,starttri,endtri,lambda i,j:self.tridists[(i,j)],acceptTri)
def loadArchitecture(path,section):
'''
Load the architecture from the given file `path' and return values from the given section (endo or epi). The
return value is a tuple containing:
landmarks: 0-based indices of landmark nodes in the atlas
lmlines : 0-based index pairs defining lines between indices in landmarks
lmregions: a list of maps, each map defining a region which are mappings from a 0-based indices into lmlines to
the line's landmark index pair
lmstim : a per-region specifier list stating which lines (L# for index #) or atlas node (N#) defines stimulation
lground : a per-region specifier list stating which lines (L# for index #) or atlas node (N#) defines ground
appendageregion: region number for the appendage
appendagenode: node index for the appendage's division node which must be generated
'''
c=configparser.SafeConfigParser()
assert len(c.read(path))>0
landmarks=ast.literal_eval(c.get(section,'landmarks')) # 0-based node indices
lines=ast.literal_eval(c.get(section,'lines')) # 1-based landmark indices
regions=ast.literal_eval(c.get(section,'regions')) # 1-based landmark indices
stimulus=ast.literal_eval(c.get(section,'stimulus')) # per region
ground=ast.literal_eval(c.get(section,'ground')) # per region
appendageregion=ast.literal_eval(c.get(section,'appendageregion'))
appendagenode=ast.literal_eval(c.get(section,'appendagenode'))
appendagelmindex=ast.literal_eval(c.get(section,'appendagelmindex'))
# types=ast.literal_eval(c.get(section,'type')) # per region
# indices that don't exist are for landmarks that need to be calculated
lmlines=[subone(l) for l in lines ]#if max(l)<=len(landmarks)] # filter for lines with existing node indices
lmregions=[subone(r) for r in regions]
# lmregions=[subone(r) for r in regions if all(i<=len(landmarks) for i in r)]
lmstim=stimulus#[:len(lmregions)]
lmground=ground#[:len(lmregions)]
allregions=[]
for r in lmregions:
lr={i:(a,b) for i,(a,b) in enumerate(lmlines) if a in r and b in r}
if len(lr)>2:
allregions.append(lr)
return landmarks,lmlines,allregions,lmstim,lmground, appendageregion,appendagenode,appendagelmindex
def writeMeshFile(filename,nodes,inds,nodegroup,indgroup,dim):
'''Write a medit format mesh file to `filename'.'''
with open(filename,'w') as o:
print('MeshVersionFormatted 1',file=o)
print('Dimension %i'%dim,file=o)
print('Vertices',file=o)
print(len(nodes),file=o)
for n in range(len(nodes)):
for v in tuple(nodes[n])[:dim]:
print('%20.10f'%v,end=' ',file=o)
group=0 if nodegroup is None else nodegroup[n]
print(group,file=o)
print('Triangles' if len(inds[0])==3 else 'Tetrahedra',file=o)
print(len(inds),file=o)
for n in range(len(inds)):
print(*['%10i'%(t+1) for t in inds[n]],file=o,end=' ')
group=0 if indgroup is None else indgroup[n]
print(group,file=o)
def createNodeQuery(nodes):
'''
Create a cKDTree object from `nodes' and return a query function which accepts a position and radius value. The
function will return the nearest point index to the given position if radius<=0 and a list of indices of points
within the given radius of the position otherwise. The node list is also returned as a second return value.
'''
tree=cKDTree(np.asarray(list(map(tuple,nodes))))
def _query(pos,radius=0):
'''Query `nodes' for the nearest node to `pos' if `radius'<=0 or a list of those within `radius' otherwise.'''
pos=tuple(pos)
if radius<=0:
return tree.query(pos)[1],tree.data
else:
return tree.query_ball_point(pos,radius),tree.data
return _query
def registerSubjectToTarget(subjectObj,targetObj,targetTrans,outdir,decimpath,VTK):
'''
Register the `subjectObj' mesh object to `targetObj' mesh object putting data into directory `outdir'. The subject
will be decimated to have roughly the same number of nodes as the target and then stored as subject.vtk in `outdir'.
Registration is done with Deformetrica and result stored as 'Registration_subject_to_subject_0__t_9.vtk' in `outdir'.
If `targetTrans' must be None or a transform which is applied to the nodes of `targetObj' before registration.
'''
dpath=os.path.join(outdir,decimatedFile)
tmpfile=os.path.join(outdir,'tmp.vtk')
# if a transform is given, apply that transform to the target mesh when saving otherwise do no transformation
vecfunc=(lambda i: tuple(targetTrans*i)) if targetTrans else None
shutil.copy(os.path.join(deformDir,datasetFile),os.path.join(outdir,datasetFile)) # copy dataset file unchanged
model=open(os.path.join(deformDir,modelFile)).read()
model=model.replace('%1',str(dataSigma))
model=model.replace('%2',str(kernelWidthSub))
model=model.replace('%3',str(kernelType))
model=model.replace('%4',str(kernelWidthDef))
with open(os.path.join(outdir,modelFile),'w') as o: # save modified model file
o.write(model)
optim=open(os.path.join(deformDir,optimFile)).read()
optim=optim.replace('%1',str(stepSize))
with open(os.path.join(outdir,optimFile),'w') as o: # save modified optimization file
o.write(optim)
VTK.saveLegacyFile(tmpfile,subjectObj,datasettype='POLYDATA')
VTK.saveLegacyFile(os.path.join(outdir,targetFile),targetObj,datasettype='POLYDATA',vecfunc=vecfunc)
snodes=subjectObj.datasets[0].getNodes()
tnodes=targetObj.datasets[0].getNodes()
sizeratio=float(tnodes.n())/snodes.n()
sizepercent=str(100*(1-sizeratio))[:6] # percent to decimate by
# decimate the mesh most of the way towards having the same number of nodes as the target
ret,output=eidolon.execBatchProgram(decimpath,tmpfile,dpath,'-reduceby',sizepercent,'-ascii',logcmd=True)
assert ret==0,output
env={'LD_LIBRARY_PATH':deformDir}
ret,output=eidolon.execBatchProgram(deformExe,"registration", "3D", modelFile, datasetFile, optimFile, "--output-dir=.",cwd=outdir,env=env,logcmd=True)
assert ret==0,output
return output
def transferLandmarks(archFilename,fieldname,targetObj,targetTrans,subjectObj,outdir,VTK):
'''
Register the landmarks defined as node indices on `targetObj' to equivalent node indices on `subjectObj' via the
decimated and registered intermediary stored in `outdir'. The result is a list of index pairs associating a node
index in `subjectObj' for every landmark index in `targetObj'.
'''
decimated=os.path.join(outdir,decimatedFile)
registered=os.path.join(outdir,registeredFile)
arch=loadArchitecture(archFilename,fieldname)
lmarks,lines=arch[:2]
appendagelmindex=arch[-1]
# append the index for the estimated appendage node, this will have to be adjusted manually after registration
lmarks.append(appendagelmindex)
reg=VTK.loadObject(registered) # mesh registered to target
dec=VTK.loadObject(decimated) # decimated unregistered mesh
tnodes=targetObj.datasets[0].getNodes() # target points
rnodes=reg.datasets[0].getNodes() # registered decimated points
dnodes=dec.datasets[0].getNodes() # unregistered decimated points
snodes=subjectObj.datasets[0].getNodes() # original subject points
targetTrans=targetTrans or eidolon.transform()
lmpoints=[(targetTrans*tnodes[m],m) for m in lmarks] # (transformed landmark node, index) pairs
# find the points in the registered mesh closest to the landmark points in the target object
query=createNodeQuery(rnodes)
rpoints=[(query(pt)[0],m) for pt,m in lmpoints]
# find the subject nodes closes to landmark points in the decimated mesh (which are at the same indices as in the registered mesh)
query=createNodeQuery(snodes)
spoints=[(query(dnodes[i])[0],m) for i,m in rpoints]
assert len(spoints)==len(lmpoints)
assert all(p[0] is not None for p in spoints)
slines=[l for l in lines if max(l)<len(spoints)]
return spoints,slines # return list (i,m) pairs where node index i in the subject mesh is landmark m
def generateTriAdj(tris):
'''
Generates a table (n,3) giving the indices of adjacent triangles for each triangle, with a value of `n' indicating a
free edge. The indices in each row are in sorted order rather than per triangle edge. The result is the dual of the
triangle mesh represented as the (n,3) array and a map relating the mesh's ragged edges to their triangle.
'''
edgemap = {} # maps edges to the first triangle having that edge
result=IndexMatrix(tris.getName()+'Adj',tris.n(),3)
result.fill(tris.n())
# Find adjacent triangles by constructing a map from edges defined by points (a,b) to the triangle having that edge,
# when that edge is encountered twice then the current triangle is adjacent to the one that originally added the edge.
for t1,tri in enumerate(tris): # iterate over each triangle t1
for a,b in successive(tri,2,True): # iterate over each edge (a,b) of t1
k=(min(a,b),max(a,b)) # key has uniform edge order
t2=edgemap.pop(k,None) # attempt to find edge k in the map, None indicates edge not found
if t2 is not None: # an edge is shared if already encountered, thus t1 is adjacent to t2
result[t1]=sorted(set(result[t1]+(t2,)))
result[t2]=sorted(set(result[t2]+(t1,)))
else:
edgemap[k]=t1 # first time edge is encountered, associate this triangle with it
return result,edgemap
@timing
def getAdjTo(adj,start,end):
'''
Returns a subgraph of `adj',represented as a node->[neighbours] dict, which includes nodes `start' and `end'.
If `end' is None or an index not appearing in the mesh, the result will be the submesh contiguous with `start'.
'''
visiting=set([start])
found={}
numnodes=adj.n()
while visiting and end not in found:
visit=visiting.pop()
neighbours=[n for n in adj[visit] if n<numnodes]
found[visit]=neighbours
visiting.update(n for n in neighbours if n not in found)
return found
def generateNodeElemMap(numnodes,tris):
'''Returns a list relating each node index to the set of element indices using that node.'''
nodemap=[set() for _ in range(numnodes)]
for i,tri in enumerate(tris):
for n in tri:
nodemap[n].add(i)
#assert all(len(s)>0 for s in nodemap), 'Unused nodes in triangle topology'
return nodemap
def generateSimplexEdgeMap(numnodes,simplices):
'''
Returns a list relating each node index to the set of node indices joined to it by graph edges. This assumes the mesh
has `numnodes' number of nodes and simplex topology `simplices'.
'''
nodemap=[set() for _ in range(numnodes)]
for simplex in simplices:
simplex=set(simplex)
for s in simplex:
nodemap[s].update(simplex.difference((s,)))
return nodemap
@timing
def dijkstra(adj, start, end,distFunc,acceptTri=None):
#http://benalexkeen.com/implementing-djikstras-shortest-path-algorithm-with-python/
# shortest paths is a dict of nodes to previous node and distance
paths = {start: (None,0)}
curnode = start
visited = set()
# consider only subgraph containing start and end, this expands geometrically so should contain the minimal path
adj=getAdjTo(adj,start,end)
eidolon.printFlush(len(adj))
if acceptTri is not None:
accept=lambda a: (a in adj and acceptTri(a))
else:
accept=lambda a: a in adj
while curnode != end:
visited.add(curnode)
destinations = list(filter(accept,adj[curnode]))
curweight = paths[curnode][1]
for dest in destinations:
weight = curweight+distFunc(curnode,dest)
if dest not in paths or weight < paths[dest][1]:
paths[dest] = (curnode, weight)
nextnodes = {node: paths[node] for node in paths if node not in visited}
if not nextnodes:
raise ValueError("Route %i -> %i not possible"%(start,end))
# next node is the destination with the lowest weight
curnode = min(nextnodes, key=lambda k:nextnodes[k][1])
# collect path from end node back to the start
path = []
while curnode is not None:
path.insert(0,curnode)
curnode = paths[curnode][0]
return path
def subone(v):
return tuple(i-1 for i in v)
def findNearestIndex(pt,nodelist):
return min(range(len(nodelist)),key=lambda i:pt.distToSq(nodelist[i]))
def findFarthestIndex(pt,nodelist):
return max(range(len(nodelist)),key=lambda i:pt.distToSq(nodelist[i]))
def getContiguousTris(graph,starttri,acceptTri):
accepted=[starttri]
adjacent=first(i for i in graph.getSharedNodeTris(starttri) if i not in accepted and acceptTri(i))
while adjacent is not None:
accepted.append(adjacent)
for a in accepted[::-1]:
allneighbours=graph.getSharedNodeTris(a)
adjacent=first(i for i in allneighbours if i not in accepted and acceptTri(i))
if adjacent:
break
return accepted
@timing
def findTrisBetweenNodes(start,end,landmarks,graph):
eidolon.printFlush('Nodes:',start,end)
start=landmarks[start]
end=landmarks[end]
assert 0<=start<len(graph.nodeelem)
assert 0<=end<len(graph.nodeelem)
starttri=first(graph.nodeelem[start])
endtri=first(graph.nodeelem[end])
assert starttri is not None
assert endtri is not None
nodes=graph.nodes
startnode=nodes[start]
endnode=nodes[end]
easypath= graph.getPath(starttri,endtri)
midnode=graph.tricenters[easypath[len(easypath)//2]]
# define planes to bound the areas to search for triangles to within the space of the line
splane=plane(startnode,midnode-startnode)
eplane=plane(endnode,midnode-endnode)
# adjust the plane's positions to account for numeric error
adjustdist=1e1
splane.moveUp(-adjustdist)
eplane.moveUp(-adjustdist)
assert starttri is not None
assert endtri is not None
# TODO: plane normal determination still needs work
#linenorm=midnode.planeNorm(startnode,endnode)
#linenorm=graph.getTriNorm(easypath[len(easypath)//2]).cross(midnode-startnode)
linenorm=eidolon.avg(graph.getTriNorm(e) for e in easypath).cross(midnode-startnode)
lineplane=plane(splane.center,linenorm)
indices=set([starttri,endtri]) # list of element indices on lineplane between splane and eplane
for i in range(graph.tris.n()):
trinodes=graph.getTriNodes(i)
numabove=lineplane.numPointsAbove(trinodes)
if numabove in (1,2) and splane.between(trinodes,eplane):
indices.add(i)
accepted=getContiguousTris(graph,starttri,lambda i:i in indices)
if endtri not in accepted or len(easypath)<len(accepted):
eidolon.printFlush('---Resorting to easypath')
accepted=easypath
return accepted
@timing
def assignRegion(region,index,assignmat,landmarks,linemap,graph):
def getEnclosedGraph(adj,excludes,start):
visiting=set([start])
found=set()
numnodes=adj.n()
assert start is not None
while visiting:
visit=visiting.pop()
neighbours=[n for n in adj.getRow(visit) if n<numnodes and n not in excludes]
found.add(visit)
visiting.update(n for n in neighbours if n not in found)
return found
# collect all tri indices on the border of this region
bordertris=set()
for lineindex,(a,b) in region.items():
if (a,b) in linemap:
line=linemap[(a,b)]
else:
line=findTrisBetweenNodes(a,b,landmarks,graph)
linemap[(a,b)]=line
linemap[(b,a)]=line
# assign line ID to triangles on the line
for tri in line:
assignmat[tri,0]=lineindex
bordertris.update(line)
bordertri=graph.tricenters[first(bordertris)]
farthest=max(range(len(graph.tris)),key=lambda i:graph.tricenters[i].distToSq(bordertri))
maxgraph=getEnclosedGraph(graph.adj,bordertris,farthest)
for tri in range(len(graph.tris)):
if tri in bordertris or tri not in maxgraph:
if assignmat[tri,1]<0:
assignmat[tri,1]=index
elif assignmat[tri,2]<0:
assignmat[tri,2]=index
elif assignmat[tri,3]<0:
assignmat[tri,3]=index
@timing
def generateRegionField(obj,landmarkObj,regions,appendageregion,appendagenode,task=None):
ds=obj.datasets[0]
nodes=ds.getNodes()
tris=first(ind for ind in ds.enumIndexSets() if ind.m()==3 and bool(ind.meta(StdProps._isspatial)))
lmnodes=landmarkObj.datasets[0].getNodes()
linemap={}
landmarks={i:nodes.indexOf(lm)[0] for i,lm in enumerate(lmnodes)}
assert all(0<=l<nodes.n() for l in landmarks)
graph=TriMeshGraph(nodes,tris)
edgenodeinds=set(eidolon.listSum(graph.ragged)) # list of all node indices on the ragged edge
filledregions=RealMatrix(fieldNames._regions,tris.n(),4)
filledregions.meta(StdProps._elemdata,'True')
filledregions.fill(-10)
#landmarks[appendagenode]=0 # TODO: skipping appendage node for now
for region in regions:
for a,b in region.values():
if appendagenode not in (a,b):
if a in landmarks and b not in landmarks:
oldlmnode=nodes[landmarks[a]]
newlm=b
elif b in landmarks and a not in landmarks:
oldlmnode=nodes[landmarks[b]]
newlm=a
else:
continue
newlmnode=min(edgenodeinds,key=lambda i:nodes[i].distToSq(oldlmnode)) # ragged edge node closest to landmark
landmarks[newlm]=newlmnode
# eidolon.printFlush(newlm,newlmnode,graph.getPath(min(a,b),newlmnode),'\n')
# line=findTrisBetweenNodes(a,b,landmarks,graph)
# for tri in line:
# filledregions[tri,0]=max(a,b)
if task:
task.setMaxProgress(len(regions))
for rindex,region in enumerate(regions):
eidolon.printFlush('Region',rindex,'of',len(regions),region)
allnodes=set(eidolon.listSum(region.values()))
if all(a in landmarks for a in allnodes):
assignRegion(region,rindex,filledregions,landmarks,linemap,graph)
else:
eidolon.printFlush('Skipping',rindex,[a for a in allnodes if a not in landmarks])
if task:
task.setProgress(rindex+1)
return filledregions,linemap
def extractTriRegion(nodes,tris,acceptFunc):
'''
Extract the region from the mesh (nodes,tris) as defined by the triangle acceptance function `acceptFunc'. The return
value is a tuple containing the list of new nodes, a list of new tris, a map from old node indices in `nodes' to new
indices in the returned node list, and a map from triangle indices in `tris' to new ones in the returned triangle list.
'''
#old -> new
newnodes=[] # new node set
newtris=[] # new triangle set
nodemap={} # maps old node indices to new
trimap={} # maps old triangle indices to new
for tri in range(len(tris)):
if acceptFunc(tri):
newtri=list(tris[tri])
for i,n in enumerate(newtri):
if n not in nodemap:
nodemap[n]=len(newnodes)
newnodes.append(nodes[n])
newtri[i]=nodemap[n]
trimap[tri]=len(newtris)
newtris.append(newtri)
return newnodes,newtris,nodemap,trimap
def calculateMeshGradient(prefix,nodes,elems,groups,VTK):
'''Calculate the laplace gradient for the mesh given as (nodes,elems,groups) using sfepy.'''
tempdir=os.path.dirname(prefix)
infile=prefix+'.mesh'
logfile=prefix+'.log'
outfile=prefix+'.vtk'
probfile=prefix+'.py'
writeMeshFile(infile,nodes,elems,groups,None,3)
with open(problemFile) as p:
with open(probfile,'w') as o:
o.write(p.read()%{'inputfile':infile,'outdir':tempdir})
p=ProblemConf.from_file(probfile)
output.set_output(logfile,True,True)
solve_pde(p)
robj=VTK.loadObject(outfile)
return robj.datasets[0].getDataField('t')
@timing
def calculateGradientDirs(nodes,edges,gradientField):
'''
Returns a RealMatrix object containing the vector field for each node of `nodes' pointing in the gradient direction
for the given field RealMatrix object `gradientField'. The `edges' argument is a map relating each node index to the
set of node indices sharing an edge with that index.
'''
#https://math.stackexchange.com/questions/2627946/how-to-approximate-numerically-the-gradient-of-the-function-on-a-triangular-mesh/2632616#2632616
numnodes=len(nodes)
nodedirs=[]#eidolon.RealMatrix(gradientDirField,numnodes,3)
for n in range(numnodes):
edgenodes=edges[n]
if edgenodes:
ngrad=gradientField[n]
nnode=nodes[n]
edgegrads=[gradientField[i]-ngrad for i in edgenodes] # field gradient in edge directions
edgedirs=[nodes[i]-nnode for i in edgenodes] # edge directional vectors
# minlen=min(e.lenSq() for e in edgedirs)**0.5
edgedirs=[list(e) for e in edgedirs]
# node direction is solution for x in Ax=b where A is edge directions and b edge gradients
nodedir=np.linalg.lstsq(np.asarray(edgedirs),np.asarray(edgegrads),rcond=None)
#nodedirs[n]=vec3(*nodedir[0]).norm()*minlen
nodedirs.append(vec3(*nodedir[0]).norm())
else:
nodedirs.append(vec3())
return nodedirs
@timing
def calculateDirectionField(obj,landmarkObj,regions,regtype,tempdir,VTK):
lmlines,allregions,lmstim,lmground=loadArchitecture(architecture,regtype)[1:5]
regions=regions or list(range(len(allregions)))
ds=obj.datasets[0]
nodes=ds.getNodes()
tris=first(ind for ind in ds.enumIndexSets() if ind.m()==3 and bool(ind.meta(StdProps._isspatial)))
regionfield=ds.getDataField(fieldNames._regions)
regionfield=np.asarray(regionfield,np.int32)
lmnodes=landmarkObj.datasets[0].getNodes()
landmarks=[nodes.indexOf(lm)[0] for lm in lmnodes]
directionfield=RealMatrix(fieldNames._directions,nodes.n(),3)
directionfield.fill(0)
gradientfield=RealMatrix('gradient',nodes.n(),1)
gradientfield.fill(-1)
obj.datasets[0].setDataField(gradientfield)
obj.datasets[0].setDataField(directionfield)
def selectRegion(region,triregions):
return region==int(triregions[0]) or region==int(triregions[1]) or region==int(triregions[2])
def collectNodes(nodemap,trimap,components):
'''Collect the nodes for the given components, being lines or landmark points.'''
nodeinds=set()
for comp in components:
if comp[0]=='L':
lind=int(comp[1:])-1
for tri in trimap:
if int(regionfield[tri,0])==lind:
nodeinds.update(nodemap[t] for t in tris[tri])
else:
nodeinds.add(nodemap[landmarks[int(comp[1:])-1]])
return nodeinds
# for each region calculate the laplace gradient and fill in the direction field
for r in regions:
eidolon.printFlush('Region',r,lmstim[r],lmground[r])
try:
newnodes,newtris,nodemap,trimap=extractTriRegion(nodes,tris,lambda i:selectRegion(r,regionfield[i,1:]))
assert len(newtris)>0, 'Empty region selected'
stimnodes=collectNodes(nodemap,trimap,lmstim[r])
groundnodes=collectNodes(nodemap,trimap,lmground[r])
if len(stimnodes)==0:
raise ValueError('Region %i has no stim nodes'%r)
elif not all(0<=s<len(newnodes) for s in stimnodes):
raise ValueError('Region %i has invalid stim nodes: %r'%(r,stimnodes))
if len(groundnodes)==0:
raise ValueError('Region %i has no ground nodes'%r)
elif not all(0<=s<len(newnodes) for s in groundnodes):
raise ValueError('Region %i has invalid ground nodes: %r'%(r,groundnodes))
# convert triangles to tets
for t in range(len(newtris)):
a,b,c=[newnodes[i] for i in newtris[t]]
norm=a.planeNorm(b,c)
newtris[t].append(len(newnodes))
newnodes.append(avg((a,b,c))+norm)
nodegroup=[1 if n in stimnodes else (2 if n in groundnodes else 0) for n in range(len(newnodes))]
assert 1 in nodegroup, 'Region %i does not assign stim nodes (%r)'%(r,stimnodes)
assert 2 in nodegroup, 'Region %i does not assign ground nodes (%r)'%(r,groundnodes)
gfield=calculateMeshGradient(os.path.join(tempdir,'region%.2i'%r),newnodes,newtris,nodegroup,VTK)
for oldn,newn in nodemap.items():
gradientfield[oldn,0]=gfield[newn]
graddirs=calculateGradientDirs(newnodes,generateSimplexEdgeMap(len(newnodes),newtris),gfield)
for oldn,newn in nodemap.items():
directionfield[oldn]=graddirs[newn]+vec3(*directionfield[oldn])
except Exception as e:
eidolon.printFlush(e)
return gradientfield,directionfield
@timing
def getElemDirectionAdj(nodes,elems,adj,dirField):
'''
Generate an index matrix with a row for each element of `elems' storing which face is the forward direction of the
directional field `dirField', which adjanct element is in the forward direction, which face is in the backward
direction, and which adjacent element is in the backward direction.
'''
assert len(nodes)==len(dirField)
et=ElemType[elems.getType()]
result=IndexMatrix('diradj',elems.n(),4)
result.meta(StdProps._elemdata,'True')
result.fill(elems.n())
def getFaceInDirection(start,direction,enodes):
dray=eidolon.Ray(start,direction)
for f,face in enumerate(et.faces):
fnodes=[enodes[i] for i in face[:3]]
if dray.intersectsTri(*fnodes):
return f
return None
for e,elem in enumerate(elems):
edirs=[vec3(*dirField[n]) for n in elem] # elem directions
enodes=[nodes[n] for n in elem] # elem nodes
edir=et.applyBasis(edirs,0.25,0.25,0.25) # elem center
center=et.applyBasis(enodes,0.25,0.25,0.25) # elem center
forward=getFaceInDirection(center,edir,enodes)
result[e,0]=forward
result[e,1]=adj[e,forward]
backward=getFaceInDirection(center,-edir,enodes)
result[e,2]=backward
result[e,3]=adj[e,backward]
assert result[e,0]<elems.n()
return result
@timing
def followElemDirAdj(elemdiradj,task=None):
'''
Follow the direction adjacency matrix `elemdiradj', storing a row for each element stating the final forward element,
final forward face, final backward element, and final backward face. The given element/face pairs are on the mesh
surface.
'''
result=IndexMatrix('diradj',elemdiradj.n(),4)
result.fill(elemdiradj.n())
result.meta(StdProps._elemdata,'True')
def followElem(start,isForward):
'''From the starting element, follow the adjacency hops until a surface element is found.'''
curelem=start
index=1 if isForward else 3
visited=set()
while curelem not in visited and curelem>=start and elemdiradj[curelem,index]<elemdiradj.n():
visited.add(curelem)
curelem=elemdiradj[curelem,index]
if curelem<start: # previously assigned value, use this since the path from here on is the same
return result[curelem,index-1]
else:
return curelem
if task:
task.setMaxProgress(elemdiradj.n())
for e in range(elemdiradj.n()):
forward=followElem(e,True)
result[e,0]=forward
result[e,1]=elemdiradj[forward,0]
backward=followElem(e,False)
result[e,2]=backward
result[e,3]=elemdiradj[backward,2]
if task:
task.setProgress(e+1)
return result
@timing
def estimateThickness(nodes,tets,elemdiradj,task=None):
'''
Follow the direction adjacency matrix `elemdiradj', and estimate thickness by measuring how far each tet along the
path to the forward and backward surface is. The assigned value in the returned field is the maximal estimated
thickness for each element.
'''
result=RealMatrix(fieldNames._elemThickness,tets.n(),1)
result.fill(elemdiradj.n())
result.meta(StdProps._elemdata,'True')
result.fill(-1)
def getTetCenter(ind):
return avg(nodes.mapIndexRow(tets,ind))
def followElem(start,isForward):
curelem=start
index=1 if isForward else 3
visited=set()
curpos=getTetCenter(start)
dist=0
while elemdiradj[curelem,index]<elemdiradj.n():
visited.add(curelem)
curelem=elemdiradj[curelem,index]
if curelem in visited: # circular path, assign no value to this element
dist=0
break
else:
nextpos=getTetCenter(curelem)
dist+=nextpos.distTo(curpos)
curpos=nextpos
return dist
if task:
task.setMaxProgress(elemdiradj.n())
for e in range(elemdiradj.n()):
result[e]=max(result[e],followElem(e,True)+followElem(e,False))
if task:
task.setProgress(e+1)
return result
@timing
def calculateTetDirections(tetmesh,endomesh,epimesh,tempdir,interpFunc,VTK,task=None):
def getTriCenterOctree(obj,ocdepth=2):
ds=obj.datasets[0]
nodes=ds.getNodes()
tris=first(i for i in ds.enumIndexSets() if i.getType()==ElemType._Tri1NL)
graph=TriMeshGraph(nodes,tris)
centeroc=eidolon.Octree(ocdepth,graph.boundbox.getDimensions(),graph.boundbox.center)
for i,c in enumerate(graph.tricenters):
centeroc.addNode(c,i)
return graph,centeroc,ds.getDataField(fieldNames._directions),ds.getDataField(fieldNames._regions)
if interpFunc is None:
interpFunc=lambda dir1,dir2,grad:tuple(dir1*grad+dir2*(1-grad))
et=ElemType.Tet1NL
faces=[f[:3] for f in et.faces]
ds=tetmesh.datasets[0]
eidolon.calculateElemExtAdj(ds)
nodes=ds.getNodes()
tets=first(i for i in ds.enumIndexSets() if i.getType()==ElemType._Tet1NL)
adj=ds.getIndexSet(tets.getName()+eidolon.MatrixType.adj[1])
numElems=tets.n()
elemdirfield=RealMatrix(fieldNames._elemDirs,tets.n(),3)
elemdirfield.fill(0)
elemdirfield.meta(StdProps._elemdata,'True')
ds.setDataField(elemdirfield)
elemregions=RealMatrix(fieldNames._regions,tets.n(),4)
elemregions.meta(StdProps._elemdata,'True')
elemregions.fill(-1)
ds.setDataField(elemregions)
endograph,endooc,endodirs,endoregions=getTriCenterOctree(endomesh)
epigraph,epioc,epidirs,epiregions=getTriCenterOctree(epimesh)
# set of nodes from the tet mesh on each surface
endonodes=set()
epinodes=set()
def calculateTriDir(graph,tri,dirs):
inds=graph.tris[tri]
trinodes=[graph.nodes[i] for i in inds]
trinorm=trinodes[0].planeNorm(trinodes[1],trinodes[2])
tridir=avg(vec3(*dirs[i]).norm() for i in inds)
return tridir.planeProject(vec3(),trinorm).norm()
# iterate over each element and fill in the above map and set values for endonodes, epinodes, and elemregions
for elem in range(numElems):
externs=adj[elem,:4]
extfaces=[f for i,f in enumerate(faces) if externs[i]==numElems]
for face in extfaces:
faceinds=[tets[elem,i] for i in face]
mid=avg(nodes[i] for i in faceinds)
tridir=None
if mid in endooc:
tri=endooc.getNode(mid)
tridir=calculateTriDir(endograph,tri,endodirs)
endonodes.update(faceinds)
elemregions[elem]=endoregions[tri]
elif mid in epioc:
tri=epioc.getNode(mid)
tridir=calculateTriDir(epigraph,tri,epidirs)
epinodes.update(faceinds)
elemregions[elem]=epiregions[tri]
# set the direction for the equivalent element
if tridir is not None:
elemdirfield[elem]=tuple(tridir)
assert endonodes
assert epinodes
nodegroup=[1 if n in endonodes else (2 if n in epinodes else 0) for n in range(len(nodes))]
gfield=calculateMeshGradient(os.path.join(tempdir,'tetmesh'),nodes,tets,nodegroup,VTK)
gfield.setName(fieldNames._nodeGradient)
ds.setDataField(gfield)
# convert gradient into node directions
dirs=calculateGradientDirs(nodes,generateSimplexEdgeMap(nodes.n(),tets),gfield)
# follow gradient and determine which elements/faces are the forward and backward endpoints of each element's gradient line
elemdiradj=getElemDirectionAdj(nodes,tets,adj,dirs)
elemFollow=followElemDirAdj(elemdiradj,task)
elemThickness=estimateThickness(nodes,tets,elemdiradj,task)
ds.setDataField(elemThickness)
for e in range(tets.n()):
elem1,face1,elem2,face2=elemFollow[e]
dir1=elemdirfield[elem1]
dir2=elemdirfield[elem2]
grad=avg(gfield[i] for i in tets[e])
elemdirfield[e]=interpFunc(vec3(*dir1),vec3(*dir2),grad)
return elemdirfield
### Project objects
class AtrialFibrePropWidget(ui.QtWidgets.QWidget,ui.Ui_AtrialFibre):
def __init__(self,parent=None):
super(AtrialFibrePropWidget,self).__init__(parent)
self.setupUi(self)
self.endoDoneButton.setVisible(False)
self.endoCancelButton.setVisible(False)
self.epiDoneButton.setVisible(False)
self.epiCancelButton.setVisible(False)
def startEdit(self,regtype):
'''Adjust button visibility and connected slots when starting to edit endo or epi nodes.'''
if regtype==regTypes._endo:
edit,other=self.endoEdit,self.epiEdit
done,cancel=self.endoDoneButton,self.endoCancelButton
else:
edit,other=self.epiEdit,self.endoEdit
done,cancel=self.epiDoneButton,self.epiCancelButton
# adjust button visibility
other.setEnabled(False)
edit.setVisible(False)
done.setVisible(True)
cancel.setVisible(True)
try: # if the edit button's been already clicked, disconnect existing slots
done.clicked.disconnect()
cancel.clicked.disconnect()
except:
pass
return done,cancel
def stopEdit(self):
'''Set UI back to default when done editing.'''
self.endoEdit.setVisible(True)
self.epiEdit.setVisible(True)
self.endoEdit.setEnabled(True)
self.epiEdit.setEnabled(True)
self.endoDoneButton.setVisible(False)
self.endoCancelButton.setVisible(False)
self.epiDoneButton.setVisible(False)
self.epiCancelButton.setVisible(False)
class AtrialFibreProject(Project):
def __init__(self,name,parentdir,mgr):
Project.__init__(self,name,parentdir,mgr)
self.header='AtrialFibre.createProject(%r,scriptdir+"/..")\n' %(self.name)
self.AtrialFibre=mgr.getPlugin('AtrialFibre')
self.VTK=self.mgr.getPlugin('VTK')
self.AtrialFibre.project=self # associate project with plugin
self.backDir=self.logDir=self.getProjectFile('logs')
self.editRep=None # node representation being edited
self.addHandlers()
def create(self):
Project.create(self)
if not os.path.isdir(self.logDir):
os.mkdir(self.logDir)
def getPropBox(self):
prop=Project.getPropBox(self)
# remove the UI for changing the project location
eidolon.cppdel(prop.chooseLocLayout)
eidolon.cppdel(prop.dirButton)
eidolon.cppdel(prop.chooseLocLabel)
self.afprop=AtrialFibrePropWidget()
prop.verticalLayout.insertWidget(prop.verticalLayout.count()-1,self.afprop)
def setConfigMap(combo,name):
@combo.currentIndexChanged.connect
def _set(i):
self.configMap[name]=str(combo.itemText(i))
setConfigMap(self.afprop.atlasBox,objNames._atlasmesh)
setConfigMap(self.afprop.origBox,objNames._origmesh)
setConfigMap(self.afprop.endoBox,objNames._endomesh)
setConfigMap(self.afprop.epiBox,objNames._epimesh)
self.afprop.importShellButton.clicked.connect(self._importShell)
self.afprop.endoReg.clicked.connect(lambda:self._registerLandmarks(objNames._endomesh,regTypes._endo))
self.afprop.endoDiv.clicked.connect(lambda:self._divideRegions(objNames._endomesh,regTypes._endo))
self.afprop.endoEdit.clicked.connect(lambda:self._editLandmarks(objNames._endomesh,regTypes._endo))
self.afprop.epiReg.clicked.connect(lambda:self._registerLandmarks(objNames._epimesh,regTypes._epi))
self.afprop.epiDiv.clicked.connect(lambda:self._divideRegions(objNames._epimesh,regTypes._epi))
self.afprop.epiEdit.clicked.connect(lambda:self._editLandmarks(objNames._epimesh,regTypes._epi))
self.afprop.genButton.clicked.connect(self._generate)
return prop
def updatePropBox(self,proj,prop):
Project.updatePropBox(self,proj,prop)
scenemeshes=[o for o in self.memberObjs if isinstance(o,eidolon.MeshSceneObject)]
names=sorted(o.getName() for o in scenemeshes)
def _fillList(combo,name):
# ensure the config value is actually set, when filling a previously empty list currentIndexChanged isn't emitted
if not self.configMap.get(name,None):
self.configMap[name]=first(names)
eidolon.fillList(combo,names,self.configMap[name])
_fillList(self.afprop.atlasBox,objNames._atlasmesh)
_fillList(self.afprop.origBox,objNames._origmesh)
_fillList(self.afprop.endoBox,objNames._endomesh)
_fillList(self.afprop.epiBox,objNames._epimesh)
@taskmethod('Adding Object to Project')
def checkIncludeObject(self,obj,task):
'''Check whether the given object should be added to the project or not.'''
if not isinstance(obj,eidolon.MeshSceneObject) or obj in self.memberObjs or obj.getObjFiles() is None:
return
@timing
def _copy():
self.mgr.removeSceneObject(obj)
self.addMesh(obj)
pdir=self.getProjectDir()
files=list(map(os.path.abspath,obj.getObjFiles() or []))
if not files or any(not f.startswith(pdir) for f in files):
msg="Do you want to add %r to the project? This requires saving/copying the object's file data into the project directory."%(obj.getName())
self.mgr.win.chooseYesNoDialog(msg,'Adding Object',_copy)
def addMesh(self,obj):
filename=self.getProjectFile(obj.getName())
self.VTK.saveObject(obj,filename,setFilenames=True)
self.addObject(obj)
self.mgr.addSceneObject(obj)
self.save()
def createTempDir(self,prefix='tmp'):
path=self.getProjectFile(prefix+datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
os.mkdir(path)
return path
def _importShell(self):
filename=self.mgr.win.chooseFileDialog('Choose Endo/Epi Shell filename',filterstr='VTK Files (*.vtk *.vtu *.vtp)')
if filename:
f=self.AtrialFibre.importShell(filename)
self.mgr.checkFutureResult(f)
@taskroutine('Add meshes')
def _add(task):
endo,epi=f()
self.addMesh(endo)
self.addMesh(epi)
self.mgr.runTasks(_add())
def _registerLandmarks(self,meshname,regtype):
atlas=self.getProjectObj(self.configMap.get(objNames._atlasmesh,''))
subj=self.getProjectObj(self.configMap.get(meshname,''))
assert atlas is not None
assert subj is not None
endo=self.getProjectObj(regtype)
if endo is not None:
self.mgr.removeSceneObject(endo)
tempdir=self.createTempDir('reg')
result=self.AtrialFibre.registerLandmarks(subj,atlas,regtype,tempdir)
self.mgr.checkFutureResult(result)
@taskroutine('Add points')
def _add(task):
name=regtype+'nodes'
oldobj=self.getProjectObj(name)
if oldobj is not None:
self.mgr.removeSceneObject(oldobj)
obj=eidolon.Future.get(result)
obj.setName(name)
self.addMesh(obj)
registered=os.path.join(tempdir,registeredFile)
regobj=self.VTK.loadObject(registered,regtype+'_RegMesh')
self.addMesh(regobj)
self.mgr.runTasks(_add())
def _editLandmarks(self,meshname,regtype):
surface=self.getProjectObj(self.configMap[meshname])
landmarks=self.getProjectObj(regtype+'nodes')
landmarkMap={} # maps landmark index to surface node index
if surface is None:
self.mgr.showMsg('Cannot find surface object %r'%self.configMap[meshname])
return
elif landmarks is None:
self.mgr.showMsg('Cannot find landmark object %r'%(regtype+'nodes'))
return
f=self._startEditLandmarks(surface,landmarks,landmarkMap)
self.mgr.checkFutureResult(f)
done,cancel=self.afprop.startEdit(regtype) # adjust UI and get done and cancel buttons
@cancel.clicked.connect
def _cancel():
'''Resets UI when the cancel button is pressed.'''
self.afprop.stopEdit()
self.mgr.removeSceneObjectRepr(self.editRep)
self.editRep=None
@done.clicked.connect
def _done():
'''Transfer data from moved repr to landmark object, save, and reset UI.'''
lmnodes=landmarks.datasets[0].getNodes()
surfacenodes=surface.datasets[0].getNodes()
for i,j in landmarkMap.items():
lmnodes[i]=surfacenodes[j]
f=landmarks.saveObject(landmarks.getObjFiles()[0])
self.mgr.checkFutureResult(f)
cancel.clicked.emit() # do cancel's cleanup
@taskmethod('Starting to edit landmarks')
def _startEditLandmarks(self,surface,landmarks,landmarkMap,task):
if not surface.reprs:
rep=surface.createRepr(ReprType._volume,0)
self.mgr.addSceneObjectRepr(rep)
noderep=landmarks.createRepr(ReprType._line,matname='Red')
self.mgr.addSceneObjectRepr(noderep)
self.editRep=noderep
landmarknodes=landmarks.datasets[0].getNodes()
editnodes=surface.datasets[0].getNodes()
query=createNodeQuery(editnodes)
handlecol=eidolon.color(1,0,0,1)
def _select(handle,index,release):
'''Handle selection callback function, updates landmarkMap and node positions in noderep.'''
if release: # on mouse release update the repr
f=self.mgr.updateSceneObjectRepr(noderep)
self.mgr.checkFutureResult(f)
else:
oldpos=handle.positionOffset
newpos=editnodes[index]
landmarkMap[handle.value]=index
for n in range(noderep.nodes.n()): # replace every old position with the new
if noderep.nodes[n,0]==oldpos:
noderep.nodes[n,0]=newpos
@eidolon.setmethod(noderep)
def createHandles():
'''Overrides the default node creation method to create selection handles instead.'''
handles=[]
for ind in range(landmarknodes.n()):
pos=landmarknodes[ind]
h=eidolon.NodeSelectHandle(pos,ind,query,_select,' '+str(ind),handlecol)
handles.append(h)
return handles
self.mgr.showHandle(noderep,True)
self.mgr.setCameraSeeAll()
def _divideRegions(self,meshname,regtype):
mesh=self.getProjectObj(self.configMap.get(meshname,''))
points=self.getProjectObj(regtype+'nodes')
assert mesh is not None
assert points is not None
result=self.AtrialFibre.divideRegions(mesh,points,regtype)
self.mgr.checkFutureResult(result)
@taskroutine('Save mesh')
def _save(task):
self.VTK.saveObject(mesh,mesh.getObjFiles()[0])
rep=mesh.createRepr(eidolon.ReprType._volume,0)
self.mgr.addSceneObjectRepr(rep)
rep.applyMaterial('Rainbow',field=fieldNames._regions,valfunc='Column 1')
self.mgr.setCameraSeeAll()
# lobj,lrep=showLines(points.datasets[0].getNodes(),lmlines,'AllLines','Red')
self.mgr.runTasks(_save())
def _generate(self):
tetmesh=self.getProjectObj(self.configMap.get(objNames._origmesh,''))
endomesh=self.getProjectObj(self.configMap.get(objNames._endomesh,''))
epimesh=self.getProjectObj(self.configMap.get(objNames._epimesh,''))
if tetmesh is None:
self.mgr.showMsg('Cannot find original tet mesh %r'%self.configMap.get(objNames._endomesh,''))
elif endomesh is None:
self.mgr.showMsg('Cannot find endo mesh %r'%self.configMap.get(objNames._endomesh,''))
elif epimesh is None:
self.mgr.showMsg('Cannot find epi mesh %r'%self.configMap.get(objNames._epimesh,''))
elif endomesh.datasets[0].getDataField('regions') is None:
self.mgr.showMsg('Endo mesh does not have region field assigned!')
elif epimesh.datasets[0].getDataField('regions') is None:
self.mgr.showMsg('Epi mesh does not have region field assigned!')
else:
tempdir=self.createTempDir('dirs')
endopoints=self.getProjectObj('endonodes')
epipoints=self.getProjectObj('epinodes')
regions=[]
result=self.AtrialFibre.generateMesh(endomesh,epimesh,tetmesh,endopoints,epipoints,tempdir,regions)
self.mgr.checkFutureResult(result)
@taskroutine('Save')
def _save(task):
self.VTK.saveObject(tetmesh,tetmesh.getObjFiles()[0])
@taskroutine('Load Rep')
def _load(task):
#rep=endomesh.createRepr(ReprType._volume,0)
#self.mgr.addSceneObjectRepr(rep)
#rep.applyMaterial('Rainbow',field='gradient',valfunc='Column 1')
rep=tetmesh.createRepr(ReprType._volume,0)
self.mgr.addSceneObjectRepr(rep)
rep.applyMaterial('Rainbow',field=fieldNames._elemDirs,valfunc='Magnitude')
self.mgr.setCameraSeeAll()
showElemDirs(tetmesh,(50,50,100),self.mgr) # TODO: replace with createRepr call
self.mgr.runTasks([_save(),_load()])
class AtrialFibrePlugin(ScenePlugin):
def __init__(self):
ScenePlugin.__init__(self,'AtrialFibre')
self.project=None
def init(self,plugid,win,mgr):
ScenePlugin.init(self,plugid,win,mgr)
self.VTK=self.mgr.getPlugin('VTK')
assert self.VTK is not None, 'Cannot find VTK plugin!'
if self.win!=None:
self.win.addMenuItem('Project','AtrialFibreProj'+str(plugid),'&Atrial Fibre Project',self._newProjDialog)
# extract the deformetrica zip file if not present
if not os.path.isdir(deformDir):
z=zipfile.ZipFile(deformDir+'.zip')
z.extractall(plugindir)
os.chmod(deformExe,stat.S_IRUSR|stat.S_IXUSR|stat.S_IWUSR)
self.mirtkdir=os.path.join(eidolon.getAppDir(),eidolon.LIBSDIR,'MIRTK','Linux')
eidolon.addPathVariable('LD_LIBRARY_PATH',self.mirtkdir)
self.decimate=os.path.join(self.mirtkdir,decimate)
def _newProjDialog(self):
def chooseProjDir(name):
newdir=self.win.chooseDirDialog('Choose Project Root Directory')
if len(newdir)>0:
self.createProject(name,newdir)
self.win.chooseStrDialog('Choose Project Name','Project',chooseProjDir)
def createProject(self,name,parentdir):
if self.project==None:
self.mgr.createProjectObj(name,parentdir,AtrialFibreProject)
def getArchitecture(self,regtype=regTypes._endo):
return loadArchitecture(architecture,regtype)
@taskmethod('Import endo/epi shell')
def importShell(self,filename,task=None):
shells=self.VTK.loadObject(filename)
ds=shells.datasets[0]
nodes=ds.getNodes()
tris=first(ds.enumIndexSets())
adj,_=generateTriAdj(tris)
center=avg(nodes) #BoundBox(nodes).center
findex=findFarthestIndex(center,nodes)
outerinds=getAdjTo(adj,findex,None)
outertris=listToMatrix([tris[i] for i in outerinds],'tris',ElemType._Tri1NL)
innertris=listToMatrix([tris[i] for i in range(tris.n()) if i not in outerinds],'tris',ElemType._Tri1NL)
assert outertris.n()>0
assert innertris.n()>0
outermesh=reduceMesh(nodes,[outertris],marginSq=1e-1)
innermesh=reduceMesh(nodes,[innertris],marginSq=1e-1)
generateNodeElemMap(outermesh[0].n(),outermesh[1][0])
generateNodeElemMap(innermesh[0].n(),innermesh[1][0])
# TODO: not reliably telling inner from outer shell, until that's better use ambiguous mesh names and have user choose
outer=MeshSceneObject('shell1',PyDataSet('ds',outermesh[0],outermesh[1]))
inner=MeshSceneObject('shell2',PyDataSet('ds',innermesh[0],innermesh[1]))
return inner,outer
@taskmethod('Registering landmarks')
def registerLandmarks(self,meshObj,atlasObj,regtype,outdir,task=None):
if atlasObj.reprs:
atlasTrans=atlasObj.reprs[0].getTransform()
else:
atlasTrans=None
output=registerSubjectToTarget(meshObj,atlasObj,atlasTrans,outdir,self.decimate,self.VTK)
eidolon.printFlush(output)
points,lines=transferLandmarks(architecture,regtype,atlasObj,atlasTrans,meshObj,outdir,self.VTK)
subjnodes=meshObj.datasets[0].getNodes()
ptds=eidolon.PyDataSet('pts',[subjnodes[n[0]] for n in points],[('lines',ElemType._Line1NL,lines)])
return eidolon.MeshSceneObject('LM',ptds)
@taskmethod('Dividing mesh into regions')
def divideRegions(self,mesh,points,regtype,task=None):
_,_,lmregions,_,_,appendageregion,appendagenode,_=loadArchitecture(architecture,regtype)
filledregions,linemap=generateRegionField(mesh,points,lmregions,appendageregion,appendagenode,task)
mesh.datasets[0].setDataField(filledregions)
@taskmethod('Generating mesh')
def generateMesh(self,endomesh,epimesh,tetmesh,endopoints,epipoints,outdir,regions=[],task=None):
endograd,endodir=calculateDirectionField(endomesh,endopoints,regions,regTypes._endo,outdir,self.VTK)
epigrad,epidir=calculateDirectionField(epimesh,epipoints,regions,regTypes._epi,outdir,self.VTK)
return calculateTetDirections(tetmesh,endomesh,epimesh,outdir,None,self.VTK,task)
### Add the project
eidolon.addPlugin(AtrialFibrePlugin()) # note this occurs after other projects are loaded and is not in the subprocesses namespaces
| [
"sfepy.base.base.output.set_output",
"sfepy.base.conf.ProblemConf.from_file",
"sfepy.applications.solve_pde"
] | [((1102, 1149), 'os.path.join', 'os.path.join', (['plugindir', '"""AtrialFibrePlugin.ui"""'], {}), "(plugindir, 'AtrialFibrePlugin.ui')\n", (1114, 1149), False, 'import os\n'), ((1160, 1200), 'os.path.join', 'os.path.join', (['plugindir', '"""deformetricaC"""'], {}), "(plugindir, 'deformetricaC')\n", (1172, 1200), False, 'import os\n'), ((1210, 1249), 'os.path.join', 'os.path.join', (['deformDir', '"""deformetrica"""'], {}), "(deformDir, 'deformetrica')\n", (1222, 1249), False, 'import os\n'), ((1262, 1305), 'os.path.join', 'os.path.join', (['plugindir', '"""architecture.ini"""'], {}), "(plugindir, 'architecture.ini')\n", (1274, 1305), False, 'import os\n'), ((1318, 1359), 'os.path.join', 'os.path.join', (['plugindir', '"""problemfile.py"""'], {}), "(plugindir, 'problemfile.py')\n", (1330, 1359), False, 'import os\n'), ((1993, 2123), 'eidolon.enum', 'eidolon.enum', (['"""regions"""', '"""landmarks"""', '"""directions"""', '"""gradientDirs"""', '"""elemDirs"""', '"""elemRegions"""', '"""elemThickness"""', '"""nodeGradient"""'], {}), "('regions', 'landmarks', 'directions', 'gradientDirs',\n 'elemDirs', 'elemRegions', 'elemThickness', 'nodeGradient')\n", (2005, 2123), False, 'import eidolon\n'), ((2145, 2250), 'eidolon.enum', 'eidolon.enum', (['"""atlasmesh"""', '"""origmesh"""', '"""epimesh"""', '"""epinodes"""', '"""endomesh"""', '"""endonodes"""', '"""architecture"""'], {}), "('atlasmesh', 'origmesh', 'epimesh', 'epinodes', 'endomesh',\n 'endonodes', 'architecture')\n", (2157, 2250), False, 'import eidolon\n'), ((2277, 2304), 'eidolon.enum', 'eidolon.enum', (['"""endo"""', '"""epi"""'], {}), "('endo', 'epi')\n", (2289, 2304), False, 'import eidolon\n'), ((1020, 1045), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (1035, 1045), False, 'import os\n'), ((2471, 2492), 'eidolon.getSceneMgr', 'eidolon.getSceneMgr', ([], {}), '()\n', (2490, 2492), False, 'import eidolon\n'), ((2504, 2550), 'eidolon.LineDataSet', 'eidolon.LineDataSet', (["(name + 'DS')", 'nodes', 'lines'], {}), "(name + 'DS', nodes, lines)\n", (2523, 2550), False, 'import eidolon\n'), ((2555, 2584), 'eidolon.MeshSceneObject', 'MeshSceneObject', (['name', 'lineds'], {}), '(name, lineds)\n', (2570, 2584), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((2970, 3009), 'eidolon.ElemType.Tet1NL.basis', 'ElemType.Tet1NL.basis', (['(0.25)', '(0.25)', '(0.25)'], {}), '(0.25, 0.25, 0.25)\n', (2991, 3009), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((8402, 8433), 'ConfigParser.SafeConfigParser', 'configparser.SafeConfigParser', ([], {}), '()\n', (8431, 8433), True, 'import ConfigParser as configparser\n'), ((12107, 12142), 'os.path.join', 'os.path.join', (['outdir', 'decimatedFile'], {}), '(outdir, decimatedFile)\n', (12119, 12142), False, 'import os\n'), ((12154, 12185), 'os.path.join', 'os.path.join', (['outdir', '"""tmp.vtk"""'], {}), "(outdir, 'tmp.vtk')\n", (12166, 12185), False, 'import os\n'), ((13576, 13680), 'eidolon.execBatchProgram', 'eidolon.execBatchProgram', (['decimpath', 'tmpfile', 'dpath', '"""-reduceby"""', 'sizepercent', '"""-ascii"""'], {'logcmd': '(True)'}), "(decimpath, tmpfile, dpath, '-reduceby',\n sizepercent, '-ascii', logcmd=True)\n", (13600, 13680), False, 'import eidolon\n'), ((13754, 13902), 'eidolon.execBatchProgram', 'eidolon.execBatchProgram', (['deformExe', '"""registration"""', '"""3D"""', 'modelFile', 'datasetFile', 'optimFile', '"""--output-dir=."""'], {'cwd': 'outdir', 'env': 'env', 'logcmd': '(True)'}), "(deformExe, 'registration', '3D', modelFile,\n datasetFile, optimFile, '--output-dir=.', cwd=outdir, env=env, logcmd=True)\n", (13778, 13902), False, 'import eidolon\n'), ((14367, 14402), 'os.path.join', 'os.path.join', (['outdir', 'decimatedFile'], {}), '(outdir, decimatedFile)\n', (14379, 14402), False, 'import os\n'), ((14417, 14453), 'os.path.join', 'os.path.join', (['outdir', 'registeredFile'], {}), '(outdir, registeredFile)\n', (14429, 14453), False, 'import os\n'), ((21333, 21373), 'eidolon.printFlush', 'eidolon.printFlush', (['"""Nodes:"""', 'start', 'end'], {}), "('Nodes:', start, end)\n", (21351, 21373), False, 'import eidolon\n'), ((21515, 21543), 'eidolon.first', 'first', (['graph.nodeelem[start]'], {}), '(graph.nodeelem[start])\n', (21520, 21543), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((21555, 21581), 'eidolon.first', 'first', (['graph.nodeelem[end]'], {}), '(graph.nodeelem[end])\n', (21560, 21581), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((28371, 28394), 'os.path.dirname', 'os.path.dirname', (['prefix'], {}), '(prefix)\n', (28386, 28394), False, 'import os\n'), ((28715, 28746), 'sfepy.base.conf.ProblemConf.from_file', 'ProblemConf.from_file', (['probfile'], {}), '(probfile)\n', (28736, 28746), False, 'from sfepy.base.conf import ProblemConf\n'), ((28751, 28789), 'sfepy.base.base.output.set_output', 'output.set_output', (['logfile', '(True)', '(True)'], {}), '(logfile, True, True)\n', (28768, 28789), False, 'from sfepy.base.base import output\n'), ((28792, 28804), 'sfepy.applications.solve_pde', 'solve_pde', (['p'], {}), '(p)\n', (28801, 28804), False, 'from sfepy.applications import solve_pde\n'), ((30819, 30852), 'numpy.asarray', 'np.asarray', (['regionfield', 'np.int32'], {}), '(regionfield, np.int32)\n', (30829, 30852), True, 'import numpy as np\n'), ((39575, 39606), 'eidolon.calculateElemExtAdj', 'eidolon.calculateElemExtAdj', (['ds'], {}), '(ds)\n', (39602, 39606), False, 'import eidolon\n'), ((47719, 47757), 'eidolon.taskmethod', 'taskmethod', (['"""Adding Object to Project"""'], {}), "('Adding Object to Project')\n", (47729, 47757), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((52180, 52220), 'eidolon.taskmethod', 'taskmethod', (['"""Starting to edit landmarks"""'], {}), "('Starting to edit landmarks')\n", (52190, 52220), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((58708, 58743), 'eidolon.taskmethod', 'taskmethod', (['"""Import endo/epi shell"""'], {}), "('Import endo/epi shell')\n", (58718, 58743), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((60004, 60039), 'eidolon.taskmethod', 'taskmethod', (['"""Registering landmarks"""'], {}), "('Registering landmarks')\n", (60014, 60039), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((60731, 60771), 'eidolon.taskmethod', 'taskmethod', (['"""Dividing mesh into regions"""'], {}), "('Dividing mesh into regions')\n", (60741, 60771), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((61112, 61141), 'eidolon.taskmethod', 'taskmethod', (['"""Generating mesh"""'], {}), "('Generating mesh')\n", (61122, 61141), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((564, 665), 'warnings.warn', 'warnings.warn', (['"""SfePy needs to be installed or in PYTHONPATH to generate fiber directions."""'], {}), "(\n 'SfePy needs to be installed or in PYTHONPATH to generate fiber directions.'\n )\n", (577, 665), False, 'import warnings\n'), ((3028, 3086), 'eidolon.ElemType.Tet1NL.applyCoeffs', 'ElemType.Tet1NL.applyCoeffs', (['[nodes[e] for e in elem]', 'mid'], {}), '([nodes[e] for e in elem], mid)\n', (3055, 3086), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((3142, 3195), 'eidolon.PyDataSet', 'PyDataSet', (['"""elemobjds"""', 'elemnodes', '[]', '[elemdirfield]'], {}), "('elemobjds', elemnodes, [], [elemdirfield])\n", (3151, 3195), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((3576, 3625), 'collections.defaultdict.__init__', 'defaultdict.__init__', (['self', 'None', '*args'], {}), '(self, None, *args, **kwargs)\n', (3596, 3625), False, 'from collections import defaultdict\n'), ((5258, 5273), 'eidolon.BoundBox', 'BoundBox', (['nodes'], {}), '(nodes)\n', (5266, 5273), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((12391, 12427), 'os.path.join', 'os.path.join', (['deformDir', 'datasetFile'], {}), '(deformDir, datasetFile)\n', (12403, 12427), False, 'import os\n'), ((12427, 12460), 'os.path.join', 'os.path.join', (['outdir', 'datasetFile'], {}), '(outdir, datasetFile)\n', (12439, 12460), False, 'import os\n'), ((13166, 13198), 'os.path.join', 'os.path.join', (['outdir', 'targetFile'], {}), '(outdir, targetFile)\n', (13178, 13198), False, 'import os\n'), ((15163, 15182), 'eidolon.transform', 'eidolon.transform', ([], {}), '()\n', (15180, 15182), False, 'import eidolon\n'), ((16853, 16877), 'eidolon.successive', 'successive', (['tri', '(2)', '(True)'], {}), '(tri, 2, True)\n', (16863, 16877), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((23070, 23116), 'eidolon.printFlush', 'eidolon.printFlush', (['"""---Resorting to easypath"""'], {}), "('---Resorting to easypath')\n", (23088, 23116), False, 'import eidolon\n'), ((24271, 24288), 'eidolon.first', 'first', (['bordertris'], {}), '(bordertris)\n', (24276, 24288), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((25295, 25324), 'eidolon.listSum', 'eidolon.listSum', (['graph.ragged'], {}), '(graph.ragged)\n', (25310, 25324), False, 'import eidolon\n'), ((32079, 32134), 'eidolon.printFlush', 'eidolon.printFlush', (['"""Region"""', 'r', 'lmstim[r]', 'lmground[r]'], {}), "('Region', r, lmstim[r], lmground[r])\n", (32097, 32134), False, 'import eidolon\n'), ((34914, 34943), 'eidolon.Ray', 'eidolon.Ray', (['start', 'direction'], {}), '(start, direction)\n', (34925, 34943), False, 'import eidolon\n'), ((41922, 41954), 'os.path.join', 'os.path.join', (['tempdir', '"""tetmesh"""'], {}), "(tempdir, 'tetmesh')\n", (41934, 41954), False, 'import os\n'), ((42697, 42728), 'eidolon.avg', 'avg', (['(gfield[i] for i in tets[e])'], {}), '(gfield[i] for i in tets[e])\n', (42700, 42728), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((44600, 44644), 'eidolon.Project.__init__', 'Project.__init__', (['self', 'name', 'parentdir', 'mgr'], {}), '(self, name, parentdir, mgr)\n', (44616, 44644), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((45125, 45145), 'eidolon.Project.create', 'Project.create', (['self'], {}), '(self)\n', (45139, 45145), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((45271, 45295), 'eidolon.Project.getPropBox', 'Project.getPropBox', (['self'], {}), '(self)\n', (45289, 45295), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((45363, 45399), 'eidolon.cppdel', 'eidolon.cppdel', (['prop.chooseLocLayout'], {}), '(prop.chooseLocLayout)\n', (45377, 45399), False, 'import eidolon\n'), ((45408, 45438), 'eidolon.cppdel', 'eidolon.cppdel', (['prop.dirButton'], {}), '(prop.dirButton)\n', (45422, 45438), False, 'import eidolon\n'), ((45447, 45482), 'eidolon.cppdel', 'eidolon.cppdel', (['prop.chooseLocLabel'], {}), '(prop.chooseLocLabel)\n', (45461, 45482), False, 'import eidolon\n'), ((46935, 46974), 'eidolon.Project.updatePropBox', 'Project.updatePropBox', (['self', 'proj', 'prop'], {}), '(self, proj, prop)\n', (46956, 46974), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((48909, 48923), 'os.mkdir', 'os.mkdir', (['path'], {}), '(path)\n', (48917, 48923), False, 'import os\n'), ((50058, 50083), 'eidolon.taskroutine', 'taskroutine', (['"""Add points"""'], {}), "('Add points')\n", (50069, 50083), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((52756, 52781), 'eidolon.color', 'eidolon.color', (['(1)', '(0)', '(0)', '(1)'], {}), '(1, 0, 0, 1)\n', (52769, 52781), False, 'import eidolon\n'), ((53496, 53522), 'eidolon.setmethod', 'eidolon.setmethod', (['noderep'], {}), '(noderep)\n', (53513, 53522), False, 'import eidolon\n'), ((54425, 54449), 'eidolon.taskroutine', 'taskroutine', (['"""Save mesh"""'], {}), "('Save mesh')\n", (54436, 54449), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((57201, 57242), 'eidolon.ScenePlugin.__init__', 'ScenePlugin.__init__', (['self', '"""AtrialFibre"""'], {}), "(self, 'AtrialFibre')\n", (57221, 57242), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((57312, 57352), 'eidolon.ScenePlugin.init', 'ScenePlugin.init', (['self', 'plugid', 'win', 'mgr'], {}), '(self, plugid, win, mgr)\n', (57328, 57352), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((57996, 58053), 'eidolon.addPathVariable', 'eidolon.addPathVariable', (['"""LD_LIBRARY_PATH"""', 'self.mirtkdir'], {}), "('LD_LIBRARY_PATH', self.mirtkdir)\n", (58019, 58053), False, 'import eidolon\n'), ((58075, 58112), 'os.path.join', 'os.path.join', (['self.mirtkdir', 'decimate'], {}), '(self.mirtkdir, decimate)\n', (58087, 58112), False, 'import os\n'), ((58991, 59001), 'eidolon.avg', 'avg', (['nodes'], {}), '(nodes)\n', (58994, 59001), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((59153, 59221), 'eidolon.listToMatrix', 'listToMatrix', (['[tris[i] for i in outerinds]', '"""tris"""', 'ElemType._Tri1NL'], {}), "([tris[i] for i in outerinds], 'tris', ElemType._Tri1NL)\n", (59165, 59221), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((59431, 59475), 'eidolon.reduceMesh', 'reduceMesh', (['nodes', '[outertris]'], {'marginSq': '(0.1)'}), '(nodes, [outertris], marginSq=0.1)\n', (59441, 59475), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((59493, 59537), 'eidolon.reduceMesh', 'reduceMesh', (['nodes', '[innertris]'], {'marginSq': '(0.1)'}), '(nodes, [innertris], marginSq=0.1)\n', (59503, 59537), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((60355, 60381), 'eidolon.printFlush', 'eidolon.printFlush', (['output'], {}), '(output)\n', (60373, 60381), False, 'import eidolon\n'), ((60567, 60669), 'eidolon.PyDataSet', 'eidolon.PyDataSet', (['"""pts"""', '[subjnodes[n[0]] for n in points]', "[('lines', ElemType._Line1NL, lines)]"], {}), "('pts', [subjnodes[n[0]] for n in points], [('lines',\n ElemType._Line1NL, lines)])\n", (60584, 60669), False, 'import eidolon\n'), ((60686, 60721), 'eidolon.MeshSceneObject', 'eidolon.MeshSceneObject', (['"""LM"""', 'ptds'], {}), "('LM', ptds)\n", (60709, 60721), False, 'import eidolon\n'), ((4778, 4806), 'eidolon.listToMatrix', 'listToMatrix', (['nodes', '"""nodes"""'], {}), "(nodes, 'nodes')\n", (4790, 4806), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((4874, 4900), 'eidolon.listToMatrix', 'listToMatrix', (['tris', '"""tris"""'], {}), "(tris, 'tris')\n", (4886, 4900), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((12756, 12787), 'os.path.join', 'os.path.join', (['outdir', 'modelFile'], {}), '(outdir, modelFile)\n', (12768, 12787), False, 'import os\n'), ((12977, 13008), 'os.path.join', 'os.path.join', (['outdir', 'optimFile'], {}), '(outdir, optimFile)\n', (12989, 13008), False, 'import os\n'), ((26907, 26994), 'eidolon.printFlush', 'eidolon.printFlush', (['"""Skipping"""', 'rindex', '[a for a in allnodes if a not in landmarks]'], {}), "('Skipping', rindex, [a for a in allnodes if a not in\n landmarks])\n", (26925, 26994), False, 'import eidolon\n'), ((35202, 35220), 'eidolon.vec3', 'vec3', (['*dirField[n]'], {}), '(*dirField[n])\n', (35206, 35220), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((41059, 41090), 'eidolon.avg', 'avg', (['(nodes[i] for i in faceinds)'], {}), '(nodes[i] for i in faceinds)\n', (41062, 41090), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((42773, 42784), 'eidolon.vec3', 'vec3', (['*dir1'], {}), '(*dir1)\n', (42777, 42784), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((42785, 42796), 'eidolon.vec3', 'vec3', (['*dir2'], {}), '(*dir2)\n', (42789, 42796), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((45161, 45187), 'os.path.isdir', 'os.path.isdir', (['self.logDir'], {}), '(self.logDir)\n', (45174, 45187), False, 'import os\n'), ((45201, 45222), 'os.mkdir', 'os.mkdir', (['self.logDir'], {}), '(self.logDir)\n', (45209, 45222), False, 'import os\n'), ((47421, 47473), 'eidolon.fillList', 'eidolon.fillList', (['combo', 'names', 'self.configMap[name]'], {}), '(combo, names, self.configMap[name])\n', (47437, 47473), False, 'import eidolon\n'), ((49242, 49267), 'eidolon.taskroutine', 'taskroutine', (['"""Add meshes"""'], {}), "('Add meshes')\n", (49253, 49267), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((50313, 50339), 'eidolon.Future.get', 'eidolon.Future.get', (['result'], {}), '(result)\n', (50331, 50339), False, 'import eidolon\n'), ((50436, 50473), 'os.path.join', 'os.path.join', (['tempdir', 'registeredFile'], {}), '(tempdir, registeredFile)\n', (50448, 50473), False, 'import os\n'), ((57706, 57730), 'os.path.isdir', 'os.path.isdir', (['deformDir'], {}), '(deformDir)\n', (57719, 57730), False, 'import os\n'), ((57746, 57781), 'zipfile.ZipFile', 'zipfile.ZipFile', (["(deformDir + '.zip')"], {}), "(deformDir + '.zip')\n", (57761, 57781), False, 'import zipfile\n'), ((57828, 57891), 'os.chmod', 'os.chmod', (['deformExe', '(stat.S_IRUSR | stat.S_IXUSR | stat.S_IWUSR)'], {}), '(deformExe, stat.S_IRUSR | stat.S_IXUSR | stat.S_IWUSR)\n', (57836, 57891), False, 'import os\n'), ((57935, 57954), 'eidolon.getAppDir', 'eidolon.getAppDir', ([], {}), '()\n', (57952, 57954), False, 'import eidolon\n'), ((59845, 59888), 'eidolon.PyDataSet', 'PyDataSet', (['"""ds"""', 'outermesh[0]', 'outermesh[1]'], {}), "('ds', outermesh[0], outermesh[1])\n", (59854, 59888), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((59927, 59970), 'eidolon.PyDataSet', 'PyDataSet', (['"""ds"""', 'innermesh[0]', 'innermesh[1]'], {}), "('ds', innermesh[0], innermesh[1])\n", (59936, 59970), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((4958, 4964), 'eidolon.vec3', 'vec3', ([], {}), '()\n', (4962, 4964), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((12508, 12542), 'os.path.join', 'os.path.join', (['deformDir', 'modelFile'], {}), '(deformDir, modelFile)\n', (12520, 12542), False, 'import os\n'), ((12872, 12906), 'os.path.join', 'os.path.join', (['deformDir', 'optimFile'], {}), '(deformDir, optimFile)\n', (12884, 12906), False, 'import os\n'), ((30112, 30132), 'numpy.asarray', 'np.asarray', (['edgedirs'], {}), '(edgedirs)\n', (30122, 30132), True, 'import numpy as np\n'), ((30133, 30154), 'numpy.asarray', 'np.asarray', (['edgegrads'], {}), '(edgegrads)\n', (30143, 30154), True, 'import numpy as np\n'), ((30337, 30343), 'eidolon.vec3', 'vec3', ([], {}), '()\n', (30341, 30343), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((33694, 33733), 'os.path.join', 'os.path.join', (['tempdir', "('region%.2i' % r)"], {}), "(tempdir, 'region%.2i' % r)\n", (33706, 33733), False, 'import os\n'), ((34195, 34216), 'eidolon.printFlush', 'eidolon.printFlush', (['e'], {}), '(e)\n', (34213, 34216), False, 'import eidolon\n'), ((47379, 47391), 'eidolon.first', 'first', (['names'], {}), '(names)\n', (47384, 47391), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((34107, 34134), 'eidolon.vec3', 'vec3', (['*directionfield[oldn]'], {}), '(*directionfield[oldn])\n', (34111, 34134), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((40677, 40683), 'eidolon.vec3', 'vec3', ([], {}), '()\n', (40681, 40683), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((30269, 30286), 'eidolon.vec3', 'vec3', (['*nodedir[0]'], {}), '(*nodedir[0])\n', (30273, 30286), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((33295, 33309), 'eidolon.avg', 'avg', (['(a, b, c)'], {}), '((a, b, c))\n', (33298, 33309), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((40596, 40610), 'eidolon.vec3', 'vec3', (['*dirs[i]'], {}), '(*dirs[i])\n', (40600, 40610), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((48851, 48874), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (48872, 48874), False, 'import datetime\n'), ((56282, 56301), 'eidolon.taskroutine', 'taskroutine', (['"""Save"""'], {}), "('Save')\n", (56293, 56301), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n'), ((56427, 56450), 'eidolon.taskroutine', 'taskroutine', (['"""Load Rep"""'], {}), "('Load Rep')\n", (56438, 56450), False, 'from eidolon import ui, ScenePlugin, Project, avg, vec3, successive, first, RealMatrix, IndexMatrix, StdProps, timing, ReprType, listToMatrix, MeshSceneObject, BoundBox, ElemType, reduceMesh, PyDataSet, taskmethod, taskroutine, printFlush\n')] |
# mixed formulation
# 07.08.2009
#!
#! Homogenization: Linear Elasticity
#! =================================
#$ \centerline{Example input file, \today}
#! Homogenization of heterogeneous linear elastic material - mixed formulation
import numpy as nm
import sfepy.discrete.fem.periodic as per
from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson_mixed, bulk_from_youngpoisson
from sfepy.homogenization.utils import define_box_regions, get_box_volume
import sfepy.homogenization.coefs_base as cb
from sfepy import data_dir
from sfepy.base.base import Struct
from sfepy.homogenization.recovery import compute_micro_u, compute_stress_strain_u, compute_mac_stress_part, add_stress_p
def recovery_le( pb, corrs, macro ):
out = {}
dim = corrs['corrs_le']['u_00'].shape[1]
mic_u = - compute_micro_u( corrs['corrs_le'], macro['strain'], 'u', dim )
mic_p = - compute_micro_u( corrs['corrs_le'], macro['strain'], 'p', dim )
out['u_mic'] = Struct( name = 'output_data',
mode = 'vertex', data = mic_u,
var_name = 'u', dofs = None )
out['p_mic'] = Struct( name = 'output_data',
mode = 'cell', data = mic_p[:,nm.newaxis,
:,nm.newaxis],
var_name = 'p', dofs = None )
stress_Y, strain_Y = compute_stress_strain_u( pb, 'i', 'Y', 'mat.D', 'u', mic_u )
stress_Y += compute_mac_stress_part( pb, 'i', 'Y', 'mat.D', 'u', macro['strain'] )
add_stress_p( stress_Y, pb, 'i', 'Y', 'p', mic_p )
strain = macro['strain'] + strain_Y
out['cauchy_strain'] = Struct( name = 'output_data',
mode = 'cell', data = strain,
dofs = None )
out['cauchy_stress'] = Struct( name = 'output_data',
mode = 'cell', data = stress_Y,
dofs = None )
return out
#! Mesh
#! ----
dim = 3
filename_mesh = data_dir + '/meshes/3d/matrix_fiber.mesh'
region_lbn = (0, 0, 0)
region_rtf = (1, 1, 1)
#! Regions
#! -------
#! Regions, edges, ...
regions = {
'Y' : 'all',
'Ym' : 'cells of group 1',
'Yc' : 'cells of group 2',
}
regions.update( define_box_regions( dim, region_lbn, region_rtf ) )
#! Materials
#! ---------
materials = {
'mat' : ({'D' : {'Ym': stiffness_from_youngpoisson_mixed(dim, 7.0e9, 0.4),
'Yc': stiffness_from_youngpoisson_mixed(dim, 70.0e9, 0.2)},
'gamma': {'Ym': 1.0/bulk_from_youngpoisson(7.0e9, 0.4),
'Yc': 1.0/bulk_from_youngpoisson(70.0e9, 0.2)}},),
}
#! Fields
#! ------
#! Scalar field for corrector basis functions.
fields = {
'corrector_u' : ('real', dim, 'Y', 1),
'corrector_p' : ('real', 1, 'Y', 0),
}
#! Variables
#! ---------
#! Unknown and corresponding test variables. Parameter fields
#! used for evaluation of homogenized coefficients.
variables = {
'u' : ('unknown field', 'corrector_u'),
'v' : ('test field', 'corrector_u', 'u'),
'p' : ('unknown field', 'corrector_p'),
'q' : ('test field', 'corrector_p', 'p'),
'Pi' : ('parameter field', 'corrector_u', 'u'),
'Pi1u' : ('parameter field', 'corrector_u', '(set-to-None)'),
'Pi2u' : ('parameter field', 'corrector_u', '(set-to-None)'),
'Pi1p' : ('parameter field', 'corrector_p', '(set-to-None)'),
'Pi2p' : ('parameter field', 'corrector_p', '(set-to-None)'),
}
#! Functions
functions = {
'match_x_plane' : (per.match_x_plane,),
'match_y_plane' : (per.match_y_plane,),
'match_z_plane' : (per.match_z_plane,),
}
#! Boundary Conditions
#! -------------------
#! Fixed nodes.
ebcs = {
'fixed_u' : ('Corners', {'u.all' : 0.0}),
}
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_x_plane'),
'periodic_y' : (['Bottom', 'Top'], {'u.all' : 'u.all'}, 'match_y_plane'),
}
all_periodic = ['periodic_%s' % ii for ii in ['x', 'y', 'z'][:dim] ]
#! Integrals
#! ---------
#! Define the integral type Volume/Surface and quadrature rule.
integrals = {
'i' : 2,
}
#! Options
#! -------
#! Various problem-specific options.
options = {
'coefs' : 'coefs',
'requirements' : 'requirements',
'ls' : 'ls', # linear solver to use
'volume' : { #'variables' : ['u'],
#'expression' : 'd_volume.i.Y( u )',
'value' : get_box_volume( dim, region_lbn, region_rtf ),
},
'output_dir' : 'output',
'coefs_filename' : 'coefs_le_up',
'recovery_hook' : 'recovery_le',
}
#! Equations
#! ---------
#! Equations for corrector functions.
equation_corrs = {
'balance_of_forces' :
""" dw_lin_elastic.i.Y( mat.D, v, u )
- dw_stokes.i.Y( v, p ) =
- dw_lin_elastic.i.Y( mat.D, v, Pi )""",
'pressure constraint' :
"""- dw_stokes.i.Y( u, q )
- dw_volume_dot.i.Y( mat.gamma, q, p ) =
+ dw_stokes.i.Y( Pi, q )""",
}
#! Expressions for homogenized linear elastic coefficients.
expr_coefs = {
'Q1' : """dw_lin_elastic.i.Y( mat.D, Pi1u, Pi2u )""",
'Q2' : """dw_volume_dot.i.Y( mat.gamma, Pi1p, Pi2p )""",
}
#! Coefficients
#! ------------
#! Definition of homogenized acoustic coefficients.
def set_elastic_u(variables, ir, ic, mode, pis, corrs_rs):
mode2var = {'row' : 'Pi1u', 'col' : 'Pi2u'}
val = pis.states[ir, ic]['u'] + corrs_rs.states[ir, ic]['u']
variables[mode2var[mode]].set_data(val)
coefs = {
'elastic_u' : {
'requires' : ['pis', 'corrs_rs'],
'expression' : expr_coefs['Q1'],
'set_variables' : set_elastic_u,
'class' : cb.CoefSymSym,
},
'elastic_p' : {
'requires' : ['corrs_rs'],
'expression' : expr_coefs['Q2'],
'set_variables' : [('Pi1p', 'corrs_rs', 'p'), ('Pi2p', 'corrs_rs', 'p')],
'class' : cb.CoefSymSym,
},
'D' : {
'requires' : ['c.elastic_u', 'c.elastic_p'],
'class' : cb.CoefSum,
},
'filenames' : {},
}
requirements = {
'pis' : {
'variables' : ['u'],
'class' : cb.ShapeDimDim,
},
'corrs_rs' : {
'requires' : ['pis'],
'ebcs' : ['fixed_u'],
'epbcs' : all_periodic,
'equations' : equation_corrs,
'set_variables' : [('Pi', 'pis', 'u')],
'class' : cb.CorrDimDim,
'save_name' : 'corrs_le',
'dump_variables' : ['u', 'p'],
'is_linear' : True,
},
}
#! Solvers
#! -------
#! Define linear and nonlinear solver.
solvers = {
'ls' : ('ls.scipy_direct', {}),
'newton' : ('nls.newton', {
'i_max' : 1,
'eps_a' : 1e-4,
})
}
| [
"sfepy.homogenization.utils.get_box_volume",
"sfepy.mechanics.matcoefs.stiffness_from_youngpoisson_mixed",
"sfepy.homogenization.recovery.compute_stress_strain_u",
"sfepy.mechanics.matcoefs.bulk_from_youngpoisson",
"sfepy.homogenization.utils.define_box_regions",
"sfepy.base.base.Struct",
"sfepy.homogen... | [((968, 1046), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""vertex"""', 'data': 'mic_u', 'var_name': '"""u"""', 'dofs': 'None'}), "(name='output_data', mode='vertex', data=mic_u, var_name='u', dofs=None)\n", (974, 1046), False, 'from sfepy.base.base import Struct\n'), ((1132, 1243), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'mic_p[:, nm.newaxis, :, nm.newaxis]', 'var_name': '"""p"""', 'dofs': 'None'}), "(name='output_data', mode='cell', data=mic_p[:, nm.newaxis, :, nm.\n newaxis], var_name='p', dofs=None)\n", (1138, 1243), False, 'from sfepy.base.base import Struct\n'), ((1384, 1442), 'sfepy.homogenization.recovery.compute_stress_strain_u', 'compute_stress_strain_u', (['pb', '"""i"""', '"""Y"""', '"""mat.D"""', '"""u"""', 'mic_u'], {}), "(pb, 'i', 'Y', 'mat.D', 'u', mic_u)\n", (1407, 1442), False, 'from sfepy.homogenization.recovery import compute_micro_u, compute_stress_strain_u, compute_mac_stress_part, add_stress_p\n'), ((1461, 1529), 'sfepy.homogenization.recovery.compute_mac_stress_part', 'compute_mac_stress_part', (['pb', '"""i"""', '"""Y"""', '"""mat.D"""', '"""u"""', "macro['strain']"], {}), "(pb, 'i', 'Y', 'mat.D', 'u', macro['strain'])\n", (1484, 1529), False, 'from sfepy.homogenization.recovery import compute_micro_u, compute_stress_strain_u, compute_mac_stress_part, add_stress_p\n'), ((1536, 1584), 'sfepy.homogenization.recovery.add_stress_p', 'add_stress_p', (['stress_Y', 'pb', '"""i"""', '"""Y"""', '"""p"""', 'mic_p'], {}), "(stress_Y, pb, 'i', 'Y', 'p', mic_p)\n", (1548, 1584), False, 'from sfepy.homogenization.recovery import compute_micro_u, compute_stress_strain_u, compute_mac_stress_part, add_stress_p\n'), ((1656, 1719), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'strain', 'dofs': 'None'}), "(name='output_data', mode='cell', data=strain, dofs=None)\n", (1662, 1719), False, 'from sfepy.base.base import Struct\n'), ((1827, 1892), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""cell"""', 'data': 'stress_Y', 'dofs': 'None'}), "(name='output_data', mode='cell', data=stress_Y, dofs=None)\n", (1833, 1892), False, 'from sfepy.base.base import Struct\n'), ((2271, 2318), 'sfepy.homogenization.utils.define_box_regions', 'define_box_regions', (['dim', 'region_lbn', 'region_rtf'], {}), '(dim, region_lbn, region_rtf)\n', (2289, 2318), False, 'from sfepy.homogenization.utils import define_box_regions, get_box_volume\n'), ((806, 867), 'sfepy.homogenization.recovery.compute_micro_u', 'compute_micro_u', (["corrs['corrs_le']", "macro['strain']", '"""u"""', 'dim'], {}), "(corrs['corrs_le'], macro['strain'], 'u', dim)\n", (821, 867), False, 'from sfepy.homogenization.recovery import compute_micro_u, compute_stress_strain_u, compute_mac_stress_part, add_stress_p\n'), ((884, 945), 'sfepy.homogenization.recovery.compute_micro_u', 'compute_micro_u', (["corrs['corrs_le']", "macro['strain']", '"""p"""', 'dim'], {}), "(corrs['corrs_le'], macro['strain'], 'p', dim)\n", (899, 945), False, 'from sfepy.homogenization.recovery import compute_micro_u, compute_stress_strain_u, compute_mac_stress_part, add_stress_p\n'), ((4731, 4774), 'sfepy.homogenization.utils.get_box_volume', 'get_box_volume', (['dim', 'region_lbn', 'region_rtf'], {}), '(dim, region_lbn, region_rtf)\n', (4745, 4774), False, 'from sfepy.homogenization.utils import define_box_regions, get_box_volume\n'), ((2390, 2447), 'sfepy.mechanics.matcoefs.stiffness_from_youngpoisson_mixed', 'stiffness_from_youngpoisson_mixed', (['dim', '(7000000000.0)', '(0.4)'], {}), '(dim, 7000000000.0, 0.4)\n', (2423, 2447), False, 'from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson_mixed, bulk_from_youngpoisson\n'), ((2469, 2527), 'sfepy.mechanics.matcoefs.stiffness_from_youngpoisson_mixed', 'stiffness_from_youngpoisson_mixed', (['dim', '(70000000000.0)', '(0.2)'], {}), '(dim, 70000000000.0, 0.2)\n', (2502, 2527), False, 'from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson_mixed, bulk_from_youngpoisson\n'), ((2557, 2598), 'sfepy.mechanics.matcoefs.bulk_from_youngpoisson', 'bulk_from_youngpoisson', (['(7000000000.0)', '(0.4)'], {}), '(7000000000.0, 0.4)\n', (2579, 2598), False, 'from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson_mixed, bulk_from_youngpoisson\n'), ((2627, 2669), 'sfepy.mechanics.matcoefs.bulk_from_youngpoisson', 'bulk_from_youngpoisson', (['(70000000000.0)', '(0.2)'], {}), '(70000000000.0, 0.2)\n', (2649, 2669), False, 'from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson_mixed, bulk_from_youngpoisson\n')] |
# This example implements homogenization of piezoeletric porous media.
# The mathematical model and numerical results are described in:
#
# <NAME>., <NAME>.
# Homogenization of the fluid-saturated piezoelectric porous media.
# International Journal of Solids and Structures
# Volume 147, 15 August 2018, Pages 110-125
# https://doi.org/10.1016/j.ijsolstr.2018.05.017
#
# Run calculation of homogeized coefficients:
#
# ./homogen.py example_poropiezo-1/poropiezo_micro_dfc.py
#
# The results are stored in `example_poropiezo-1/results` directory.
#
import sys
import numpy as nm
import os.path as osp
from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson
from sfepy.homogenization.utils import coor_to_sym, define_box_regions
import sfepy.discrete.fem.periodic as per
from sfepy.discrete.fem.mesh import Mesh
import sfepy.homogenization.coefs_base as cb
from sfepy.base.base import Struct
data_dir = 'example_poropiezo-1'
def data_to_struct(data):
out = {}
for k, v in data.items():
out[k] = Struct(name='output_data',
mode='cell' if v[2] == 'c' else 'vertex',
data=v[0],
var_name=v[1],
dofs=None)
return out
def get_periodic_bc(var_tab, dim=3, dim_tab=None):
if dim_tab is None:
dim_tab = {'x': ['left', 'right'],
'z': ['bottom', 'top'],
'y': ['near', 'far']}
periodic = {}
epbcs = {}
for ivar, reg in var_tab:
periodic['per_%s' % ivar] = pers = []
for idim in 'xyz'[0:dim]:
key = 'per_%s_%s' % (ivar, idim)
regs = ['%s_%s' % (reg, ii) for ii in dim_tab[idim]]
epbcs[key] = (regs, {'%s.all' % ivar: '%s.all' % ivar},
'match_%s_plane' % idim)
pers.append(key)
return epbcs, periodic
# reconstruct displacement, and electric fields at the microscopic level,
# see Section 6.2
def recovery_micro_dfc(pb, corrs, macro):
eps0 = macro['eps0']
mesh = pb.domain.mesh
regions = pb.domain.regions
dim = mesh.dim
Yms_map = regions['Yms'].get_entities(0)
Ym_map = regions['Ym'].get_entities(0)
gl = '_' + list(corrs.keys())[0].split('_')[-1]
u1 = -corrs['corrs_p' + gl]['u'] * macro['press'][Yms_map, :]
phi = -corrs['corrs_p' + gl]['r'] * macro['press'][Ym_map, :]
for ii in range(2):
u1 += corrs['corrs_k%d' % ii + gl]['u'] * macro['phi'][ii]
phi += corrs['corrs_k%d' % ii + gl]['r'] * macro['phi'][ii]
for ii in range(dim):
for jj in range(dim):
kk = coor_to_sym(ii, jj, dim)
phi += corrs['corrs_rs' + gl]['r_%d%d' % (ii, jj)]\
* nm.expand_dims(macro['strain'][Ym_map, kk], axis=1)
u1 += corrs['corrs_rs' + gl]['u_%d%d' % (ii, jj)]\
* nm.expand_dims(macro['strain'][Yms_map, kk], axis=1)
u = macro['u'][Yms_map, :] + eps0 * u1
mvar = pb.create_variables(['u', 'r', 'svar'])
e_mac_Yms = [None] * macro['strain'].shape[1]
for ii in range(dim):
for jj in range(dim):
kk = coor_to_sym(ii, jj, dim)
mvar['svar'].set_data(macro['strain'][:, kk])
mac_e_Yms = pb.evaluate('ev_volume_integrate.i2.Yms(svar)',
mode='el_avg',
var_dict={'svar': mvar['svar']})
e_mac_Yms[kk] = mac_e_Yms.squeeze()
e_mac_Yms = nm.vstack(e_mac_Yms).T[:, nm.newaxis, :, nm.newaxis]
mvar['r'].set_data(phi)
E_mic = pb.evaluate('ev_grad.i2.Ym(r)',
mode='el_avg',
var_dict={'r': mvar['r']}) / eps0
mvar['u'].set_data(u1)
e_mic = pb.evaluate('ev_cauchy_strain.i2.Yms(u)',
mode='el_avg',
var_dict={'u': mvar['u']})
e_mic += e_mac_Yms
out = {
'u0': (macro['u'][Yms_map, :], 'u', 'p'), # macro displacement
'u1': (u1, 'u', 'p'), # local displacement corrections, see eq. (58)
'u': (u, 'u', 'p'), # total displacement
'e_mic': (e_mic, 'u', 'c'), # micro strain field, see eq. (58)
'phi': (phi, 'r', 'p'), # electric potential, see eq. (57)
'E_mic': (E_mic, 'r', 'c'), # electric field, see eq. (58)
}
return data_to_struct(out)
# define homogenized coefficients and subproblems for correctors
def define(grid0=100, filename_mesh=None):
eps0 = 0.01 / grid0
if filename_mesh is None:
filename_mesh = osp.join(data_dir, 'piezo_mesh_micro_dfc.vtk')
mesh = Mesh.from_file(filename_mesh)
n_conduct = len(nm.unique(mesh.cmesh.cell_groups)) - 2
sym_eye = 'nm.array([1,1,0])' if mesh.dim == 2 else\
'nm.array([1,1,1,0,0,0])'
bbox = mesh.get_bounding_box()
regions = define_box_regions(mesh.dim, bbox[0], bbox[1], eps=1e-3)
regions.update({
'Y': 'all',
# matrix
'Ym': 'cells of group 1',
'Ym_left': ('r.Ym *v r.Left', 'vertex'),
'Ym_right': ('r.Ym *v r.Right', 'vertex'),
'Ym_bottom': ('r.Ym *v r.Bottom', 'vertex'),
'Ym_top': ('r.Ym *v r.Top', 'vertex'),
'Ym_far': ('r.Ym *v r.Far', 'vertex'),
'Ym_near': ('r.Ym *v r.Near', 'vertex'),
'Gamma_mc': ('r.Ym *v r.Yc', 'facet', 'Ym'),
# channel / inclusion
'Yc': 'cells of group 2',
'Yc0': ('r.Yc -v r.Gamma_cm', 'vertex'),
'Gamma_cm': ('r.Ym *v r.Yc', 'facet', 'Yc'),
})
print('number of cnonductors: %d' % n_conduct)
regions.update({
'Yms': ('r.Ym +v r.Ys', 'cell'),
'Yms_left': ('r.Yms *v r.Left', 'vertex'),
'Yms_right': ('r.Yms *v r.Right', 'vertex'),
'Yms_bottom': ('r.Yms *v r.Bottom', 'vertex'),
'Yms_top': ('r.Yms *v r.Top', 'vertex'),
'Yms_far': ('r.Yms *v r.Far', 'vertex'),
'Yms_near': ('r.Yms *v r.Near', 'vertex'),
'Gamma_ms': ('r.Ym *v r.Ys', 'facet', 'Ym'),
'Gamma_msc': ('r.Yms *v r.Yc', 'facet', 'Yms'),
'Ys': (' +v '.join(['r.Ys%d' % k for k in range(n_conduct)]),
'cell'),
})
options = {
'coefs_filename': 'coefs_poropiezo_%d' % (grid0),
'volume': {
'variables': ['svar'],
'expression': 'd_volume.i2.Y(svar)',
},
'coefs': 'coefs',
'requirements': 'requirements',
'output_dir': osp.join(data_dir, 'results'),
'ls': 'ls',
'file_per_var': True,
'absolute_mesh_path': True,
'multiprocessing': False,
'recovery_hook': recovery_micro_dfc,
}
fields = {
'displacement': ('real', 'vector', 'Yms', 1),
'potential': ('real', 'scalar', 'Ym', 1),
'sfield': ('real', 'scalar', 'Y', 1),
}
variables = {
# displacement
'u': ('unknown field', 'displacement'),
'v': ('test field', 'displacement', 'u'),
'Pi_u': ('parameter field', 'displacement', 'u'),
'U1': ('parameter field', 'displacement', '(set-to-None)'),
'U2': ('parameter field', 'displacement', '(set-to-None)'),
# potential
'r': ('unknown field', 'potential'),
's': ('test field', 'potential', 'r'),
'Pi_r': ('parameter field', 'potential', 'r'),
'R1': ('parameter field', 'potential', '(set-to-None)'),
'R2': ('parameter field', 'potential', '(set-to-None)'),
# aux variable
'svar': ('parameter field', 'sfield', '(set-to-None)'),
}
epbcs, periodic = get_periodic_bc([('u', 'Yms'), ('r', 'Ym')])
mat_g_sc, mat_d_sc = eps0, eps0**2
# BaTiO3 - Miara, Rohan, ... doi: 10.1016/j.jmps.2005.05.006
materials = {
'matrix': ({
'D': {'Ym': nm.array([[1.504, 0.656, 0.659, 0, 0, 0],
[0.656, 1.504, 0.659, 0, 0, 0],
[0.659, 0.659, 1.455, 0, 0, 0],
[0, 0, 0, 0.424, 0, 0],
[0, 0, 0, 0, 0.439, 0],
[0, 0, 0, 0, 0, 0.439]]) * 1e11, }
},),
'piezo': ({
'g': nm.array([[0, 0, 0, 0, 11.404, 0],
[0, 0, 0, 0, 0, 11.404],
[-4.322, -4.322, 17.360, 0, 0, 0]]) / mat_g_sc,
'd': nm.array([[1.284, 0, 0],
[0, 1.284, 0],
[0, 0, 1.505]]) * 1e-8 / mat_d_sc,
},),
'fluid': ({'gamma': 1.0 / 2.15e9},),
}
functions = {
'match_x_plane': (per.match_x_plane,),
'match_y_plane': (per.match_y_plane,),
'match_z_plane': (per.match_z_plane,),
}
ebcs = {
'fixed_u': ('Corners', {'u.all': 0.0}),
'fixed_r': ('Gamma_ms', {'r.all': 0.0}),
}
integrals = {
'i2': 2,
'i5': 5,
}
solvers = {
'ls': ('ls.scipy_direct', {}),
'ns_em6': ('nls.newton', {
'i_max': 1,
'eps_a': 1e-6,
'eps_r': 1e-6,
'problem': 'nonlinear'}),
'ns_em3': ('nls.newton', {
'i_max': 1,
'eps_a': 1e-3,
'eps_r': 1e-6,
'problem': 'nonlinear'}),
}
coefs = {
# homogenized elasticity, see eq. (46)_1
'A': {
'requires': ['c.A1', 'c.A2'],
'expression': 'c.A1 + c.A2',
'class': cb.CoefEval,
},
'A1': {
'status': 'auxiliary',
'requires': ['pis_u', 'corrs_rs'],
'expression': 'dw_lin_elastic.i2.Yms(matrix.D, U1, U2)',
'set_variables': [('U1', ('corrs_rs', 'pis_u'), 'u'),
('U2', ('corrs_rs', 'pis_u'), 'u')],
'class': cb.CoefSymSym,
},
'A2': {
'status': 'auxiliary',
'requires': ['corrs_rs'],
'expression': 'dw_diffusion.i2.Ym(piezo.d, R1, R2)',
'set_variables': [('R1', 'corrs_rs', 'r'),
('R2', 'corrs_rs', 'r')],
'class': cb.CoefSymSym,
},
# homogenized Biot coefficient, see eq. (46)_2
'B': {
'requires': ['c.Phi', 'c.B1', 'c.B2'],
'expression': 'c.B1 - c.B2 + c.Phi * %s' % sym_eye,
'class': cb.CoefEval,
},
'B1': {
'status': 'auxiliary',
'requires': ['pis_u', 'corrs_p'],
'expression': 'dw_lin_elastic.i2.Yms(matrix.D, U1, U2)',
'set_variables': [('U1', 'corrs_p', 'u'),
('U2', 'pis_u', 'u')],
'class': cb.CoefSym,
},
'B2': {
'status': 'auxiliary',
'requires': ['pis_u', 'corrs_p'],
'expression': 'dw_piezo_coupling.i2.Ym(piezo.g, U1, R1)',
'set_variables': [('R1', 'corrs_p', 'r'),
('U1', 'pis_u', 'u')],
'class': cb.CoefSym,
},
# homogenized compressibility coefficient, see eq. (46)_6
'M': {
'requires': ['c.Phi', 'c.N'],
'expression': 'c.N + c.Phi * %e' % materials['fluid'][0]['gamma'],
'class': cb.CoefEval,
},
'N': {
'status': 'auxiliary',
'requires': ['corrs_p'],
'expression': 'dw_surface_ltr.i2.Gamma_msc(U1)',
'set_variables': [('U1', 'corrs_p', 'u')],
'class': cb.CoefOne,
},
'Phi': {
'requires': ['c.vol'],
'expression': 'c.vol["fraction_Yc"]',
'class': cb.CoefEval,
},
# volume fractions of Ym, Yc, Ys1, Ys2, ...
'vol': {
'regions': ['Ym', 'Yc'] + ['Ys%d' % k for k in range(n_conduct)],
'expression': 'd_volume.i2.%s(svar)',
'class': cb.VolumeFractions,
},
'eps0': {
'requires': [],
'expression': '%e' % eps0,
'class': cb.CoefEval,
},
'filenames': {},
}
requirements = {
'pis_u': {
'variables': ['u'],
'class': cb.ShapeDimDim,
},
'pis_r': {
'variables': ['r'],
'class': cb.ShapeDim,
},
# local subproblem defined by eq. (41)
'corrs_rs': {
'requires': ['pis_u'],
'ebcs': ['fixed_u', 'fixed_r'],
'epbcs': periodic['per_u'] + periodic['per_r'],
'is_linear': True,
'equations': {
'eq1':
"""dw_lin_elastic.i2.Yms(matrix.D, v, u)
- dw_piezo_coupling.i2.Ym(piezo.g, v, r)
= - dw_lin_elastic.i2.Yms(matrix.D, v, Pi_u)""",
'eq2':
"""
- dw_piezo_coupling.i2.Ym(piezo.g, u, s)
- dw_diffusion.i2.Ym(piezo.d, s, r)
= dw_piezo_coupling.i2.Ym(piezo.g, Pi_u, s)""",
},
'set_variables': [('Pi_u', 'pis_u', 'u')],
'class': cb.CorrDimDim,
'save_name': 'corrs_rs_%d' % grid0,
'dump_variables': ['u', 'r'],
'solvers': {'ls': 'ls', 'nls': 'ns_em3'},
},
# local subproblem defined by eq. (42)
'corrs_p': {
'requires': [],
'ebcs': ['fixed_u', 'fixed_r'],
'epbcs': periodic['per_u'] + periodic['per_r'],
'is_linear': True,
'equations': {
'eq1':
"""dw_lin_elastic.i2.Yms(matrix.D, v, u)
- dw_piezo_coupling.i2.Ym(piezo.g, v, r)
= dw_surface_ltr.i2.Gamma_msc(v)""",
'eq2':
"""
- dw_piezo_coupling.i2.Ym(piezo.g, u, s)
- dw_diffusion.i2.Ym(piezo.d, s, r)
= 0"""
},
'class': cb.CorrOne,
'save_name': 'corrs_p_%d' % grid0,
'dump_variables': ['u', 'r'],
'solvers': {'ls': 'ls', 'nls': 'ns_em6'},
},
# local subproblem defined by eq. (43)
'corrs_rho': {
'requires': [],
'ebcs': ['fixed_u', 'fixed_r'],
'epbcs': periodic['per_u'] + periodic['per_r'],
'is_linear': True,
'equations': {
'eq1':
"""dw_lin_elastic.i2.Yms(matrix.D, v, u)
- dw_piezo_coupling.i2.Ym(piezo.g, v, r)
= 0""",
'eq2':
"""
- dw_piezo_coupling.i2.Ym(piezo.g, u, s)
- dw_diffusion.i2.Ym(piezo.d, s, r)
=
- dw_surface_integrate.i2.Gamma_mc(s)"""
},
'class': cb.CorrOne,
'save_name': 'corrs_p_%d' % grid0,
'dump_variables': ['u', 'r'],
'solvers': {'ls': 'ls', 'nls': 'ns_em6'},
},
}
for k in range(n_conduct):
sk = '%d' % k
regions.update({
'Ys' + sk: 'cells of group %d' % (3 + k),
'Gamma_s' + sk: ('r.Ym *v r.Ys' + sk, 'facet', 'Ym'),
})
materials['matrix'][0]['D'].update({
'Ys' + sk: stiffness_from_youngpoisson(3, 200e9, 0.25),
})
ebcs.update({
'fixed_r1_k_' + sk: ('Gamma_s' + sk, {'r.0': 1.0}),
'fixed_r0_k_' + sk: ('Gamma_s' + sk, {'r.0': 0.0}),
})
fixed_r0_k = ['fixed_r0_k_%d' % ii for ii in range(n_conduct)
if not ii == k]
# local subproblems defined for conductors, see eq. (44)
requirements.update({
'corrs_k' + sk: {
'requires': ['pis_r'],
'ebcs': ['fixed_u', 'fixed_r1_k_' + sk] + fixed_r0_k,
'epbcs': periodic['per_u'] + periodic['per_r'],
'is_linear': True,
'equations': {
'eq1':
"""dw_lin_elastic.i2.Yms(matrix.D, v, u)
- dw_piezo_coupling.i2.Ym(piezo.g, v, r)
= 0""",
'eq2':
"""
- dw_piezo_coupling.i2.Ym(piezo.g, u, s)
- dw_diffusion.i2.Ym(piezo.d, s, r)
= 0"""
},
'class': cb.CorrOne,
'save_name': 'corrs_k' + sk + '_%d' % grid0,
'dump_variables': ['u', 'r'],
'solvers': {'ls': 'ls', 'nls': 'ns_em6'},
},
})
coefs.update({
# homogenized coefficient (46)_3
'H' + sk: {
'requires': ['c.H1_' + sk, 'c.H2_' + sk],
'expression': 'c.H1_%s - c.H2_%s' % (sk, sk),
'class': cb.CoefEval,
},
'H1_' + sk: {
'status': 'auxiliary',
'requires': ['pis_u', 'corrs_k' + sk],
'expression': 'dw_lin_elastic.i2.Yms(matrix.D, U1, U2)',
'set_variables': [('U1', 'corrs_k' + sk, 'u'),
('U2', 'pis_u', 'u')],
'class': cb.CoefSym,
},
'H2_' + sk: {
'status': 'auxiliary',
'requires': ['pis_u', 'corrs_k' + sk],
'expression': 'dw_piezo_coupling.i2.Ym(piezo.g, U1, R1)',
'set_variables': [('R1', 'corrs_k' + sk, 'r'),
('U1', 'pis_u', 'u')],
'class': cb.CoefSym,
},
# homogenized coefficient (46)_7
'Z' + sk: {
'requires': ['corrs_k' + sk],
'expression': 'dw_surface_ltr.i2.Gamma_msc(U1)',
'set_variables': [('U1', 'corrs_k' + sk, 'u')],
'class': cb.CoefOne,
},
})
return locals()
| [
"sfepy.mechanics.matcoefs.stiffness_from_youngpoisson",
"sfepy.homogenization.utils.define_box_regions",
"sfepy.base.base.Struct",
"sfepy.homogenization.utils.coor_to_sym",
"sfepy.discrete.fem.mesh.Mesh.from_file"
] | [((4603, 4632), 'sfepy.discrete.fem.mesh.Mesh.from_file', 'Mesh.from_file', (['filename_mesh'], {}), '(filename_mesh)\n', (4617, 4632), False, 'from sfepy.discrete.fem.mesh import Mesh\n'), ((4834, 4891), 'sfepy.homogenization.utils.define_box_regions', 'define_box_regions', (['mesh.dim', 'bbox[0]', 'bbox[1]'], {'eps': '(0.001)'}), '(mesh.dim, bbox[0], bbox[1], eps=0.001)\n', (4852, 4891), False, 'from sfepy.homogenization.utils import coor_to_sym, define_box_regions\n'), ((1025, 1135), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': "('cell' if v[2] == 'c' else 'vertex')", 'data': 'v[0]', 'var_name': 'v[1]', 'dofs': 'None'}), "(name='output_data', mode='cell' if v[2] == 'c' else 'vertex', data=v\n [0], var_name=v[1], dofs=None)\n", (1031, 1135), False, 'from sfepy.base.base import Struct\n'), ((4544, 4590), 'os.path.join', 'osp.join', (['data_dir', '"""piezo_mesh_micro_dfc.vtk"""'], {}), "(data_dir, 'piezo_mesh_micro_dfc.vtk')\n", (4552, 4590), True, 'import os.path as osp\n'), ((6417, 6446), 'os.path.join', 'osp.join', (['data_dir', '"""results"""'], {}), "(data_dir, 'results')\n", (6425, 6446), True, 'import os.path as osp\n'), ((2623, 2647), 'sfepy.homogenization.utils.coor_to_sym', 'coor_to_sym', (['ii', 'jj', 'dim'], {}), '(ii, jj, dim)\n', (2634, 2647), False, 'from sfepy.homogenization.utils import coor_to_sym, define_box_regions\n'), ((3137, 3161), 'sfepy.homogenization.utils.coor_to_sym', 'coor_to_sym', (['ii', 'jj', 'dim'], {}), '(ii, jj, dim)\n', (3148, 3161), False, 'from sfepy.homogenization.utils import coor_to_sym, define_box_regions\n'), ((3478, 3498), 'numpy.vstack', 'nm.vstack', (['e_mac_Yms'], {}), '(e_mac_Yms)\n', (3487, 3498), True, 'import numpy as nm\n'), ((4653, 4686), 'numpy.unique', 'nm.unique', (['mesh.cmesh.cell_groups'], {}), '(mesh.cmesh.cell_groups)\n', (4662, 4686), True, 'import numpy as nm\n'), ((2730, 2781), 'numpy.expand_dims', 'nm.expand_dims', (["macro['strain'][Ym_map, kk]"], {'axis': '(1)'}), "(macro['strain'][Ym_map, kk], axis=1)\n", (2744, 2781), True, 'import numpy as nm\n'), ((2863, 2915), 'numpy.expand_dims', 'nm.expand_dims', (["macro['strain'][Yms_map, kk]"], {'axis': '(1)'}), "(macro['strain'][Yms_map, kk], axis=1)\n", (2877, 2915), True, 'import numpy as nm\n'), ((15322, 15374), 'sfepy.mechanics.matcoefs.stiffness_from_youngpoisson', 'stiffness_from_youngpoisson', (['(3)', '(200000000000.0)', '(0.25)'], {}), '(3, 200000000000.0, 0.25)\n', (15349, 15374), False, 'from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson\n'), ((8160, 8258), 'numpy.array', 'nm.array', (['[[0, 0, 0, 0, 11.404, 0], [0, 0, 0, 0, 0, 11.404], [-4.322, -4.322, 17.36, \n 0, 0, 0]]'], {}), '([[0, 0, 0, 0, 11.404, 0], [0, 0, 0, 0, 0, 11.404], [-4.322, -4.322,\n 17.36, 0, 0, 0]])\n', (8168, 8258), True, 'import numpy as nm\n'), ((7751, 7939), 'numpy.array', 'nm.array', (['[[1.504, 0.656, 0.659, 0, 0, 0], [0.656, 1.504, 0.659, 0, 0, 0], [0.659, \n 0.659, 1.455, 0, 0, 0], [0, 0, 0, 0.424, 0, 0], [0, 0, 0, 0, 0.439, 0],\n [0, 0, 0, 0, 0, 0.439]]'], {}), '([[1.504, 0.656, 0.659, 0, 0, 0], [0.656, 1.504, 0.659, 0, 0, 0], [\n 0.659, 0.659, 1.455, 0, 0, 0], [0, 0, 0, 0.424, 0, 0], [0, 0, 0, 0, \n 0.439, 0], [0, 0, 0, 0, 0, 0.439]])\n', (7759, 7939), True, 'import numpy as nm\n'), ((8339, 8394), 'numpy.array', 'nm.array', (['[[1.284, 0, 0], [0, 1.284, 0], [0, 0, 1.505]]'], {}), '([[1.284, 0, 0], [0, 1.284, 0], [0, 0, 1.505]])\n', (8347, 8394), True, 'import numpy as nm\n')] |
# Vibroacoustics
#
# E.Rohan, V.Lukeš
# Homogenization of the vibro–acoustic transmission on periodically
# perforated elastic plates with arrays of resonators.
# https://arxiv.org/abs/2104.01367 (arXiv:2104.01367v1)
import os
import numpy as nm
from sfepy.base.base import Struct
from sfepy.homogenization.coefficients import Coefficients
from sfepy.discrete.fem import Mesh, FEDomain
def coefs2qp(out, coefs, nqp):
others = {}
for k, v in coefs.items():
if type(v) is nm.float64:
v = nm.array(v)
if type(v) is not nm.ndarray:
others[k] = v
continue
if k[0] == 's':
out[k] = nm.tile(v, (nqp, 1, 1))
else:
if not(k in out):
out[k] = nm.tile(v, (nqp, 1, 1))
out.update(others)
return out
def get_homogmat(coors, mode, pb, coefs_filename, omega=None):
if mode == 'qp':
nqp = coors.shape[0]
outdir = pb.conf.options['output_dir']
cfname = os.path.join(outdir, coefs_filename + '.h5')
out = {}
print('>>> coefs from: ', cfname)
coefs_ = Coefficients.from_file_hdf5(cfname).to_dict()
coefs = {}
if 'omega' in coefs_ and omega is not None:
idx = (nm.abs(coefs_['omega'] - omega)).argmin()
rerr = nm.abs(coefs_['omega'][idx] - omega) / omega
if rerr > 1e-3:
raise ValueError('omega: given=%e, found=%e'
% (omega, coefs_['omega'][idx]))
print('found coeficcients for w=%e' % coefs_['omega'][idx])
del(coefs_['omega'])
else:
idx = 4 # magic index?
for k, v in coefs_.items():
if isinstance(v, nm.ndarray) and len(v.shape) == 3:
coefs[k] = v[idx, ...]
else:
coefs[k] = v
coefs2qp(out, coefs, nqp)
transpose = [k for k, v in out.items()
if type(v) == nm.ndarray and (v.shape[-1] > v.shape[-2])]
for k in transpose:
out[k] = out[k].transpose((0, 2, 1))
return out
def read_dict_hdf5(filename, level=0, group=None, fd=None):
import tables as pt
out = {}
if level == 0:
# fd = pt.openFile(filename, mode='r')
fd = pt.open_file(filename, mode='r')
group = fd.root
for name, gr in group._v_groups.items():
name = name.replace('_', '', 1)
out[name] = read_dict_hdf5(filename, level + 1, gr, fd)
for name, data in group._v_leaves.items():
name = name.replace('_', '', 1)
out[name] = data.read()
if level == 0:
fd.close()
return out
def eval_phi(pb, state_p1, state_p2, p_inc):
pvars = pb.create_variables(['P1', 'P2'])
# transmission loss function: log10(|p_in|^2/|p_out|^2)
pvars['P2'].set_data(nm.ones_like(state_p2) * p_inc**2)
phi_In = pb.evaluate('ev_surface_integrate.5.GammaIn(P2)',
P2=pvars['P2'])
pvars['P1'].set_data(state_p1**2)
phi_Out = pb.evaluate('ev_surface_integrate.5.GammaOut(P1)',
P1=pvars['P1'])
return 10.0 * nm.log10(nm.absolute(phi_In) / nm.absolute(phi_Out))
def post_process(out, pb, state, save_var0='p0'):
rmap = {'g01': 0, 'g02': 0, 'g0': 0, 'dp0': 0, 'sp0': 0, 'p0': 0,
'px': 1, 'p1': 1, 'p2': 2}
for k in out.keys():
if 'real_' in k or 'imag_' in k:
newk = k[:4] + '.' + k[5:]
out[newk] = out[k]
del(out[k])
midfn = pb.conf.filename_mesh_plate
fname, _ = os.path.splitext(os.path.basename(midfn))
fname = os.path.join(pb.output_dir, fname + '.h5')
aux = []
for k, v in read_dict_hdf5(fname)['step0'].items():
if ('real' in k) or ('imag' in k):
aux.append(k)
vn = k.strip('_').split('_')
key = '%s.%s' % tuple(vn)
if key not in out:
out[key] = Struct(name=v['name'].decode('ascii'),
mode=v['mode'].decode('ascii'),
dofs=[j.decode('ascii') for j in v['dofs']],
var_name=v['varname'].decode('ascii'),
shape=v['shape'],
data=v['data'],
dname=v['dname'])
if 'imag' in k:
rmap[vn[1]] = 0
absvars = [ii[4:] for ii in out.keys() if ii[0:4] == 'imag']
for ii in absvars:
if type(out['real' + ii]) is dict:
rpart = out.pop('real' + ii)
rdata = rpart['data']
ipart = out.pop('imag' + ii)
idata = ipart['data']
dim = rdata.shape[1]
varname = save_var0
if dim > 1:
aux = nm.zeros((rdata.shape[0], 1), dtype=nm.float64)
data = rdata if dim < 2 else nm.hstack((rdata, aux))
out['real' + ii] = Struct(name=rpart['name'],
mode=rpart['mode'],
dofs=rpart['dofs'],
var_name=varname,
data=data.copy())
data = idata if dim < 2 else nm.hstack((idata, aux))
out['imag' + ii] = Struct(name=ipart['name'],
mode=ipart['mode'],
dofs=ipart['dofs'],
var_name=varname,
data=data.copy())
else:
rpart = out['real' + ii].__dict__
rdata = rpart['data']
ipart = out['imag' + ii].__dict__
idata = ipart['data']
varname = rpart['var_name']
absval = nm.absolute(rdata + 1j*idata)
if rdata.shape[1] > 1:
aux = nm.zeros((rpart['data'].shape[0], 1), dtype=nm.float64)
absval = nm.hstack((absval, aux))
out[ii[1:]] = Struct(name=rpart['name'],
mode=rpart['mode'],
dofs=rpart['dofs'],
var_name=varname,
data=absval.copy())
# all plate variables as save_var0
for k in out.keys():
k0 = k.replace('imag.', '').replace('real.', '')
if rmap[k0] == 0:
out[k].var_name = save_var0
return out
def get_region_entities(rvar, noff=0):
reg = rvar.field.region
mesh = reg.domain.mesh
rnodes = reg.entities[0]
coors = mesh.coors
ngrp = mesh.cmesh.vertex_groups.squeeze()
descs = mesh.descs[0]
rcells = reg.entities[-1]
rconn = mesh.get_conn(descs)[rcells]
mat_ids = mesh.cmesh.cell_groups[rcells]
remap = -nm.ones((nm.max(rnodes) + 1,), dtype=nm.int64)
remap[rnodes] = nm.arange(rnodes.shape[0]) + noff
rconn = remap[rconn]
nmap = nm.where(remap >= 0)[0]
return coors[rnodes, :], ngrp[rnodes], rconn, mat_ids, descs, nmap
def generate_plate_mesh(fname):
dim_tab = {'3_4': '2_3', '3_8': '2_4'}
mesh3d = Mesh.from_file(fname)
domain = FEDomain('domain', mesh3d)
domain.create_region('Omega1', 'cells of group 1')
domain.create_region('Omega2', 'cells of group 2')
gamma0 = domain.create_region('Gamma0', 'r.Omega1 *v r.Omega2', 'facet')
cmesh = mesh3d.cmesh
cmesh.setup_connectivity(2, 0)
fcnd = cmesh.get_conn(2, 0)
fcidxs = gamma0.entities[2]
fcconn = []
for ii in fcidxs:
fcconn.append(fcnd.indices[fcnd.offsets[ii]:fcnd.offsets[ii + 1]])
fcconn = nm.array(fcconn)
remap = nm.zeros((nm.max(fcconn) + 1,), dtype=nm.int32)
remap[fcconn] = 1
ndidxs = nm.where(remap > 0)[0]
remap[ndidxs] = nm.arange(len(ndidxs))
coors2 = domain.mesh.coors[ndidxs, :]
conn2 = remap[fcconn]
ngrps2 = nm.ones((coors2.shape[0],))
mids2 = nm.ones((conn2.shape[0],))
midfn = fname[:-4] + '_plate.vtk'
mesh2d = Mesh.from_data('2d plate', coors2, ngrps2, [conn2], [mids2],
[dim_tab[mesh3d.descs[0]]])
mesh2d.write(midfn)
return midfn
| [
"sfepy.homogenization.coefficients.Coefficients.from_file_hdf5",
"sfepy.discrete.fem.Mesh.from_data",
"sfepy.discrete.fem.Mesh.from_file",
"sfepy.discrete.fem.FEDomain"
] | [((3633, 3675), 'os.path.join', 'os.path.join', (['pb.output_dir', "(fname + '.h5')"], {}), "(pb.output_dir, fname + '.h5')\n", (3645, 3675), False, 'import os\n'), ((7126, 7147), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['fname'], {}), '(fname)\n', (7140, 7147), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((7161, 7187), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""domain"""', 'mesh3d'], {}), "('domain', mesh3d)\n", (7169, 7187), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((7625, 7641), 'numpy.array', 'nm.array', (['fcconn'], {}), '(fcconn)\n', (7633, 7641), True, 'import numpy as nm\n'), ((7885, 7912), 'numpy.ones', 'nm.ones', (['(coors2.shape[0],)'], {}), '((coors2.shape[0],))\n', (7892, 7912), True, 'import numpy as nm\n'), ((7925, 7951), 'numpy.ones', 'nm.ones', (['(conn2.shape[0],)'], {}), '((conn2.shape[0],))\n', (7932, 7951), True, 'import numpy as nm\n'), ((8004, 8097), 'sfepy.discrete.fem.Mesh.from_data', 'Mesh.from_data', (['"""2d plate"""', 'coors2', 'ngrps2', '[conn2]', '[mids2]', '[dim_tab[mesh3d.descs[0]]]'], {}), "('2d plate', coors2, ngrps2, [conn2], [mids2], [dim_tab[\n mesh3d.descs[0]]])\n", (8018, 8097), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((999, 1043), 'os.path.join', 'os.path.join', (['outdir', "(coefs_filename + '.h5')"], {}), "(outdir, coefs_filename + '.h5')\n", (1011, 1043), False, 'import os\n'), ((2287, 2319), 'tables.open_file', 'pt.open_file', (['filename'], {'mode': '"""r"""'}), "(filename, mode='r')\n", (2299, 2319), True, 'import tables as pt\n'), ((3596, 3619), 'os.path.basename', 'os.path.basename', (['midfn'], {}), '(midfn)\n', (3612, 3619), False, 'import os\n'), ((5821, 5854), 'numpy.absolute', 'nm.absolute', (['(rdata + 1.0j * idata)'], {}), '(rdata + 1.0j * idata)\n', (5832, 5854), True, 'import numpy as nm\n'), ((6868, 6894), 'numpy.arange', 'nm.arange', (['rnodes.shape[0]'], {}), '(rnodes.shape[0])\n', (6877, 6894), True, 'import numpy as nm\n'), ((6939, 6959), 'numpy.where', 'nm.where', (['(remap >= 0)'], {}), '(remap >= 0)\n', (6947, 6959), True, 'import numpy as nm\n'), ((7738, 7757), 'numpy.where', 'nm.where', (['(remap > 0)'], {}), '(remap > 0)\n', (7746, 7757), True, 'import numpy as nm\n'), ((517, 528), 'numpy.array', 'nm.array', (['v'], {}), '(v)\n', (525, 528), True, 'import numpy as nm\n'), ((661, 684), 'numpy.tile', 'nm.tile', (['v', '(nqp, 1, 1)'], {}), '(v, (nqp, 1, 1))\n', (668, 684), True, 'import numpy as nm\n'), ((2848, 2870), 'numpy.ones_like', 'nm.ones_like', (['state_p2'], {}), '(state_p2)\n', (2860, 2870), True, 'import numpy as nm\n'), ((5900, 5955), 'numpy.zeros', 'nm.zeros', (["(rpart['data'].shape[0], 1)"], {'dtype': 'nm.float64'}), "((rpart['data'].shape[0], 1), dtype=nm.float64)\n", (5908, 5955), True, 'import numpy as nm\n'), ((5977, 6001), 'numpy.hstack', 'nm.hstack', (['(absval, aux)'], {}), '((absval, aux))\n', (5986, 6001), True, 'import numpy as nm\n'), ((755, 778), 'numpy.tile', 'nm.tile', (['v', '(nqp, 1, 1)'], {}), '(v, (nqp, 1, 1))\n', (762, 778), True, 'import numpy as nm\n'), ((1121, 1156), 'sfepy.homogenization.coefficients.Coefficients.from_file_hdf5', 'Coefficients.from_file_hdf5', (['cfname'], {}), '(cfname)\n', (1148, 1156), False, 'from sfepy.homogenization.coefficients import Coefficients\n'), ((1319, 1355), 'numpy.abs', 'nm.abs', (["(coefs_['omega'][idx] - omega)"], {}), "(coefs_['omega'][idx] - omega)\n", (1325, 1355), True, 'import numpy as nm\n'), ((3157, 3176), 'numpy.absolute', 'nm.absolute', (['phi_In'], {}), '(phi_In)\n', (3168, 3176), True, 'import numpy as nm\n'), ((3179, 3199), 'numpy.absolute', 'nm.absolute', (['phi_Out'], {}), '(phi_Out)\n', (3190, 3199), True, 'import numpy as nm\n'), ((4837, 4884), 'numpy.zeros', 'nm.zeros', (['(rdata.shape[0], 1)'], {'dtype': 'nm.float64'}), '((rdata.shape[0], 1), dtype=nm.float64)\n', (4845, 4884), True, 'import numpy as nm\n'), ((4927, 4950), 'numpy.hstack', 'nm.hstack', (['(rdata, aux)'], {}), '((rdata, aux))\n', (4936, 4950), True, 'import numpy as nm\n'), ((5278, 5301), 'numpy.hstack', 'nm.hstack', (['(idata, aux)'], {}), '((idata, aux))\n', (5287, 5301), True, 'import numpy as nm\n'), ((7665, 7679), 'numpy.max', 'nm.max', (['fcconn'], {}), '(fcconn)\n', (7671, 7679), True, 'import numpy as nm\n'), ((1258, 1289), 'numpy.abs', 'nm.abs', (["(coefs_['omega'] - omega)"], {}), "(coefs_['omega'] - omega)\n", (1264, 1289), True, 'import numpy as nm\n'), ((6810, 6824), 'numpy.max', 'nm.max', (['rnodes'], {}), '(rnodes)\n', (6816, 6824), True, 'import numpy as nm\n')] |
import numpy as nm
from sfepy.base.base import OneTypeList, Container, Struct
class Functions(Container):
"""Container to hold all user-defined functions."""
def from_conf(conf):
objs = OneTypeList(Function)
for key, fc in conf.iteritems():
fun = Function(name = fc.name,
function = fc.function,
is_constant = False,
extra_args = {})
objs.append(fun)
obj = Functions(objs)
return obj
from_conf = staticmethod(from_conf)
class Function(Struct):
"""Base class for user-defined functions."""
def __init__(self, name, function, is_constant=False, extra_args=None):
Struct.__init__(self, name = name, function = function,
is_constant = is_constant)
if extra_args is None:
extra_args = {}
self.extra_args = extra_args
def __call__(self, *args, **kwargs):
_kwargs = dict(kwargs)
_kwargs.update(self.extra_args)
return self.function(*args, **_kwargs)
def set_function(self, function, is_constant=False):
self.function = function
self.is_constant = is_constant
def set_extra_args(self, **extra_args):
self.extra_args = extra_args
class ConstantFunction(Function):
"""Function with constant values."""
def __init__(self, values):
"""Make a function out of a dictionary of constant values. When
called with coors argument, the values are repeated for each
coordinate."""
name = '_'.join(['get_constants'] + values.keys())
def get_constants(ts=None, coors=None, mode=None, **kwargs):
out = {}
if mode == 'special':
for key, val in values.iteritems():
if '.' in key:
vkey = key.split('.')[1]
out[vkey] = val
elif (mode == 'qp'):
for key, val in values.iteritems():
if '.' in key: continue
val = nm.array(val, dtype=nm.float64, ndmin=3)
out[key] = nm.tile(val, (coors.shape[0], 1, 1))
elif (mode == 'special_constant') or (mode is None):
for key, val in values.iteritems():
if '.' in key: continue
out[key] = val
else:
raise ValueError('unknown function mode! (%s)' % mode)
return out
Function.__init__(self, name = name, function = get_constants,
is_constant = True)
class ConstantFunctionByRegion(Function):
"""
Function with constant values in regions.
"""
def __init__(self, values):
"""
Make a function out of a dictionary of constant values per region. When
called with coors argument, the values are repeated for each
coordinate in each of the given regions.
"""
name = '_'.join(['get_constants_by_region'] + values.keys())
def get_constants(ts=None, coors=None, mode=None,
term=None, problem=None, **kwargs):
out = {}
if mode == 'qp':
qps = term.get_physical_qps()
for key, val in values.iteritems():
if '.' in key: continue
rval = nm.array(val[val.keys()[0]], dtype=nm.float64,
ndmin=3)
matdata = nm.zeros((coors.shape[0], ) + rval.shape[1:],
dtype=nm.float64)
for rkey, rval in val.iteritems():
region = problem.domain.regions[rkey]
rval = nm.array(rval, dtype=nm.float64, ndmin=3)
for ig in region.igs:
if not (ig in qps.igs):
continue
matdata[qps.rindx[ig]] = rval
out[key] = matdata
return out
Function.__init__(self, name=name, function=get_constants,
is_constant=True)
| [
"sfepy.base.base.OneTypeList",
"sfepy.base.base.Struct.__init__"
] | [((205, 226), 'sfepy.base.base.OneTypeList', 'OneTypeList', (['Function'], {}), '(Function)\n', (216, 226), False, 'from sfepy.base.base import OneTypeList, Container, Struct\n'), ((732, 808), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'name': 'name', 'function': 'function', 'is_constant': 'is_constant'}), '(self, name=name, function=function, is_constant=is_constant)\n', (747, 808), False, 'from sfepy.base.base import OneTypeList, Container, Struct\n'), ((3529, 3591), 'numpy.zeros', 'nm.zeros', (['((coors.shape[0],) + rval.shape[1:])'], {'dtype': 'nm.float64'}), '((coors.shape[0],) + rval.shape[1:], dtype=nm.float64)\n', (3537, 3591), True, 'import numpy as nm\n'), ((2098, 2138), 'numpy.array', 'nm.array', (['val'], {'dtype': 'nm.float64', 'ndmin': '(3)'}), '(val, dtype=nm.float64, ndmin=3)\n', (2106, 2138), True, 'import numpy as nm\n'), ((2170, 2206), 'numpy.tile', 'nm.tile', (['val', '(coors.shape[0], 1, 1)'], {}), '(val, (coors.shape[0], 1, 1))\n', (2177, 2206), True, 'import numpy as nm\n'), ((3781, 3822), 'numpy.array', 'nm.array', (['rval'], {'dtype': 'nm.float64', 'ndmin': '(3)'}), '(rval, dtype=nm.float64, ndmin=3)\n', (3789, 3822), True, 'import numpy as nm\n')] |
r"""
Poisson equation.
This example demonstrates parametric study capabilities of Application
classes. In particular (written in the strong form):
.. math::
c \Delta t = f \mbox{ in } \Omega,
t = 2 \mbox{ on } \Gamma_1 \;,
t = -2 \mbox{ on } \Gamma_2 \;,
f = 1 \mbox{ in } \Omega_1 \;,
f = 0 \mbox{ otherwise,}
where :math:`\Omega` is a square domain, :math:`\Omega_1 \in \Omega` is
a circular domain.
Now let's see what happens if :math:`\Omega_1` diameter changes.
Run::
$ ./simple.py <this file>
and then look in 'output/r_omega1' directory, try for example::
$ ./postproc.py output/r_omega1/circles_in_square*.vtk
Remark: this simple case could be achieved also by defining
:math:`\Omega_1` by a time-dependent function and solve the static
problem as a time-dependent problem. However, the approach below is much
more general.
Find :math:`t` such that:
.. math::
\int_{\Omega} c \nabla s \cdot \nabla t
= 0
\;, \quad \forall s \;.
"""
from __future__ import absolute_import
import os
import numpy as nm
from sfepy import data_dir
from sfepy.base.base import output
# Mesh.
filename_mesh = data_dir + '/meshes/2d/special/circles_in_square.vtk'
# Options. The value of 'parametric_hook' is the function that does the
# parametric study.
options = {
'nls' : 'newton', # Nonlinear solver
'ls' : 'ls', # Linear solver
'parametric_hook' : 'vary_omega1_size',
'output_dir' : 'output/r_omega1',
}
# Domain and subdomains.
default_diameter = 0.25
regions = {
'Omega' : 'all',
'Gamma_1' : ('vertices in (x < -0.999)', 'facet'),
'Gamma_2' : ('vertices in (x > 0.999)', 'facet'),
'Omega_1' : 'vertices by select_circ',
}
# FE field defines the FE approximation: 2_3_P1 = 2D, P1 on triangles.
field_1 = {
'name' : 'temperature',
'dtype' : 'real',
'shape' : (1,),
'region' : 'Omega',
'approx_order' : 1,
}
# Unknown and test functions (FE sense).
variables = {
't' : ('unknown field', 'temperature', 0),
's' : ('test field', 'temperature', 't'),
}
# Dirichlet boundary conditions.
ebcs = {
't1' : ('Gamma_1', {'t.0' : 2.0}),
't2' : ('Gamma_2', {'t.0' : -2.0}),
}
# Material coefficient c and source term value f.
material_1 = {
'name' : 'coef',
'values' : {
'val' : 1.0,
}
}
material_2 = {
'name' : 'source',
'values' : {
'val' : 10.0,
}
}
# Numerical quadrature and the equation.
integral_1 = {
'name' : 'i',
'order' : 2,
}
equations = {
'Poisson' : """dw_laplace.i.Omega( coef.val, s, t )
= dw_volume_lvf.i.Omega_1( source.val, s )"""
}
# Solvers.
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,
}
functions = {
'select_circ': (lambda coors, domain=None:
select_circ(coors[:,0], coors[:,1], 0, default_diameter),),
}
# Functions.
def select_circ( x, y, z, diameter ):
"""Select circular subdomain of a given diameter."""
r = nm.sqrt( x**2 + y**2 )
out = nm.where(r < diameter)[0]
n = out.shape[0]
if n <= 3:
raise ValueError( 'too few vertices selected! (%d)' % n )
return out
def vary_omega1_size( problem ):
"""Vary size of \Omega1. Saves also the regions into options['output_dir'].
Input:
problem: Problem instance
Return:
a generator object:
1. creates new (modified) problem
2. yields the new (modified) problem and output container
3. use the output container for some logging
4. yields None (to signal next iteration to Application)
"""
from sfepy.discrete import Problem
from sfepy.solvers.ts import get_print_info
output.prefix = 'vary_omega1_size:'
diameters = nm.linspace( 0.1, 0.6, 7 ) + 0.001
ofn_trunk, output_format = problem.ofn_trunk, problem.output_format
output_dir = problem.output_dir
join = os.path.join
conf = problem.conf
cf = conf.get_raw( 'functions' )
n_digit, aux, d_format = get_print_info( len( diameters ) + 1 )
for ii, diameter in enumerate( diameters ):
output( 'iteration %d: diameter %3.2f' % (ii, diameter) )
cf['select_circ'] = (lambda coors, domain=None:
select_circ(coors[:,0], coors[:,1], 0, diameter),)
conf.edit('functions', cf)
problem = Problem.from_conf(conf)
problem.save_regions( join( output_dir, ('regions_' + d_format) % ii ),
['Omega_1'] )
region = problem.domain.regions['Omega_1']
if not region.has_cells():
raise ValueError('region %s has no cells!' % region.name)
ofn_trunk = ofn_trunk + '_' + (d_format % ii)
problem.setup_output(output_filename_trunk=ofn_trunk,
output_dir=output_dir,
output_format=output_format)
out = []
yield problem, out
out_problem, state = out[-1]
filename = join( output_dir,
('log_%s.txt' % d_format) % ii )
fd = open( filename, 'w' )
log_item = '$r(\Omega_1)$: %f\n' % diameter
fd.write( log_item )
fd.write( 'solution:\n' )
nm.savetxt(fd, state())
fd.close()
yield None
| [
"sfepy.base.base.output",
"sfepy.discrete.Problem.from_conf"
] | [((3347, 3371), 'numpy.sqrt', 'nm.sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (3354, 3371), True, 'import numpy as nm\n'), ((3381, 3403), 'numpy.where', 'nm.where', (['(r < diameter)'], {}), '(r < diameter)\n', (3389, 3403), True, 'import numpy as nm\n'), ((4097, 4121), 'numpy.linspace', 'nm.linspace', (['(0.1)', '(0.6)', '(7)'], {}), '(0.1, 0.6, 7)\n', (4108, 4121), True, 'import numpy as nm\n'), ((4450, 4505), 'sfepy.base.base.output', 'output', (["('iteration %d: diameter %3.2f' % (ii, diameter))"], {}), "('iteration %d: diameter %3.2f' % (ii, diameter))\n", (4456, 4505), False, 'from sfepy.base.base import output\n'), ((4699, 4722), 'sfepy.discrete.Problem.from_conf', 'Problem.from_conf', (['conf'], {}), '(conf)\n', (4716, 4722), False, 'from sfepy.discrete import Problem\n')] |
r"""
Laplace equation with Dirichlet boundary conditions given by a sine function
and constants.
Find :math:`t` such that:
.. math::
\int_{\Omega} c \nabla s \cdot \nabla t
= 0
\;, \quad \forall s \;.
The :class:`sfepy.discrete.fem.meshio.UserMeshIO` class is used to refine the
original two-element mesh before the actual solution.
The FE polynomial basis and the approximation order can be chosen on the
command-line. By default, the fifth order Lagrange polynomial space is used,
see ``define()`` arguments.
This example demonstrates how to visualize higher order approximations of the
continuous solution. The adaptive linearization is applied in order to save
viewable results, see both the options keyword and the ``post_process()``
function that computes the solution gradient. The linearization parameters can
also be specified on the command line.
The Lagrange or Bernstein polynomial bases support higher order
DOFs in the Dirichlet boundary conditions, unlike the hierarchical Lobatto
basis implementation, compare the results of::
python simple.py examples/diffusion/sinbc.py -d basis=lagrange
python simple.py examples/diffusion/sinbc.py -d basis=bernstein
python simple.py examples/diffusion/sinbc.py -d basis=lobatto
Use the following commands to view each of the results of the above commands
(assuming default output directory and names)::
python postproc.py -b -d't,plot_warp_scalar,rel_scaling=1' 2_4_2_refined_t.vtk --wireframe
python postproc.py -b 2_4_2_refined_grad.vtk
"""
from __future__ import absolute_import
import numpy as nm
from sfepy import data_dir
from sfepy.base.base import output
from sfepy.discrete.fem import Mesh, FEDomain
from sfepy.discrete.fem.meshio import UserMeshIO, MeshIO
from sfepy.homogenization.utils import define_box_regions
from six.moves import range
base_mesh = data_dir + '/meshes/elements/2_4_2.mesh'
def mesh_hook(mesh, mode):
"""
Load and refine a mesh here.
"""
if mode == 'read':
mesh = Mesh.from_file(base_mesh)
domain = FEDomain(mesh.name, mesh)
for ii in range(3):
output('refine %d...' % ii)
domain = domain.refine()
output('... %d nodes %d elements'
% (domain.shape.n_nod, domain.shape.n_el))
domain.mesh.name = '2_4_2_refined'
return domain.mesh
elif mode == 'write':
pass
def post_process(out, pb, state, extend=False):
"""
Calculate gradient of the solution.
"""
from sfepy.discrete.fem.fields_base import create_expression_output
aux = create_expression_output('ev_grad.ie.Elements( t )',
'grad', 'temperature',
pb.fields, pb.get_materials(),
pb.get_variables(), functions=pb.functions,
mode='qp', verbose=False,
min_level=0, max_level=5, eps=1e-3)
out.update(aux)
return out
def define(order=5, basis='lagrange', min_level=0, max_level=5, eps=1e-3):
filename_mesh = UserMeshIO(mesh_hook)
# Get the mesh bounding box.
io = MeshIO.any_from_filename(base_mesh)
bbox, dim = io.read_bounding_box(ret_dim=True)
options = {
'nls' : 'newton',
'ls' : 'ls',
'post_process_hook' : 'post_process',
'linearization' : {
'kind' : 'adaptive',
'min_level' : min_level, # Min. refinement level applied everywhere.
'max_level' : max_level, # Max. refinement level.
'eps' : eps, # Relative error tolerance.
},
}
materials = {
'coef' : ({'val' : 1.0},),
}
regions = {
'Omega' : 'all',
}
regions.update(define_box_regions(dim, bbox[0], bbox[1], 1e-5))
fields = {
'temperature' : ('real', 1, 'Omega', order, 'H1', basis),
}
variables = {
't' : ('unknown field', 'temperature', 0),
's' : ('test field', 'temperature', 't'),
}
amplitude = 1.0
def ebc_sin(ts, coor, **kwargs):
x0 = 0.5 * (coor[:, 1].min() + coor[:, 1].max())
val = amplitude * nm.sin( (coor[:, 1] - x0) * 2. * nm.pi )
return val
ebcs = {
't1' : ('Left', {'t.0' : 'ebc_sin'}),
't2' : ('Right', {'t.0' : -0.5}),
't3' : ('Top', {'t.0' : 1.0}),
}
functions = {
'ebc_sin' : (ebc_sin,),
}
equations = {
'Temperature' : """dw_laplace.10.Omega(coef.val, s, t) = 0"""
}
solvers = {
'ls' : ('ls.scipy_direct', {}),
'newton' : ('nls.newton', {
'i_max' : 1,
'eps_a' : 1e-10,
}),
}
return locals()
| [
"sfepy.base.base.output",
"sfepy.discrete.fem.meshio.UserMeshIO",
"sfepy.homogenization.utils.define_box_regions",
"sfepy.discrete.fem.meshio.MeshIO.any_from_filename",
"sfepy.discrete.fem.Mesh.from_file",
"sfepy.discrete.fem.FEDomain"
] | [((3111, 3132), 'sfepy.discrete.fem.meshio.UserMeshIO', 'UserMeshIO', (['mesh_hook'], {}), '(mesh_hook)\n', (3121, 3132), False, 'from sfepy.discrete.fem.meshio import UserMeshIO, MeshIO\n'), ((3176, 3211), 'sfepy.discrete.fem.meshio.MeshIO.any_from_filename', 'MeshIO.any_from_filename', (['base_mesh'], {}), '(base_mesh)\n', (3200, 3211), False, 'from sfepy.discrete.fem.meshio import UserMeshIO, MeshIO\n'), ((2008, 2033), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['base_mesh'], {}), '(base_mesh)\n', (2022, 2033), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((2051, 2076), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['mesh.name', 'mesh'], {}), '(mesh.name, mesh)\n', (2059, 2076), False, 'from sfepy.discrete.fem import Mesh, FEDomain\n'), ((2095, 2103), 'six.moves.range', 'range', (['(3)'], {}), '(3)\n', (2100, 2103), False, 'from six.moves import range\n'), ((3774, 3822), 'sfepy.homogenization.utils.define_box_regions', 'define_box_regions', (['dim', 'bbox[0]', 'bbox[1]', '(1e-05)'], {}), '(dim, bbox[0], bbox[1], 1e-05)\n', (3792, 3822), False, 'from sfepy.homogenization.utils import define_box_regions\n'), ((2117, 2144), 'sfepy.base.base.output', 'output', (["('refine %d...' % ii)"], {}), "('refine %d...' % ii)\n", (2123, 2144), False, 'from sfepy.base.base import output\n'), ((2194, 2270), '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", (2200, 2270), False, 'from sfepy.base.base import output\n'), ((4181, 4220), 'numpy.sin', 'nm.sin', (['((coor[:, 1] - x0) * 2.0 * nm.pi)'], {}), '((coor[:, 1] - x0) * 2.0 * nm.pi)\n', (4187, 4220), True, 'import numpy as nm\n')] |
"""
Elapsed time measurement utilities.
"""
import time
from sfepy.base.base import Struct
class Timer(Struct):
def __init__(self, name='timer', start=False):
Struct.__init__(self, name=name)
self.time_function = time.perf_counter
self.reset()
if start:
self.start()
def reset(self):
self.t0 = self.t1 = None
self.total = self.dt = 0.0
def start(self, reset=False):
if reset: self.reset()
self.t1 = None
self.t0 = self.time_function()
def stop(self):
self.t1 = self.time_function()
if self.t0 is None:
raise ValueError('timer "%s" was not started!' % self.name)
self.dt = self.t1 - self.t0
self.total += self.dt
return self.dt
| [
"sfepy.base.base.Struct.__init__"
] | [((174, 206), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'name': 'name'}), '(self, name=name)\n', (189, 206), False, 'from sfepy.base.base import Struct\n')] |
"""
Functions to visualize the CMesh geometry and topology.
"""
from sfepy.postprocess.plot_dofs import _get_axes, _to2d
def plot_wireframe(ax, cmesh, color='k'):
"""
Plot a finite element mesh as a wireframe using edges connectivity.
"""
coors = cmesh.coors
coors = _to2d(coors)
dim = cmesh.dim
ax = _get_axes(ax, dim)
edges = cmesh.get_conn(1, 0)
for edge_vertices in edges.indices.reshape((edges.num, 2)):
cc = coors[edge_vertices]
ax.plot(*cc.T, color=color)
return ax
def plot_entities(ax, cmesh, edim, color='b', size=10):
"""
Plot mesh topology entities using scatter plot.
"""
coors = cmesh.get_centroids(edim)
coors = _to2d(coors)
dim = cmesh.dim
ax = _get_axes(ax, dim)
ax.scatter(*coors.T, s=size, c=color)
return ax
def label_global_entities(ax, cmesh, edim, color='b', fontsize=10):
"""
Label mesh topology entities using global ids.
"""
coors = cmesh.get_centroids(edim)
coors = _to2d(coors)
dim = cmesh.dim
ax = _get_axes(ax, dim)
for ii, cc in enumerate(coors):
ax.text(*cc.T, s=ii, color=color, fontsize=fontsize)
return ax
def label_local_entities(ax, cmesh, edim, color='b', fontsize=10):
"""
Label mesh topology entities using cell-local ids.
"""
coors = cmesh.get_centroids(edim)
coors = _to2d(coors)
dim = cmesh.dim
centres = cmesh.get_centroids(dim)
cmesh.setup_connectivity(dim, edim)
conn = cmesh.get_conn(dim, edim)
off = conn.offsets
ax = _get_axes(ax, dim)
eps = 0.1
oeps = 1.0 - eps
for ii in xrange(conn.num):
for ic, ie in enumerate(conn.indices[off[ii]:off[ii+1]]):
# Shift labels towards the cell centre.
cc = oeps * coors[ie] + eps * centres[ii]
ax.text(*cc.T, s=ic, color=color, fontsize=fontsize)
return ax
| [
"sfepy.postprocess.plot_dofs._to2d",
"sfepy.postprocess.plot_dofs._get_axes"
] | [((288, 300), 'sfepy.postprocess.plot_dofs._to2d', '_to2d', (['coors'], {}), '(coors)\n', (293, 300), False, 'from sfepy.postprocess.plot_dofs import _get_axes, _to2d\n'), ((331, 349), 'sfepy.postprocess.plot_dofs._get_axes', '_get_axes', (['ax', 'dim'], {}), '(ax, dim)\n', (340, 349), False, 'from sfepy.postprocess.plot_dofs import _get_axes, _to2d\n'), ((708, 720), 'sfepy.postprocess.plot_dofs._to2d', '_to2d', (['coors'], {}), '(coors)\n', (713, 720), False, 'from sfepy.postprocess.plot_dofs import _get_axes, _to2d\n'), ((751, 769), 'sfepy.postprocess.plot_dofs._get_axes', '_get_axes', (['ax', 'dim'], {}), '(ax, dim)\n', (760, 769), False, 'from sfepy.postprocess.plot_dofs import _get_axes, _to2d\n'), ((1013, 1025), 'sfepy.postprocess.plot_dofs._to2d', '_to2d', (['coors'], {}), '(coors)\n', (1018, 1025), False, 'from sfepy.postprocess.plot_dofs import _get_axes, _to2d\n'), ((1056, 1074), 'sfepy.postprocess.plot_dofs._get_axes', '_get_axes', (['ax', 'dim'], {}), '(ax, dim)\n', (1065, 1074), False, 'from sfepy.postprocess.plot_dofs import _get_axes, _to2d\n'), ((1377, 1389), 'sfepy.postprocess.plot_dofs._to2d', '_to2d', (['coors'], {}), '(coors)\n', (1382, 1389), False, 'from sfepy.postprocess.plot_dofs import _get_axes, _to2d\n'), ((1560, 1578), 'sfepy.postprocess.plot_dofs._get_axes', '_get_axes', (['ax', 'dim'], {}), '(ax, dim)\n', (1569, 1578), False, 'from sfepy.postprocess.plot_dofs import _get_axes, _to2d\n')] |
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
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
from sfepy.solvers.ls import ScipyDirect
from sfepy.solvers.nls import Newton
from sfepy.postprocess.viewer import Viewer
from sfepy.mechanics.matcoefs import stiffness_from_lame
import numpy as np
def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0):
"""
Define a displacement depending on the y coordinate.
"""
val = shift * coors[:,1]**2
return val
helps = {
'show' : 'show the results figure',
}
# def main():
from sfepy import data_dir
parser = ArgumentParser()
parser.add_argument('--version', action='version', version='%(prog)s')
parser.add_argument('-s', '--show',
action="store_true", dest='show',
default=False, help=helps['show'])
options = parser.parse_args()
# mesh = Mesh.from_file(data_dir + '/meshes/2d/rectangle_tri.mesh')
mesh = Mesh.from_file(data_dir + '/meshes/3d/cube_medium_hexa.mesh')
domain = FEDomain('domain', mesh)
# min_x, max_x = domain.get_mesh_bounding_box()[:,0]
# eps = 1e-8 * (max_x - min_x)
omega = domain.create_region('Omega', 'all')
# gamma1 = domain.create_region('Gamma1',
# 'vertices in x < %.10f' % (min_x + eps),
# 'facet')
Bottom = domain.create_region('Bottom',
'vertices in z < %.10f' % -0.499,
'facet')
# gamma2 = domain.create_region('Gamma2',
# 'vertices in x > %.10f' % (max_x - eps),
# 'facet')
Top = domain.create_region('Top',
'vertices in z > %.10f' % 0.499,
'facet')
field = Field.from_args('fu', nm.float64, 'vector', omega,
approx_order=3)
u = FieldVariable('u', 'unknown', field)
v = FieldVariable('v', 'test', field, primary_var_name='u')
# materials = {
# 'solid' : ({
# 'D': stiffness_from_lame(dim=3, lam=5.769, mu=3.846),
# },),
# 'cs' : ({
# 'f' : [1e5, 1e-2],
# '.c' : [0.0, 0.0, 1.2],
# '.r' : 0.8,
# },),
# }
# defK = materials['cs'][0]
# cs = ContactSphere(csc['.c'], csc['.r'])
m = Material('m', D=stiffness_from_lame(dim=3, lam=5.769, mu=3.846))
# f = Material('f', val=[[0.02], [0.01]])
# csf = Material('csf', val=[1e5, 1e-2])
# csc = Material('csc', val=[0.0, 0.0, 1.2])
# csr = Material('csr', val=0.8)
cs = Material('cs',f=[1e5, 1e-2],c=[0.0, 0.0, 1.2],r=0.8)
integral = Integral('i', order=3)
integral1 = Integral('i', order=2)
t1 = Term.new('dw_lin_elastic(m.D, v, u)',
integral, omega, m=m, v=v, u=u)
t2 = Term.new('dw_contact_sphere(cs.f, cs.c, cs.r, v, u)', integral1, Top, cs=cs, v=v, u=u)
eq = Equation('balance', t1 + t2)
eqs = Equations([eq])
fix_u = EssentialBC('fix_u', Bottom, {'u.all' : 0.0})
# bc_fun = Function('shift_u_fun', shift_u_fun,
# extra_args={'shift' : 0.01})
# shift_u = EssentialBC('shift_u', gamma2, {'u.0' : bc_fun})
ls = ScipyDirect({})
nls_status = IndexedStruct()
nls = Newton({}, lin_solver=ls, status=nls_status)
pb = Problem('elasticity', equations=eqs)
pb.save_regions_as_groups('regions')
pb.set_bcs(ebcs=Conditions([fix_u]))
pb.set_solver(nls)
status = IndexedStruct()
state = pb.solve(status=status)
print('Nonlinear solver status:\n', nls_status)
print('Stationary solver status:\n', status)
pb.save_state('linear_elasticity.vtk', state)
# if options.show:
view = Viewer('linear_elasticity.vtk')
view(vector_mode='warp_norm', rel_scaling=2,
is_scalar_bar=True, is_wireframe=True) | [
"sfepy.discrete.conditions.EssentialBC",
"sfepy.discrete.Integral",
"sfepy.postprocess.viewer.Viewer",
"sfepy.solvers.ls.ScipyDirect",
"sfepy.discrete.Equations",
"sfepy.discrete.fem.Field.from_args",
"sfepy.discrete.Equation",
"sfepy.discrete.fem.Mesh.from_file",
"sfepy.discrete.fem.FEDomain",
"s... | [((144, 164), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (159, 164), False, 'import sys\n'), ((971, 987), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (985, 987), False, 'from argparse import ArgumentParser\n'), ((1310, 1371), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (["(data_dir + '/meshes/3d/cube_medium_hexa.mesh')"], {}), "(data_dir + '/meshes/3d/cube_medium_hexa.mesh')\n", (1324, 1371), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1381, 1405), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['"""domain"""', 'mesh'], {}), "('domain', mesh)\n", (1389, 1405), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((2137, 2203), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""fu"""', 'nm.float64', '"""vector"""', 'omega'], {'approx_order': '(3)'}), "('fu', nm.float64, 'vector', omega, approx_order=3)\n", (2152, 2203), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((2233, 2269), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""u"""', '"""unknown"""', 'field'], {}), "('u', 'unknown', field)\n", (2246, 2269), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2274, 2329), 'sfepy.discrete.FieldVariable', 'FieldVariable', (['"""v"""', '"""test"""', 'field'], {'primary_var_name': '"""u"""'}), "('v', 'test', field, primary_var_name='u')\n", (2287, 2329), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2866, 2926), 'sfepy.discrete.Material', 'Material', (['"""cs"""'], {'f': '[100000.0, 0.01]', 'c': '[0.0, 0.0, 1.2]', 'r': '(0.8)'}), "('cs', f=[100000.0, 0.01], c=[0.0, 0.0, 1.2], r=0.8)\n", (2874, 2926), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2931, 2953), 'sfepy.discrete.Integral', 'Integral', (['"""i"""'], {'order': '(3)'}), "('i', order=3)\n", (2939, 2953), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2966, 2988), 'sfepy.discrete.Integral', 'Integral', (['"""i"""'], {'order': '(2)'}), "('i', order=2)\n", (2974, 2988), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((2995, 3064), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_lin_elastic(m.D, v, u)"""', 'integral', 'omega'], {'m': 'm', 'v': 'v', 'u': 'u'}), "('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u)\n", (3003, 3064), False, 'from sfepy.terms import Term\n'), ((3084, 3174), 'sfepy.terms.Term.new', 'Term.new', (['"""dw_contact_sphere(cs.f, cs.c, cs.r, v, u)"""', 'integral1', 'Top'], {'cs': 'cs', 'v': 'v', 'u': 'u'}), "('dw_contact_sphere(cs.f, cs.c, cs.r, v, u)', integral1, Top, cs=cs,\n v=v, u=u)\n", (3092, 3174), False, 'from sfepy.terms import Term\n'), ((3176, 3204), 'sfepy.discrete.Equation', 'Equation', (['"""balance"""', '(t1 + t2)'], {}), "('balance', t1 + t2)\n", (3184, 3204), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((3211, 3226), 'sfepy.discrete.Equations', 'Equations', (['[eq]'], {}), '([eq])\n', (3220, 3226), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((3236, 3280), 'sfepy.discrete.conditions.EssentialBC', 'EssentialBC', (['"""fix_u"""', 'Bottom', "{'u.all': 0.0}"], {}), "('fix_u', Bottom, {'u.all': 0.0})\n", (3247, 3280), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n'), ((3447, 3462), 'sfepy.solvers.ls.ScipyDirect', 'ScipyDirect', (['{}'], {}), '({})\n', (3458, 3462), False, 'from sfepy.solvers.ls import ScipyDirect\n'), ((3477, 3492), 'sfepy.base.base.IndexedStruct', 'IndexedStruct', ([], {}), '()\n', (3490, 3492), False, 'from sfepy.base.base import IndexedStruct\n'), ((3499, 3543), 'sfepy.solvers.nls.Newton', 'Newton', (['{}'], {'lin_solver': 'ls', 'status': 'nls_status'}), '({}, lin_solver=ls, status=nls_status)\n', (3505, 3543), False, 'from sfepy.solvers.nls import Newton\n'), ((3550, 3586), 'sfepy.discrete.Problem', 'Problem', (['"""elasticity"""'], {'equations': 'eqs'}), "('elasticity', equations=eqs)\n", (3557, 3586), False, 'from sfepy.discrete import FieldVariable, Material, Integral, Function, Equation, Equations, Problem\n'), ((3692, 3707), 'sfepy.base.base.IndexedStruct', 'IndexedStruct', ([], {}), '()\n', (3705, 3707), False, 'from sfepy.base.base import IndexedStruct\n'), ((3908, 3939), 'sfepy.postprocess.viewer.Viewer', 'Viewer', (['"""linear_elasticity.vtk"""'], {}), "('linear_elasticity.vtk')\n", (3914, 3939), False, 'from sfepy.postprocess.viewer import Viewer\n'), ((2650, 2697), 'sfepy.mechanics.matcoefs.stiffness_from_lame', 'stiffness_from_lame', ([], {'dim': '(3)', 'lam': '(5.769)', 'mu': '(3.846)'}), '(dim=3, lam=5.769, mu=3.846)\n', (2669, 2697), False, 'from sfepy.mechanics.matcoefs import stiffness_from_lame\n'), ((3641, 3660), 'sfepy.discrete.conditions.Conditions', 'Conditions', (['[fix_u]'], {}), '([fix_u])\n', (3651, 3660), False, 'from sfepy.discrete.conditions import Conditions, EssentialBC\n')] |
"""
Classes holding information on global DOFs and mapping of all DOFs -
equations (active DOFs).
Helper functions for the equation mapping.
"""
import numpy as nm
import scipy.sparse as sp
from sfepy.base.base import assert_, Struct, basestr
from sfepy.discrete.functions import Function
from sfepy.discrete.conditions import get_condition_value, EssentialBC, \
PeriodicBC, DGPeriodicBC, DGEssentialBC
def expand_nodes_to_dofs(nods, n_dof_per_node):
"""
Expand DOF node indices into DOFs given a constant number of DOFs
per node.
"""
dofs = nm.repeat(nods, n_dof_per_node)
dofs.shape = (nods.shape[0], n_dof_per_node)
idof = nm.arange(n_dof_per_node, dtype=nm.int32)
dofs = n_dof_per_node * dofs + idof
return dofs
def expand_nodes_to_equations(nods, dof_names, all_dof_names):
"""
Expand vector of node indices to equations (DOF indices) based on
the DOF-per-node count.
DOF names must be already canonized.
Returns
-------
eq : array
The equations/DOF indices in the node-by-node order.
"""
dpn = len(all_dof_names)
nc = len(dof_names)
eq = nm.empty(len(nods) * nc, dtype=nm.int32)
for ii, dof in enumerate(dof_names):
idof = all_dof_names.index(dof)
eq[ii::nc] = dpn * nods + idof
return eq
def resolve_chains(master_slave, chains):
"""
Resolve EPBC chains - e.g. in corner nodes.
"""
for chain in chains:
slave = chain[-1]
master_slave[chain[:-1]] = slave + 1
master_slave[slave] = - chain[0] - 1 # Any of masters...
def group_chains(chain_list):
"""
Group EPBC chains.
"""
chains = []
while len(chain_list):
chain = set(chain_list.pop(0))
## print ':', chain
ii = 0
while ii < len(chain_list):
c1 = sorted(chain_list[ii])
## print '--', ii, c1, chain
is0 = c1[0] in chain
is1 = c1[1] in chain
if is0 and is1:
chain_list.pop(ii)
elif is0 or is1:
chain.update(c1)
chain_list.pop(ii)
ii = 0
else:
ii += 1
## print ii, chain, chain_list
## print '->', chain
## print chain_list
chains.append(list(chain))
## print 'EPBC chain groups:', chains
aux = {}
for chain in chains:
aux.setdefault(len(chain), [0])[0] += 1
## print 'EPBC chain counts:', aux
return chains
class DofInfo(Struct):
"""
Global DOF information, i.e. ordering of DOFs of the state (unknown)
variables in the global state vector.
"""
def __init__(self, name):
Struct.__init__(self, name=name)
self.n_var = 0
self.var_names = []
self.n_dof = {}
self.ptr = [0]
self.indx = {}
self.details = {}
def _update_after_append(self, name):
self.ptr.append(self.ptr[-1] + self.n_dof[name])
ii = self.n_var
self.indx[name] = slice(int(self.ptr[ii]), int(self.ptr[ii+1]))
self.n_var += 1
def append_variable(self, var, active=False):
"""
Append DOFs of the given variable.
Parameters
----------
var : Variable instance
The variable to append.
active : bool, optional
When True, only active (non-constrained) DOFs are considered.
"""
name = var.name
if name in self.var_names:
raise ValueError('variable %s already present!' % name)
self.var_names.append(name)
self.n_dof[name], self.details[name] = var.get_dof_info(active=active)
self._update_after_append(name)
def append_raw(self, name, n_dof):
"""
Append raw DOFs.
Parameters
----------
name : str
The name of variable the DOFs correspond to.
n_dof : int
The number of DOFs.
"""
if name in self.var_names:
raise ValueError('variable %s already present!' % name)
self.var_names.append(name)
self.n_dof[name], self.details[name] = n_dof, None
self._update_after_append(name)
def update(self, name, n_dof):
"""
Set the number of DOFs of the given variable.
Parameters
----------
name : str
The name of variable the DOFs correspond to.
n_dof : int
The number of DOFs.
"""
if not name in self.var_names:
raise ValueError('variable %s is not present!' % name)
ii = self.var_names.index(name)
delta = n_dof - self.n_dof[name]
self.n_dof[name] = n_dof
for iv, nn in enumerate(self.var_names[ii:]):
self.ptr[ii+iv+1] += delta
self.indx[nn] = slice(self.ptr[ii+iv], self.ptr[ii+iv+1])
def get_info(self, var_name):
"""
Return information on DOFs of the given variable.
Parameters
----------
var_name : str
The name of the variable.
"""
return Struct(name='%s_dof_info' % var_name,
var_name=var_name,
n_dof=self.n_dof[var_name],
indx=self.indx[var_name],
details=self.details[var_name])
def get_subset_info(self, var_names):
"""
Return global DOF information for selected variables
only. Silently ignores non-existing variable names.
Parameters
----------
var_names : list
The names of the selected variables.
"""
di = DofInfo(self.name + ':subset')
for var_name in var_names:
if var_name not in self.var_names:
continue
di.append_raw(var_name, self.n_dof[var_name])
return di
def get_n_dof_total(self):
"""
Return the total number of DOFs of all state variables.
"""
return self.ptr[-1]
def is_active_bc(bc, ts=None, functions=None):
"""
Check whether the given boundary condition is active in the current
time.
Returns
-------
active : bool
True if the condition `bc` is active.
"""
if (bc.times is None) or (ts is None):
active = True
elif isinstance(bc.times, list):
for tt in bc.times:
if tt[0] <= ts.time < tt[1]:
active = True
break
else:
active = False
else:
if isinstance(bc.times, basestr):
if functions is not None:
fun = functions[bc.times]
else:
raise ValueError('no functions given for bc %s!' % bc.name)
elif isinstance(bc.times, Function):
fun = bc.times
else:
raise ValueError('unknown times type! (%s)'
% type(bc.times))
active = fun(ts)
return active
class EquationMap(Struct):
"""
Map all DOFs to equations for active DOFs.
"""
def __init__(self, name, dof_names, var_di):
Struct.__init__(self, name=name, dof_names=dof_names, var_di=var_di)
self.dpn = len(self.dof_names)
self.eq = nm.arange(var_di.n_dof, dtype=nm.int32)
self.n_dg_ebc = 0
self.dg_ebc_names = {}
self.dg_ebc = {}
self.dg_ebc_val = {}
self.n_dg_epbc = 0
self.dg_epbc_names = []
self.dg_epbc = []
def _init_empty(self, field):
self.val_ebc = nm.empty((0,), dtype=field.dtype)
if field.get('unused_dofs') is None:
self.eqi = nm.arange(self.var_di.n_dof, dtype=nm.int32)
else:
self._mark_unused(field)
self.eqi = nm.compress(self.eq >= 0, self.eq)
self.eq[self.eqi] = nm.arange(self.eqi.shape[0], dtype=nm.int32)
self.eq_ebc = nm.empty((0,), dtype=nm.int32)
self.master = nm.empty((0,), dtype=nm.int32)
self.slave = nm.empty((0,), dtype=nm.int32)
self.n_eq = self.eqi.shape[0]
self.n_ebc = self.eq_ebc.shape[0]
self.n_epbc = self.master.shape[0]
def _mark_unused(self, field):
unused_dofs = field.get('unused_dofs')
if unused_dofs is not None:
unused = expand_nodes_to_equations(field.unused_dofs,
self.dof_names, self.dof_names)
self.eq[unused] = -3
def map_equations(self, bcs, field, ts, functions, problem=None,
warn=False):
"""
Create the mapping of active DOFs from/to all DOFs.
Parameters
----------
bcs : Conditions instance
The Dirichlet or periodic boundary conditions (single
condition instances). The dof names in the conditions must
already be canonized.
field : Field instance
The field of the variable holding the DOFs.
ts : TimeStepper instance
The time stepper.
functions : Functions instance
The registered functions.
problem : Problem instance, optional
The problem that can be passed to user functions as a context.
warn : bool, optional
If True, warn about BC on non-existent nodes.
Returns
-------
active_bcs : set
The set of boundary conditions active in the current time.
Notes
-----
- Periodic bc: master and slave DOFs must belong to the same
field (variables can differ, though).
"""
if bcs is None:
self._init_empty(field)
return set()
eq_ebc = nm.zeros((self.var_di.n_dof,), dtype=nm.int32)
val_ebc = nm.zeros((self.var_di.n_dof,), dtype=field.dtype)
master_slave = nm.zeros((self.var_di.n_dof,), dtype=nm.int32)
chains = []
active_bcs = set()
for bc in bcs:
# Skip conditions that are not active in the current time.
if not is_active_bc(bc, ts=ts, functions=functions):
continue
active_bcs.add(bc.key)
if isinstance(bc, DGEssentialBC):
ntype = "DGEBC"
region = bc.region
elif isinstance(bc, DGPeriodicBC):
ntype = "DGEPBC"
region = bc.regions[0]
elif isinstance(bc, EssentialBC):
ntype = 'EBC'
region = bc.region
elif isinstance(bc, PeriodicBC):
ntype = 'EPBC'
region = bc.regions[0]
if warn:
clean_msg = ('warning: ignoring nonexistent %s node (%s) in '
% (ntype, self.var_di.var_name))
else:
clean_msg = None
# Get master region nodes.
master_nod_list = field.get_dofs_in_region(region)
if len(master_nod_list) == 0:
continue
if ntype == 'EBC': # EBC.
dofs, val = bc.dofs
##
# Evaluate EBC values.
fun = get_condition_value(val, functions, 'EBC', bc.name)
if isinstance(fun, Function):
aux = fun
fun = lambda coors: aux(ts, coors,
bc=bc, problem=problem)
nods, vv = field.set_dofs(fun, region, len(dofs), clean_msg)
eq = expand_nodes_to_equations(nods, dofs, self.dof_names)
# Duplicates removed here...
eq_ebc[eq] = 1
if vv is not None: val_ebc[eq] = nm.ravel(vv)
elif ntype == "DGEBC":
dofs, val = bc.dofs
##
# Evaluate EBC values.
fun = get_condition_value(val, functions, 'EBC', bc.name)
if isinstance(fun, Function):
aux = fun
fun = lambda coors: aux(ts, coors,
bc=bc, problem=problem)
values = field.get_bc_facet_values(fun, region, diff=bc.diff)
bc2bfi = field.get_bc_facet_idx(region)
self.dg_ebc_val.setdefault(bc.diff, []).append(values)
self.dg_ebc.setdefault(bc.diff, []).append(bc2bfi)
self.n_dg_ebc += 1
elif ntype == "DGEPBC":
# ensure matching boundaries?
master_bc2bfi = field.get_bc_facet_idx(region)
slave_bc2bfi = field.get_bc_facet_idx(bc.regions[1])
self.dg_epbc.append((master_bc2bfi, slave_bc2bfi))
self.n_dg_epbc += 1
else: # EPBC.
region = bc.regions[1]
slave_nod_list = field.get_dofs_in_region(region)
nmaster = nm.unique(master_nod_list)
# Treat fields not covering the whole domain.
if nmaster[0] == -1:
nmaster = nmaster[1:]
nslave = nm.unique(slave_nod_list)
# Treat fields not covering the whole domain.
if nslave[0] == -1:
nslave = nslave[1:]
## print nmaster + 1
## print nslave + 1
if nmaster.shape != nslave.shape:
msg = 'EPBC list lengths do not match!\n(%s,\n %s)' %\
(nmaster, nslave)
raise ValueError(msg)
if (nmaster.shape[0] == 0) and (nslave.shape[0] == 0):
continue
mcoor = field.get_coor(nmaster)
scoor = field.get_coor(nslave)
fun = get_condition_value(bc.match, functions, 'EPBC', bc.name)
if isinstance(fun, Function):
i1, i2 = fun(mcoor, scoor)
else:
i1, i2 = fun
## print nm.c_[mcoor[i1], scoor[i2]]
## print nm.c_[nmaster[i1], nslave[i2]] + 1
meq = expand_nodes_to_equations(nmaster[i1], bc.dofs[0],
self.dof_names)
seq = expand_nodes_to_equations(nslave[i2], bc.dofs[1],
self.dof_names)
m_assigned = nm.where(master_slave[meq] != 0)[0]
s_assigned = nm.where(master_slave[seq] != 0)[0]
if m_assigned.size or s_assigned.size: # Chain EPBC.
aux = master_slave[meq[m_assigned]]
sgn = nm.sign(aux)
om_chain = zip(meq[m_assigned], (aux - sgn) * sgn)
chains.extend(om_chain)
aux = master_slave[seq[s_assigned]]
sgn = nm.sign(aux)
os_chain = zip(seq[s_assigned], (aux - sgn) * sgn)
chains.extend(os_chain)
m_chain = zip(meq[m_assigned], seq[m_assigned])
chains.extend(m_chain)
msd = nm.setdiff1d(s_assigned, m_assigned)
s_chain = zip(meq[msd], seq[msd])
chains.extend(s_chain)
msa = nm.union1d(m_assigned, s_assigned)
ii = nm.setdiff1d(nm.arange(meq.size), msa)
master_slave[meq[ii]] = seq[ii] + 1
master_slave[seq[ii]] = - meq[ii] - 1
else:
master_slave[meq] = seq + 1
master_slave[seq] = - meq - 1
chains = group_chains(chains)
resolve_chains(master_slave, chains)
self.master = nm.nonzero(master_slave > 0)[0]
self.slave = master_slave[self.master] - 1
# Propagate EBCs via PBCs.
mask = eq_ebc[self.master] > 0
im0 = self.master[mask]
im1 = self.slave[mask]
mask = eq_ebc[self.slave] > 0
is0 = self.slave[mask]
is1 = self.master[mask]
val_ebc[im1] = val_ebc[im0]
eq_ebc[im1] = eq_ebc[im0]
val_ebc[is1] = val_ebc[is0]
eq_ebc[is1] = eq_ebc[is0]
self.eq_ebc = nm.nonzero(eq_ebc > 0)[0]
self.val_ebc = val_ebc[self.eq_ebc]
assert_((self.eq_ebc.shape == self.val_ebc.shape))
self.eq[self.eq_ebc] = -2
self.eq[self.master] = -1
self._mark_unused(field)
self.eqi = self.eq[self.eq >= 0]
self.eq[self.eqi] = nm.arange(self.eqi.shape[0], dtype=nm.int32)
self.eq[self.master] = self.eq[self.slave]
self.n_eq = self.eqi.shape[0]
self.n_ebc = self.eq_ebc.shape[0]
self.n_epbc = self.master.shape[0]
return active_bcs
def get_operator(self):
"""
Get the matrix operator :math:`R` corresponding to the equation
mapping, such that the restricted matrix :math:`A_r` can be
obtained from the full matrix :math:`A` by :math:`A_r = R^T A
R`. All the matrices are w.r.t. a single variables that uses
this mapping.
Returns
-------
mtx : coo_matrix
The matrix :math:`R`.
"""
# EBC.
rows = self.eqi
cols = nm.arange(self.n_eq, dtype=nm.int32)
# EPBC.
ic = self.eq[self.slave]
ii = ic >= 0
rows = nm.r_[rows, self.master[ii]]
cols = nm.r_[cols, ic[ii]]
ones = nm.ones(rows.shape[0], dtype=nm.float64)
mtx = sp.coo_matrix((ones, (rows, cols)),
shape=(self.eq.shape[0], self.n_eq))
return mtx
| [
"sfepy.base.base.Struct",
"sfepy.discrete.conditions.get_condition_value",
"sfepy.base.base.Struct.__init__",
"sfepy.base.base.assert_"
] | [((570, 601), 'numpy.repeat', 'nm.repeat', (['nods', 'n_dof_per_node'], {}), '(nods, n_dof_per_node)\n', (579, 601), True, 'import numpy as nm\n'), ((663, 704), 'numpy.arange', 'nm.arange', (['n_dof_per_node'], {'dtype': 'nm.int32'}), '(n_dof_per_node, dtype=nm.int32)\n', (672, 704), True, 'import numpy as nm\n'), ((2711, 2743), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'name': 'name'}), '(self, name=name)\n', (2726, 2743), False, 'from sfepy.base.base import assert_, Struct, basestr\n'), ((5124, 5271), 'sfepy.base.base.Struct', 'Struct', ([], {'name': "('%s_dof_info' % var_name)", 'var_name': 'var_name', 'n_dof': 'self.n_dof[var_name]', 'indx': 'self.indx[var_name]', 'details': 'self.details[var_name]'}), "(name='%s_dof_info' % var_name, var_name=var_name, n_dof=self.n_dof[\n var_name], indx=self.indx[var_name], details=self.details[var_name])\n", (5130, 5271), False, 'from sfepy.base.base import assert_, Struct, basestr\n'), ((7147, 7215), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'name': 'name', 'dof_names': 'dof_names', 'var_di': 'var_di'}), '(self, name=name, dof_names=dof_names, var_di=var_di)\n', (7162, 7215), False, 'from sfepy.base.base import assert_, Struct, basestr\n'), ((7274, 7313), 'numpy.arange', 'nm.arange', (['var_di.n_dof'], {'dtype': 'nm.int32'}), '(var_di.n_dof, dtype=nm.int32)\n', (7283, 7313), True, 'import numpy as nm\n'), ((7570, 7603), 'numpy.empty', 'nm.empty', (['(0,)'], {'dtype': 'field.dtype'}), '((0,), dtype=field.dtype)\n', (7578, 7603), True, 'import numpy as nm\n'), ((7928, 7958), 'numpy.empty', 'nm.empty', (['(0,)'], {'dtype': 'nm.int32'}), '((0,), dtype=nm.int32)\n', (7936, 7958), True, 'import numpy as nm\n'), ((7982, 8012), 'numpy.empty', 'nm.empty', (['(0,)'], {'dtype': 'nm.int32'}), '((0,), dtype=nm.int32)\n', (7990, 8012), True, 'import numpy as nm\n'), ((8034, 8064), 'numpy.empty', 'nm.empty', (['(0,)'], {'dtype': 'nm.int32'}), '((0,), dtype=nm.int32)\n', (8042, 8064), True, 'import numpy as nm\n'), ((9733, 9779), 'numpy.zeros', 'nm.zeros', (['(self.var_di.n_dof,)'], {'dtype': 'nm.int32'}), '((self.var_di.n_dof,), dtype=nm.int32)\n', (9741, 9779), True, 'import numpy as nm\n'), ((9798, 9847), 'numpy.zeros', 'nm.zeros', (['(self.var_di.n_dof,)'], {'dtype': 'field.dtype'}), '((self.var_di.n_dof,), dtype=field.dtype)\n', (9806, 9847), True, 'import numpy as nm\n'), ((9871, 9917), 'numpy.zeros', 'nm.zeros', (['(self.var_di.n_dof,)'], {'dtype': 'nm.int32'}), '((self.var_di.n_dof,), dtype=nm.int32)\n', (9879, 9917), True, 'import numpy as nm\n'), ((16298, 16346), 'sfepy.base.base.assert_', 'assert_', (['(self.eq_ebc.shape == self.val_ebc.shape)'], {}), '(self.eq_ebc.shape == self.val_ebc.shape)\n', (16305, 16346), False, 'from sfepy.base.base import assert_, Struct, basestr\n'), ((16522, 16566), 'numpy.arange', 'nm.arange', (['self.eqi.shape[0]'], {'dtype': 'nm.int32'}), '(self.eqi.shape[0], dtype=nm.int32)\n', (16531, 16566), True, 'import numpy as nm\n'), ((17268, 17304), 'numpy.arange', 'nm.arange', (['self.n_eq'], {'dtype': 'nm.int32'}), '(self.n_eq, dtype=nm.int32)\n', (17277, 17304), True, 'import numpy as nm\n'), ((17471, 17511), 'numpy.ones', 'nm.ones', (['rows.shape[0]'], {'dtype': 'nm.float64'}), '(rows.shape[0], dtype=nm.float64)\n', (17478, 17511), True, 'import numpy as nm\n'), ((17526, 17598), 'scipy.sparse.coo_matrix', 'sp.coo_matrix', (['(ones, (rows, cols))'], {'shape': '(self.eq.shape[0], self.n_eq)'}), '((ones, (rows, cols)), shape=(self.eq.shape[0], self.n_eq))\n', (17539, 17598), True, 'import scipy.sparse as sp\n'), ((7673, 7717), 'numpy.arange', 'nm.arange', (['self.var_di.n_dof'], {'dtype': 'nm.int32'}), '(self.var_di.n_dof, dtype=nm.int32)\n', (7682, 7717), True, 'import numpy as nm\n'), ((7793, 7827), 'numpy.compress', 'nm.compress', (['(self.eq >= 0)', 'self.eq'], {}), '(self.eq >= 0, self.eq)\n', (7804, 7827), True, 'import numpy as nm\n'), ((7860, 7904), 'numpy.arange', 'nm.arange', (['self.eqi.shape[0]'], {'dtype': 'nm.int32'}), '(self.eqi.shape[0], dtype=nm.int32)\n', (7869, 7904), True, 'import numpy as nm\n'), ((15735, 15763), 'numpy.nonzero', 'nm.nonzero', (['(master_slave > 0)'], {}), '(master_slave > 0)\n', (15745, 15763), True, 'import numpy as nm\n'), ((16220, 16242), 'numpy.nonzero', 'nm.nonzero', (['(eq_ebc > 0)'], {}), '(eq_ebc > 0)\n', (16230, 16242), True, 'import numpy as nm\n'), ((11182, 11233), 'sfepy.discrete.conditions.get_condition_value', 'get_condition_value', (['val', 'functions', '"""EBC"""', 'bc.name'], {}), "(val, functions, 'EBC', bc.name)\n", (11201, 11233), False, 'from sfepy.discrete.conditions import get_condition_value, EssentialBC, PeriodicBC, DGPeriodicBC, DGEssentialBC\n'), ((11712, 11724), 'numpy.ravel', 'nm.ravel', (['vv'], {}), '(vv)\n', (11720, 11724), True, 'import numpy as nm\n'), ((11877, 11928), 'sfepy.discrete.conditions.get_condition_value', 'get_condition_value', (['val', 'functions', '"""EBC"""', 'bc.name'], {}), "(val, functions, 'EBC', bc.name)\n", (11896, 11928), False, 'from sfepy.discrete.conditions import get_condition_value, EssentialBC, PeriodicBC, DGPeriodicBC, DGEssentialBC\n'), ((12915, 12941), 'numpy.unique', 'nm.unique', (['master_nod_list'], {}), '(master_nod_list)\n', (12924, 12941), True, 'import numpy as nm\n'), ((13109, 13134), 'numpy.unique', 'nm.unique', (['slave_nod_list'], {}), '(slave_nod_list)\n', (13118, 13134), True, 'import numpy as nm\n'), ((13778, 13835), 'sfepy.discrete.conditions.get_condition_value', 'get_condition_value', (['bc.match', 'functions', '"""EPBC"""', 'bc.name'], {}), "(bc.match, functions, 'EPBC', bc.name)\n", (13797, 13835), False, 'from sfepy.discrete.conditions import get_condition_value, EssentialBC, PeriodicBC, DGPeriodicBC, DGEssentialBC\n'), ((14403, 14435), 'numpy.where', 'nm.where', (['(master_slave[meq] != 0)'], {}), '(master_slave[meq] != 0)\n', (14411, 14435), True, 'import numpy as nm\n'), ((14468, 14500), 'numpy.where', 'nm.where', (['(master_slave[seq] != 0)'], {}), '(master_slave[seq] != 0)\n', (14476, 14500), True, 'import numpy as nm\n'), ((14655, 14667), 'numpy.sign', 'nm.sign', (['aux'], {}), '(aux)\n', (14662, 14667), True, 'import numpy as nm\n'), ((14866, 14878), 'numpy.sign', 'nm.sign', (['aux'], {}), '(aux)\n', (14873, 14878), True, 'import numpy as nm\n'), ((15133, 15169), 'numpy.setdiff1d', 'nm.setdiff1d', (['s_assigned', 'm_assigned'], {}), '(s_assigned, m_assigned)\n', (15145, 15169), True, 'import numpy as nm\n'), ((15294, 15328), 'numpy.union1d', 'nm.union1d', (['m_assigned', 's_assigned'], {}), '(m_assigned, s_assigned)\n', (15304, 15328), True, 'import numpy as nm\n'), ((15367, 15386), 'numpy.arange', 'nm.arange', (['meq.size'], {}), '(meq.size)\n', (15376, 15386), True, 'import numpy as nm\n')] |
"""
Reference-physical domain mappings.
"""
import numpy as nm
from sfepy.base.base import Struct
class PhysicalQPs(Struct):
"""
Physical quadrature points in a region.
"""
def __init__(self, igs, n_total=0, is_uniform=True):
Struct.__init__(self, igs=igs, n_total=n_total, indx={}, rindx={},
n_per_group={}, shape={}, values={},
is_uniform=is_uniform)
for ig in self.igs:
self.indx[ig] = slice(None)
self.rindx[ig] = slice(None)
self.n_per_group[ig] = 0
self.shape[ig] = (0, 0, 0)
self.values[ig] = nm.empty(self.shape[ig], dtype=nm.float64)
def get_merged_values(self):
qps = nm.concatenate([self.values[ig] for ig in self.igs], axis=0)
return qps
def get_shape(self, rshape, ig=None):
"""
Get shape from raveled shape.
"""
if ig is None:
if self.is_uniform:
n_qp = self.shape[self.igs[0]][1]
else:
msg = 'ig argument must be given for non-uniform QPs!'
raise ValueError(msg)
else:
n_qp = self.shape[ig][1]
if (rshape[0] / n_qp) * n_qp != rshape[0]:
raise ValueError('incompatible shapes! (n_qp: %d, %s)'
% (n_qp, rshape))
shape = (rshape[0] / n_qp, n_qp) + rshape[1:]
return shape
class Mapping(Struct):
"""
Base class for mappings.
"""
@staticmethod
def from_args(region, kind='v', ig=None):
"""
Create mapping from reference to physical entities in a given
region, given the integration kind ('v' or 's').
This mapping can be used to compute the physical quadrature
points.
Parameters
----------
region : Region instance
The region defining the entities.
kind : 'v' or 's'
The kind of the entities: 'v' - cells, 's' - facets.
ig : int, optional
The group index.
Returns
-------
mapping : VolumeMapping or SurfaceMapping instance
The requested mapping.
"""
from sfepy.discrete.fem.domain import FEDomain
from sfepy.discrete.iga.domain import IGDomain
if isinstance(region.domain, FEDomain):
import sfepy.discrete.fem.mappings as mm
coors = region.domain.get_mesh_coors()
if kind == 's':
coors = coors[region.vertices]
gel = region.domain.groups[ig].gel
conn = region.domain.groups[ig].conn
if kind == 'v':
cells = region.get_cells(ig)
mapping = mm.VolumeMapping(coors, conn[cells], gel=gel)
elif kind == 's':
from sfepy.discrete.fem.fe_surface import FESurface
aux = FESurface('aux', region, gel.get_surface_entities(),
conn , ig)
mapping = mm.SurfaceMapping(coors, aux.leconn,
gel=gel.surface_facet)
elif isinstance(region.domain, IGDomain):
import sfepy.discrete.iga.mappings as mm
mapping = mm.IGMapping(region.domain, region.cells)
else:
raise ValueError('unknown domain class! (%s)' % type(region.domain))
return mapping
def get_physical_qps(region, integral, map_kind=None):
"""
Get physical quadrature points corresponding to the given region
and integral.
"""
phys_qps = PhysicalQPs(region.igs)
if map_kind is None:
map_kind = 'v' if region.can_cells else 's'
ii = 0
for ig in region.igs:
gmap = Mapping.from_args(region, map_kind, ig)
gel = gmap.get_geometry()
qp_coors, _ = integral.get_qp(gel.name)
qps = gmap.get_physical_qps(qp_coors)
n_el, n_qp = qps.shape[0], qps.shape[1]
phys_qps.n_per_group[ig] = n_per_group = n_el * n_qp
phys_qps.shape[ig] = qps.shape
phys_qps.indx[ig] = slice(ii, ii + n_el)
phys_qps.rindx[ig] = slice(ii * n_qp, (ii + n_el) * n_qp)
ii += qps.shape[0]
qps.shape = (n_per_group, qps.shape[2])
phys_qps.values[ig] = qps
phys_qps.n_total += n_el * n_qp
return phys_qps
def get_mapping_data(name, field, integral, region=None, integration='volume'):
"""
General helper function for accessing reference mapping data.
Get data attribute `name` from reference mapping corresponding to
`field` in `region` in quadrature points of the given `integral` and
`integration` type.
Parameters
----------
name : str
The reference mapping attribute name.
field : Field instance
The field defining the reference mapping.
integral : Integral instance
The integral defining quadrature points.
region : Region instance, optional
If given, use the given region instead of `field` region.
integration : one of ('volume', 'surface', 'surface_extra')
The integration type.
Returns
-------
data : array
The required data merged for all element groups.
Notes
-----
Assumes the same element geometry in all element groups of the field!
"""
data = None
if region is None:
region = field.region
for ig in region.igs:
geo, _ = field.get_mapping(ig, region, integral, integration)
_data = getattr(geo, name)
if data is None:
data = _data
else:
data = nm.concatenate((data, _data), axis=0)
return data
def get_jacobian(field, integral, region=None, integration='volume'):
"""
Get the jacobian of reference mapping corresponding to `field`.
Parameters
----------
field : Field instance
The field defining the reference mapping.
integral : Integral instance
The integral defining quadrature points.
region : Region instance, optional
If given, use the given region instead of `field` region.
integration : one of ('volume', 'surface', 'surface_extra')
The integration type.
Returns
-------
jac : array
The jacobian merged for all element groups.
See Also
--------
get_mapping_data()
Notes
-----
Assumes the same element geometry in all element groups of the field!
"""
jac = get_mapping_data('det', field, integral, region=region,
integration=integration)
return jac
def get_normals(field, integral, region):
"""
Get the normals of element faces in `region`.
Parameters
----------
field : Field instance
The field defining the reference mapping.
integral : Integral instance
The integral defining quadrature points.
region : Region instance
The given of the element faces.
Returns
-------
normals : array
The normals merged for all element groups.
See Also
--------
get_mapping_data()
Notes
-----
Assumes the same element geometry in all element groups of the field!
"""
normals = get_mapping_data('normal', field, integral, region=region,
integration='surface')
return normals
| [
"sfepy.discrete.iga.mappings.SurfaceMapping",
"sfepy.discrete.iga.mappings.VolumeMapping",
"sfepy.discrete.iga.mappings.IGMapping",
"sfepy.base.base.Struct.__init__"
] | [((253, 383), 'sfepy.base.base.Struct.__init__', 'Struct.__init__', (['self'], {'igs': 'igs', 'n_total': 'n_total', 'indx': '{}', 'rindx': '{}', 'n_per_group': '{}', 'shape': '{}', 'values': '{}', 'is_uniform': 'is_uniform'}), '(self, igs=igs, n_total=n_total, indx={}, rindx={},\n n_per_group={}, shape={}, values={}, is_uniform=is_uniform)\n', (268, 383), False, 'from sfepy.base.base import Struct\n'), ((734, 794), 'numpy.concatenate', 'nm.concatenate', (['[self.values[ig] for ig in self.igs]'], {'axis': '(0)'}), '([self.values[ig] for ig in self.igs], axis=0)\n', (748, 794), True, 'import numpy as nm\n'), ((643, 685), 'numpy.empty', 'nm.empty', (['self.shape[ig]'], {'dtype': 'nm.float64'}), '(self.shape[ig], dtype=nm.float64)\n', (651, 685), True, 'import numpy as nm\n'), ((5623, 5660), 'numpy.concatenate', 'nm.concatenate', (['(data, _data)'], {'axis': '(0)'}), '((data, _data), axis=0)\n', (5637, 5660), True, 'import numpy as nm\n'), ((2746, 2791), 'sfepy.discrete.iga.mappings.VolumeMapping', 'mm.VolumeMapping', (['coors', 'conn[cells]'], {'gel': 'gel'}), '(coors, conn[cells], gel=gel)\n', (2762, 2791), True, 'import sfepy.discrete.iga.mappings as mm\n'), ((3266, 3307), 'sfepy.discrete.iga.mappings.IGMapping', 'mm.IGMapping', (['region.domain', 'region.cells'], {}), '(region.domain, region.cells)\n', (3278, 3307), True, 'import sfepy.discrete.iga.mappings as mm\n'), ((3036, 3095), 'sfepy.discrete.iga.mappings.SurfaceMapping', 'mm.SurfaceMapping', (['coors', 'aux.leconn'], {'gel': 'gel.surface_facet'}), '(coors, aux.leconn, gel=gel.surface_facet)\n', (3053, 3095), True, 'import sfepy.discrete.iga.mappings as mm\n')] |
# This example implements 2nd-level homogenization 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 calculation of homogenized coefficients:
#
# ./homogen.py example_perfusion_BDB/perf_BDB_mes.py
#
# The results are stored in `example_perfusion_BDB/results/meso` directory.
#
import numpy as nm
from sfepy import data_dir
import os.path as osp
from sfepy.discrete.fem.mesh import Mesh
import sfepy.discrete.fem.periodic as per
from sfepy.mechanics.tensors import dim2sym
from sfepy.homogenization.utils import define_box_regions
import sfepy.homogenization.coefs_base as cb
from sfepy.homogenization.micmac import get_homog_coefs_linear
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
def get_periodic_bc(var_tab, dim=3, dim_tab=None):
if dim_tab is None:
dim_tab = {'x': ['left', 'right'],
'z': ['bottom', 'top'],
'y': ['near', 'far']}
periodic = {}
epbcs = {}
for ivar, reg in var_tab:
periodic['per_%s' % ivar] = pers = []
for idim in 'xyz'[0:dim]:
key = 'per_%s_%s' % (ivar, idim)
regs = ['%s_%s' % (reg, ii) for ii in dim_tab[idim]]
epbcs[key] = (regs, {'%s.all' % ivar: '%s.all' % ivar},
'match_%s_plane' % idim)
pers.append(key)
return epbcs, periodic
# get homogenized coefficients, recalculate them if necessary
def get_homog(coors, mode, pb,micro_filename, **kwargs):
if not (mode == 'qp'):
return
nqp = coors.shape[0]
coefs_filename = 'coefs_micro'
coefs_filename = osp.join(pb.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]
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
def define(filename_mesh=None):
eta = 3.6e-3
if filename_mesh is None:
filename_mesh = osp.join(data_dir, 'meso_perf_puc.vtk')
mesh = Mesh.from_file(filename_mesh)
poroela_micro_file = osp.join(data_dir, 'perf_BDB_mic.py')
dim = 3
sym = (dim + 1) * dim // 2
sym_eye = 'nm.array([1,1,0])' if dim == 2 else 'nm.array([1,1,1,0,0,0])'
bbox = mesh.get_bounding_box()
regions = define_box_regions(mesh.dim, bbox[0], bbox[1], eps=1e-3)
regions.update({
'Z': 'all',
'Gamma_Z': ('vertices of surface', 'facet'),
# matrix
'Zm': 'cells of group 1',
'Zm_left': ('r.Zm *v r.Left', 'vertex'),
'Zm_right': ('r.Zm *v r.Right', 'vertex'),
'Zm_bottom': ('r.Zm *v r.Bottom', 'vertex'),
'Zm_top': ('r.Zm *v r.Top', 'vertex'),
'Gamma_Zm': ('r.Zm *v r.Zc', 'facet', 'Zm'),
# canal
'Zc': 'cells of group 2',
'Zc0': ('r.Zc -v r.Gamma_Zc', 'vertex'),
'Zc_left': ('r.Zc0 *v r.Left', 'vertex'),
'Zc_right': ('r.Zc0 *v r.Right', 'vertex'),
'Zc_bottom': ('r.Zc0 *v r.Bottom', 'vertex'),
'Zc_top': ('r.Zc0 *v r.Top', 'vertex'),
'Gamma_Zc': ('r.Zm *v r.Zc', 'facet', 'Zc'),
"Surface": ("vertices of surface", "facet"),
'Center_c': ('vertex 5346', 'vertex'), # canal center
})
if dim == 3:
regions.update({
'Zm_far': ('r.Zm *v r.Far', 'vertex'),
'Zm_near': ('r.Zm *v r.Near', 'vertex'),
'Zc_far': ('r.Zc0 *v r.Far', 'vertex'),
'Zc_near': ('r.Zc0 *v r.Near', 'vertex'),
})
fields = {
'one': ('real', 'scalar', 'Z', 1),
'displacement': ('real', 'vector', 'Zm', 1),
'pressure_m': ('real', 'scalar', 'Zm', 1),
'pressure_c': ('real', 'scalar', 'Zc', 1),
'displacement_c': ('real', 'vector', 'Zc', 1),
'velocity': ('real', 'vector', 'Zc', 2),
}
variables = {
# displacement
'u': ('unknown field', 'displacement', 0),
'v': ('test field', 'displacement', 'u'),
'Pi_u': ('parameter field', 'displacement', 'u'),
'U1': ('parameter field', 'displacement', '(set-to-None)'),
'U2': ('parameter field', 'displacement', '(set-to-None)'),
'uc': ('unknown field', 'displacement_c', 4),
'vc': ('test field', 'displacement_c', 'uc'),
# velocity
'w': ('unknown field', 'velocity', 1),
'z': ('test field', 'velocity', 'w'),
'Pi_w': ('parameter field', 'velocity', 'w'),
'W1': ('parameter field', 'velocity', '(set-to-None)'),
'W2': ('parameter field', 'velocity', '(set-to-None)'),
# pressure
'pm': ('unknown field', 'pressure_m', 2),
'qm': ('test field', 'pressure_m', 'pm'),
'Pm1': ('parameter field', 'pressure_m', '(set-to-None)'),
'Pm2': ('parameter field', 'pressure_m', '(set-to-None)'),
'Pi_pm': ('parameter field', 'pressure_m', 'pm'),
'pc': ('unknown field', 'pressure_c', 3),
'qc': ('test field', 'pressure_c', 'pc'),
'Pc1': ('parameter field', 'pressure_c', '(set-to-None)'),
'Pc2': ('parameter field', 'pressure_c', '(set-to-None)'),
# one
'one': ('parameter field', 'one', '(set-to-None)'),
}
functions = {
'match_x_plane': (per.match_x_plane,),
'match_y_plane': (per.match_y_plane,),
'match_z_plane': (per.match_z_plane,),
'get_homog': (lambda ts, coors, mode=None, problem=None, **kwargs:\
get_homog(coors, mode, problem, poroela_micro_file, **kwargs),),
}
materials = {
'hmatrix': 'get_homog',
'fluid': ({
'eta_c': eta* nm.eye(dim2sym(dim)),
},),
'mat': ({
'k1': nm.array([[1, 0, 0]]).T,
'k2': nm.array([[0, 1, 0]]).T,
'k3': nm.array([[0, 0, 1]]).T,
},),
}
ebcs = {
'fixed_u': ('Corners', {'um.all': 0.0}),
'fixed_pm': ('Corners', {'p.0': 0.0}),
'fixed_w': ('Center_c', {'w.all': 0.0}),
}
epbcs, periodic = get_periodic_bc([('u', 'Zm'), ('pm', 'Zm'),
('pc', 'Zc'), ('w', 'Zc')])
all_periodic = periodic['per_w'] + periodic['per_pc']
integrals = {
'i': 4,
}
options = {
'coefs': 'coefs',
'coefs_filename': 'coefs_meso',
'requirements': 'requirements',
'volume': {
'variables': ['u', 'pc'],
'expression': 'd_volume.i.Zm(u) + d_volume.i.Zc(pc)',
},
'output_dir': data_dir + '/results/meso',
'file_per_var': True,
'save_format': 'vtk', # Global setting.
'dump_format': 'h5', # Global setting.
'absolute_mesh_path': True,
'multiprocessing': False,
'ls': 'ls',
'nls': 'ns_m15',
'output_prefix': 'meso:',
}
solvers = {
'ls': ('ls.mumps', {}),
'ls_s': ('ls.schur_mumps',
{'schur_variables': ['pc'],
'fallback': 'ls'}),
'ns': ('nls.newton', {
'i_max': 1,
'eps_a': 1e-14,
'eps_r': 1e-3,
'problem': 'nonlinear'}),
'ns_em15': ('nls.newton', {
'i_max': 1,
'eps_a': 1e-15,
'eps_r': 1e-3,
'problem': 'nonlinear'}),
'ns_em12': ('nls.newton', {
'i_max': 1,
'eps_a': 1e-12,
'eps_r': 1e-3,
'problem': 'nonlinear'}),
'ns_em9': ('nls.newton', {
'i_max': 1,
'eps_a': 1e-9,
'eps_r': 1e-3,
'problem': 'nonlinear'}),
'ns_em6': ('nls.newton', {
'i_max': 1,
'eps_a': 1e-4,
'eps_r': 1e-3,
'problem': 'nonlinear'}),
}
#Definition of homogenized coefficients, see (33)-(35)
coefs = {
'A': {
'requires': ['pis_u', 'corrs_omega_ij'],
'expression': 'dw_lin_elastic.i.Zm(hmatrix.A, U1, U2)',
'set_variables': [('U1', ('corrs_omega_ij', 'pis_u'), 'u'),
('U2', ('corrs_omega_ij', 'pis_u'), 'u')],
'class': cb.CoefSymSym,
},
'B_aux1': {
'status': 'auxiliary',
'requires': ['corrs_omega_ij'],
'expression': '- dw_surface_ltr.i.Gamma_Zm(U1)', # !!! -
'set_variables': [('U1', 'corrs_omega_ij', 'u')],
'class': cb.CoefSym,
},
'B_aux2': {
'status': 'auxiliary',
'requires': ['corrs_omega_ij', 'pis_u', 'corr_one'],
'expression': 'dw_biot.i.Zm(hmatrix.B, U1, one)',
'set_variables': [('U1', ('corrs_omega_ij', 'pis_u'), 'u'),
('one', 'corr_one', 'one')],
'class': cb.CoefSym,
},
'B': {
'requires': ['c.B_aux1', 'c.B_aux2', 'c.vol_c'],
'expression': 'c.B_aux1 + c.B_aux2 + c.vol_c* %s' % sym_eye,
'class': cb.CoefEval,
},
'H': {
'requires': ['corrs_phi_k'],
'expression': 'dw_diffusion.i.Zm(hmatrix.K, Pm1, Pm2)',
'set_variables': [('Pm1', 'corrs_phi_k', 'pm'),
('Pm2', 'corrs_phi_k', 'pm')],
'class': cb.CoefDimDim,
},
'K': {
'requires': ['corrs_pi_k', 'pis_pm'],
'expression': 'dw_diffusion.i.Zm(hmatrix.K, Pm1, Pm2)',
'set_variables': [('Pm1', ('corrs_pi_k', 'pis_pm'), 'pm'),
('Pm2', ('corrs_pi_k', 'pis_pm'), 'pm')],
'class': cb.CoefDimDim,
},
'Q': {
'requires': ['corrs_phi_k', 'pis_pm'],
'expression': 'dw_diffusion.i.Zm(hmatrix.K, Pm1, Pm2)',
'set_variables': [('Pm1', 'pis_pm', 'pm'),
('Pm2', 'corrs_phi_k', 'pm')],
'class': cb.CoefDimDim,
},
'P': {
'requires': ['c.Q', 'c.vol'],
'expression': 'c.vol["fraction_Zc"] * nm.eye(%d) - c.Q' % dim,
'class': cb.CoefEval,
},
'PT': {
'requires': ['c.P'],
'expression': 'c.P.T',
'class': cb.CoefEval,
},
'M_aux1': {
'status': 'auxiliary',
'requires': [],
'expression': 'ev_volume_integrate_mat.i.Zm(hmatrix.M, one)',
'set_variables': [],
'class': cb.CoefOne,
},
'M_aux2': {
'status': 'auxiliary',
'requires': ['corrs_omega_p', 'corr_one'],
'expression': 'dw_biot.i.Zm(hmatrix.B, U1, one)',
'set_variables': [('U1', 'corrs_omega_p', 'u'),
('one', 'corr_one', 'one')],
'class': cb.CoefOne,
},
'M_aux3': {
'status': 'auxiliary',
'requires': ['corrs_omega_p'],
'expression': ' dw_surface_ltr.i.Gamma_Zm(U1)',
'set_variables': [('U1', 'corrs_omega_p', 'u')],
'class': cb.CoefOne,
},
'M': {
'requires': ['c.M_aux1', 'c.M_aux2', 'c.M_aux3'],
'expression': 'c.M_aux1 + c.M_aux2 -c.M_aux3 ',
'class': cb.CoefEval,
},
'S': {
'requires': ['corrs_psi_ij', 'pis_w'],
'expression': 'dw_lin_elastic.i.Zc(fluid.eta_c, W1, W2)',
'set_variables': [('W1', ('corrs_psi_ij', 'pis_w'), 'w'),
('W2', ('corrs_psi_ij', 'pis_w'), 'w')],
'class': cb.CoefSymSym,
},
'vol': {
'regions': ['Zm', 'Zc'],
'expression': 'd_volume.i.%s(one)',
'class': cb.VolumeFractions,
},
'surf_vol': {
'regions': ['Zm', 'Zc'],
'expression': 'd_surface.i.%s(one)',
'class': cb.VolumeFractions,
},
'surf_c': {
'requires': ['c.surf_vol'],
'expression': 'c.surf_vol["fraction_Zc"]',
'class': cb.CoefEval,
},
'vol_c': {
'requires': ['c.vol'],
'expression': 'c.vol["fraction_Zc"]',
'class': cb.CoefEval,
},
'filenames': {},
}
#Definition of mesoscopic corrector problems
requirements = {
'corr_one': {
'variable': 'one',
'expression':
"nm.ones((problem.fields['one'].n_vertex_dof, 1), dtype=nm.float64)",
'class': cb.CorrEval,
},
'pis_u': {
'variables': ['u'],
'class': cb.ShapeDimDim,
'save_name': 'corrs_pis_u',
'dump_variables': ['u'],
},
'pis_pm': {
'variables': ['pm'],
'class': cb.ShapeDim,
},
'pis_w': {
'variables': ['w'],
'class': cb.ShapeDimDim,
},
# Corrector problem, see (31)_1
'corrs_omega_ij': {
'requires': ['pis_u'],
'ebcs': ['fixed_u'],
'epbcs': periodic['per_u'],
'is_linear': True,
'equations': {
'balance_of_forces':
"""dw_lin_elastic.i.Zm(hmatrix.A, v, u)
= - dw_lin_elastic.i.Zm(hmatrix.A, v, Pi_u)"""
},
'set_variables': [('Pi_u', 'pis_u', 'u')],
'class': cb.CorrDimDim,
'save_name': 'corrs_omega_ij',
'dump_variables': ['u'],
'solvers': {'ls': 'ls', 'nls': 'ns_em6'},
'is_linear': True,
},
# Corrector problem, see (31)_2
'corrs_omega_p': {
'requires': ['corr_one'],
'ebcs': ['fixed_u'],
'epbcs': periodic['per_u'],
'equations': {
'balance_of_forces':
"""dw_lin_elastic.i.Zm(hmatrix.A, v, u)
= dw_biot.i.Zm(hmatrix.B, v, one)
- dw_surface_ltr.i.Gamma_Zm(v)""",
},
'set_variables': [('one', 'corr_one', 'one')],
'class': cb.CorrOne,
'save_name': 'corrs_omega_p',
'dump_variables': ['u'],
'solvers': {'ls': 'ls', 'nls': 'ns_em9'},
},
# Corrector problem, see (31)_3
'corrs_pi_k': {
'requires': ['pis_pm'],
'ebcs': [], # ['fixed_pm'],
'epbcs': periodic['per_pm'],
'is_linear': True,
'equations': {
'eq':
"""dw_diffusion.i.Zm(hmatrix.K, qm, pm)
= - dw_diffusion.i.Zm(hmatrix.K, qm, Pi_pm)""",
},
'set_variables': [('Pi_pm', 'pis_pm', 'pm')],
'class': cb.CorrDim,
'save_name': 'corrs_pi_k',
'dump_variables': ['pm'],
'solvers': {'ls': 'ls', 'nls': 'ns_em12'},
},
# Corrector problem, see (31)_4
'corrs_phi_k': {
'requires': [],
'ebcs': [],
'epbcs': periodic['per_pm'],
'equations': {
'eq':
"""dw_diffusion.i.Zm(hmatrix.K, qm, pm)
= - dw_surface_ndot.i.Gamma_Zm(mat.k%d, qm)""",
},
'class': cb.CorrEqPar,
'eq_pars': [(ii + 1) for ii in range(dim)],
'save_name': 'corrs_phi_k',
'dump_variables': ['pm'],
'solvers': {'ls': 'ls', 'nls': 'ns_em9'},
},
# Corrector problem, see (32)
'corrs_psi_ij': {
'requires': ['pis_w'],
'ebcs': ['fixed_w'],
'epbcs': periodic['per_w'] + periodic['per_pc'],
'equations': {
'eq1':
"""2*dw_lin_elastic.i.Zc(fluid.eta_c, z, w)
- dw_stokes.i.Zc(z, pc)
= - 2*dw_lin_elastic.i.Zc(fluid.eta_c, z, Pi_w)""",
'eq2':
"""dw_stokes.i.Zc(w, qc)
= - dw_stokes.i.Zc(Pi_w, qc)"""
},
'set_variables': [('Pi_w', 'pis_w', 'w')],
'class': cb.CorrDimDim,
'save_name': 'corrs_psi_ij',
'dump_variables': ['w', 'pc'],
'solvers': {'ls': 'ls', 'nls': 'ns_em15'},
# 'solvers': {'ls': 'ls_s', 'nls': 'ns_em15'},
'is_linear': True,
},
}
return locals() | [
"sfepy.mechanics.tensors.dim2sym",
"sfepy.homogenization.utils.define_box_regions",
"sfepy.homogenization.micmac.get_homog_coefs_linear",
"sfepy.discrete.fem.mesh.Mesh.from_file"
] | [((2373, 2473), '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', (2395, 2473), False, 'from sfepy.homogenization.micmac import get_homog_coefs_linear\n'), ((3096, 3125), 'sfepy.discrete.fem.mesh.Mesh.from_file', 'Mesh.from_file', (['filename_mesh'], {}), '(filename_mesh)\n', (3110, 3125), False, 'from sfepy.discrete.fem.mesh import Mesh\n'), ((3154, 3191), 'os.path.join', 'osp.join', (['data_dir', '"""perf_BDB_mic.py"""'], {}), "(data_dir, 'perf_BDB_mic.py')\n", (3162, 3191), True, 'import os.path as osp\n'), ((3368, 3425), 'sfepy.homogenization.utils.define_box_regions', 'define_box_regions', (['mesh.dim', 'bbox[0]', 'bbox[1]'], {'eps': '(0.001)'}), '(mesh.dim, bbox[0], bbox[1], eps=0.001)\n', (3386, 3425), False, 'from sfepy.homogenization.utils import define_box_regions\n'), ((1305, 1328), 'numpy.tile', 'nm.tile', (['v', '(nqp, 1, 1)'], {}), '(v, (nqp, 1, 1))\n', (1312, 1328), True, 'import numpy as nm\n'), ((3042, 3081), 'os.path.join', 'osp.join', (['data_dir', '"""meso_perf_puc.vtk"""'], {}), "(data_dir, 'meso_perf_puc.vtk')\n", (3050, 3081), True, 'import os.path as osp\n'), ((2863, 2878), 'numpy.array', 'nm.array', (['[[v]]'], {}), '([[v]])\n', (2871, 2878), True, 'import numpy as nm\n'), ((6856, 6877), 'numpy.array', 'nm.array', (['[[1, 0, 0]]'], {}), '([[1, 0, 0]])\n', (6864, 6877), True, 'import numpy as nm\n'), ((6908, 6929), 'numpy.array', 'nm.array', (['[[0, 1, 0]]'], {}), '([[0, 1, 0]])\n', (6916, 6929), True, 'import numpy as nm\n'), ((6960, 6981), 'numpy.array', 'nm.array', (['[[0, 0, 1]]'], {}), '([[0, 0, 1]])\n', (6968, 6981), True, 'import numpy as nm\n'), ((6771, 6783), 'sfepy.mechanics.tensors.dim2sym', 'dim2sym', (['dim'], {}), '(dim)\n', (6778, 6783), False, 'from sfepy.mechanics.tensors import dim2sym\n')] |
import os
import numpy as nm
from sfepy.base.testing import TestCommon
class Test(TestCommon):
@staticmethod
def from_conf(conf, options):
test = Test(conf=conf, options=options)
test.join = lambda x: os.path.join(test.options.out_dir, x)
return test
def test_linearization(self):
from sfepy.base.base import Struct
from sfepy.discrete.fem import Mesh, FEDomain, Field
from sfepy import data_dir
geometries = ['2_3', '2_4', '3_4', '3_8']
approx_orders = [1, 2]
funs = [nm.cos, nm.sin, lambda x: x]
ok = True
for geometry in geometries:
name = os.path.join(data_dir,
'meshes/elements/%s_1.mesh' % geometry)
mesh = Mesh.from_file(name)
domain = FEDomain('', mesh)
domain = domain.refine()
domain.mesh.write(self.join('linearizer-%s-0.mesh' % geometry))
omega = domain.create_region('Omega', 'all')
for approx_order in approx_orders:
for dpn in [1, mesh.dim]:
self.report('geometry: %s, approx. order: %d, dpn: %d' %
(geometry, approx_order, dpn))
field = Field.from_args('fu', nm.float64, dpn, omega,
approx_order=approx_order)
cc = field.get_coor()
dofs = nm.zeros((field.n_nod, dpn), dtype=nm.float64)
for ic in range(dpn):
dofs[:, ic] = funs[ic](3 * (cc[:, 0] * cc[:, 1]))
vmesh, vdofs, level = field.linearize(dofs,
min_level=0,
max_level=3,
eps=1e-2)
if approx_order == 1:
_ok = level == 0
else:
_ok = level > 0
self.report('max. refinement level: %d: %s' % (level, _ok))
ok = ok and _ok
rdofs = nm.zeros((vmesh.n_nod, dpn), dtype=nm.float64)
cc = vmesh.coors
for ic in range(dpn):
rdofs[:, ic] = funs[ic](3 * (cc[:, 0] * cc[:, 1]))
_ok = nm.allclose(rdofs, vdofs, rtol=0.0, atol=0.03)
self.report('interpolation: %s' % _ok)
ok = ok and _ok
out = {
'u' : Struct(name='output_data',
mode='vertex', data=vdofs,
var_name='u', dofs=None)
}
name = self.join('linearizer-%s-%d-%d'
% (geometry, approx_order, dpn))
vmesh.write(name + '.mesh')
vmesh.write(name + '.vtk', out=out)
return ok
| [
"sfepy.base.base.Struct",
"sfepy.discrete.fem.Mesh.from_file",
"sfepy.discrete.fem.Field.from_args",
"sfepy.discrete.fem.FEDomain"
] | [((228, 265), 'os.path.join', 'os.path.join', (['test.options.out_dir', 'x'], {}), '(test.options.out_dir, x)\n', (240, 265), False, 'import os\n'), ((661, 723), 'os.path.join', 'os.path.join', (['data_dir', "('meshes/elements/%s_1.mesh' % geometry)"], {}), "(data_dir, 'meshes/elements/%s_1.mesh' % geometry)\n", (673, 723), False, 'import os\n'), ((775, 795), 'sfepy.discrete.fem.Mesh.from_file', 'Mesh.from_file', (['name'], {}), '(name)\n', (789, 795), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((818, 836), 'sfepy.discrete.fem.FEDomain', 'FEDomain', (['""""""', 'mesh'], {}), "('', mesh)\n", (826, 836), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1268, 1340), 'sfepy.discrete.fem.Field.from_args', 'Field.from_args', (['"""fu"""', 'nm.float64', 'dpn', 'omega'], {'approx_order': 'approx_order'}), "('fu', nm.float64, dpn, omega, approx_order=approx_order)\n", (1283, 1340), False, 'from sfepy.discrete.fem import Mesh, FEDomain, Field\n'), ((1455, 1501), 'numpy.zeros', 'nm.zeros', (['(field.n_nod, dpn)'], {'dtype': 'nm.float64'}), '((field.n_nod, dpn), dtype=nm.float64)\n', (1463, 1501), True, 'import numpy as nm\n'), ((2191, 2237), 'numpy.zeros', 'nm.zeros', (['(vmesh.n_nod, dpn)'], {'dtype': 'nm.float64'}), '((vmesh.n_nod, dpn), dtype=nm.float64)\n', (2199, 2237), True, 'import numpy as nm\n'), ((2419, 2465), 'numpy.allclose', 'nm.allclose', (['rdofs', 'vdofs'], {'rtol': '(0.0)', 'atol': '(0.03)'}), '(rdofs, vdofs, rtol=0.0, atol=0.03)\n', (2430, 2465), True, 'import numpy as nm\n'), ((2620, 2698), 'sfepy.base.base.Struct', 'Struct', ([], {'name': '"""output_data"""', 'mode': '"""vertex"""', 'data': 'vdofs', 'var_name': '"""u"""', 'dofs': 'None'}), "(name='output_data', mode='vertex', data=vdofs, var_name='u', dofs=None)\n", (2626, 2698), False, 'from sfepy.base.base import Struct\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.