prompt
stringlengths
174
59.5k
completion
stringlengths
7
228
api
stringlengths
12
64
#!/usr/bin/env python """ Transient Laplace equation (heat equation) with non-constant initial conditions given by a function, using commands for interactive use. The script allows setting various simulation parameters, namely: - the diffusivity coefficient - the max. initial condition value - temperature field approximation order - uniform mesh refinement The example shows also how to probe the results. In the SfePy top-level directory the following command can be used to get usage information:: python examples/diffusion/time_poisson_interactive.py -h """ 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, Function, Equation, Equations, Problem) from sfepy.discrete.problem import prepare_matrix 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.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.discrete.probes import LineProbe, CircleProbe from sfepy.discrete.projections import project_by_component def gen_probes(problem): """ Define a line probe and a circle probe. """ # Use enough points for higher order approximations. n_point = 1000 p0, p1 = nm.array([0.0, 0.0, 0.0]), nm.array([0.1, 0.0, 0.0]) line = LineProbe(p0, p1, n_point, share_geometry=True) # Workaround current probe code shortcoming. line.set_options(close_limit=0.5) centre = 0.5 * (p0 + p1) normal = [0.0, 1.0, 0.0] r = 0.019 circle = CircleProbe(centre, normal, r, n_point, share_geometry=True) circle.set_options(close_limit=0.0) probes = [line, circle] labels = ['%s -> %s' % (p0, p1), 'circle(%s, %s, %s' % (centre, normal, r)] return probes, labels def probe_results(ax_num, T, dvel, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(T) results['T'] = (pars, vals) pars, vals = probe(dvel) results['dvel'] = (pars, vals) fig = plt.figure(1) ax = plt.subplot(2, 2, 2 * ax_num + 1) ax.cla() pars, vals = results['T'] ax.plot(pars, vals, label=r'$T$', lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('temperature') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) ax = plt.subplot(2, 2, 2 * ax_num + 2) ax.cla() pars, vals = results['dvel'] for ic in range(vals.shape[1]): ax.plot(pars, vals[:, ic], label=r'$w_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('diffusion velocity') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) return fig, results helps = { 'diffusivity' : 'the diffusivity coefficient [default: %(default)s]', 'ic_max' : 'the max. initial condition value [default: %(default)s]', 'order' : 'temperature field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the probing results figure, if --probe is used', } 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('--diffusivity', metavar='float', type=float, action='store', dest='diffusivity', default=1e-5, help=helps['diffusivity']) parser.add_argument('--ic-max', metavar='float', type=float, action='store', dest='ic_max', default=2.0, help=helps['ic_max']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=2, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() assert_((0 < options.order), 'temperature approximation order must be at least 1!') output('using values:') output(' diffusivity:', options.diffusivity) output(' max. IC value:', options.ic_max) output('uniform mesh refinement level:', options.refine) mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.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.00001', 'facet') right = domain.create_region('Right', 'vertices in x > 0.099999', 'facet') field = Field.from_args('fu', nm.float64, 'scalar', omega, approx_order=options.order) T = FieldVariable('T', 'unknown', field, history=1) s = FieldVariable('s', 'test', field, primary_var_name='T') m = Material('m', diffusivity=options.diffusivity * nm.eye(3)) integral = Integral('i', order=2*options.order) t1 = Term.new('dw_diffusion(m.diffusivity, s, T)', integral, omega, m=m, s=s, T=T) t2 = Term.new('dw_volume_dot(s, dT/dt)', integral, omega, s=s, T=T) eq = Equation('balance', t1 + t2) eqs = Equations([eq]) # Boundary conditions. ebc1 = EssentialBC('T1', left, {'T.0' : 2.0}) ebc2 = EssentialBC('T2', right, {'T.0' : -2.0}) # Initial conditions. def get_ic(coors, ic): x, y, z = coors.T return 2 - 40.0 * x + options.ic_max * nm.sin(4 * nm.pi * x / 0.1) ic_fun = Function('ic_fun', get_ic) ic = InitialCondition('ic', omega, {'T.0' : ic_fun}) pb = Problem('heat', equations=eqs) pb.set_bcs(ebcs=Conditions([ebc1, ebc2])) pb.set_ics(Conditions([ic])) state0 = pb.get_initial_state() init_fun, prestep_fun, _poststep_fun = pb.get_tss_functions(state0) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({'is_linear' : True}, lin_solver=ls, status=nls_status) tss = SimpleTimeSteppingSolver({'t0' : 0.0, 't1' : 100.0, 'n_step' : 11}, nls=nls, context=pb, verbose=True) pb.set_solver(tss) if options.probe: # Prepare probe data. probes, labels = gen_probes(pb) ev = pb.evaluate order = 2 * (options.order - 1) gfield = Field.from_args('gu', nm.float64, 'vector', omega, approx_order=options.order - 1) dvel = FieldVariable('dvel', 'parameter', gfield, primary_var_name='(set-to-None)') cfield = Field.from_args('gu', nm.float64, 'scalar', omega, approx_order=options.order - 1) component = FieldVariable('component', 'parameter', cfield, primary_var_name='(set-to-None)') nls_options = {'eps_a' : 1e-16, 'i_max' : 1} suffix = tss.ts.suffix def poststep_fun(ts, vec): _poststep_fun(ts, vec) # Probe the solution. dvel_qp = ev('ev_diffusion_velocity.%d.Omega(m.diffusivity, T)' % order, copy_materials=False, mode='qp') project_by_component(dvel, dvel_qp, component, order, nls_options=nls_options) all_results = [] for ii, probe in enumerate(probes): fig, results = probe_results(ii, T, dvel, probe, labels[ii]) all_results.append(results) plt.tight_layout() fig.savefig('time_poisson_interactive_probe_%s.png' % (suffix % ts.step), bbox_inches='tight') for ii, results in enumerate(all_results): output('probe %d (%s):' % (ii, probes[ii].name)) 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 else: poststep_fun = _poststep_fun pb.time_update(tss.ts) state0.apply_ebc() # This is required if {'is_linear' : True} is passed to Newton. mtx = prepare_matrix(pb, state0) pb.try_presolve(mtx) tss_status = IndexedStruct() tss(state0.get_vec(pb.active_only), init_fun=init_fun, prestep_fun=prestep_fun, poststep_fun=poststep_fun, status=tss_status)
output(tss_status)
sfepy.base.base.output
#!/usr/bin/env python """ Transient Laplace equation (heat equation) with non-constant initial conditions given by a function, using commands for interactive use. The script allows setting various simulation parameters, namely: - the diffusivity coefficient - the max. initial condition value - temperature field approximation order - uniform mesh refinement The example shows also how to probe the results. In the SfePy top-level directory the following command can be used to get usage information:: python examples/diffusion/time_poisson_interactive.py -h """ 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, Function, Equation, Equations, Problem) from sfepy.discrete.problem import prepare_matrix 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.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.discrete.probes import LineProbe, CircleProbe from sfepy.discrete.projections import project_by_component def gen_probes(problem): """ Define a line probe and a circle probe. """ # Use enough points for higher order approximations. n_point = 1000 p0, p1 = nm.array([0.0, 0.0, 0.0]), nm.array([0.1, 0.0, 0.0]) line = LineProbe(p0, p1, n_point, share_geometry=True) # Workaround current probe code shortcoming. line.set_options(close_limit=0.5) centre = 0.5 * (p0 + p1) normal = [0.0, 1.0, 0.0] r = 0.019 circle = CircleProbe(centre, normal, r, n_point, share_geometry=True) circle.set_options(close_limit=0.0) probes = [line, circle] labels = ['%s -> %s' % (p0, p1), 'circle(%s, %s, %s' % (centre, normal, r)] return probes, labels def probe_results(ax_num, T, dvel, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(T) results['T'] = (pars, vals) pars, vals = probe(dvel) results['dvel'] = (pars, vals) fig = plt.figure(1) ax = plt.subplot(2, 2, 2 * ax_num + 1) ax.cla() pars, vals = results['T'] ax.plot(pars, vals, label=r'$T$', lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('temperature') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) ax = plt.subplot(2, 2, 2 * ax_num + 2) ax.cla() pars, vals = results['dvel'] for ic in range(vals.shape[1]): ax.plot(pars, vals[:, ic], label=r'$w_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('diffusion velocity') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) return fig, results helps = { 'diffusivity' : 'the diffusivity coefficient [default: %(default)s]', 'ic_max' : 'the max. initial condition value [default: %(default)s]', 'order' : 'temperature field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the probing results figure, if --probe is used', } 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('--diffusivity', metavar='float', type=float, action='store', dest='diffusivity', default=1e-5, help=helps['diffusivity']) parser.add_argument('--ic-max', metavar='float', type=float, action='store', dest='ic_max', default=2.0, help=helps['ic_max']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=2, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() assert_((0 < options.order), 'temperature approximation order must be at least 1!') output('using values:') output(' diffusivity:', options.diffusivity) output(' max. IC value:', options.ic_max) output('uniform mesh refinement level:', options.refine) mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.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.00001', 'facet') right = domain.create_region('Right', 'vertices in x > 0.099999', 'facet') field = Field.from_args('fu', nm.float64, 'scalar', omega, approx_order=options.order) T = FieldVariable('T', 'unknown', field, history=1) s = FieldVariable('s', 'test', field, primary_var_name='T') m = Material('m', diffusivity=options.diffusivity * nm.eye(3)) integral = Integral('i', order=2*options.order) t1 = Term.new('dw_diffusion(m.diffusivity, s, T)', integral, omega, m=m, s=s, T=T) t2 = Term.new('dw_volume_dot(s, dT/dt)', integral, omega, s=s, T=T) eq = Equation('balance', t1 + t2) eqs = Equations([eq]) # Boundary conditions. ebc1 = EssentialBC('T1', left, {'T.0' : 2.0}) ebc2 = EssentialBC('T2', right, {'T.0' : -2.0}) # Initial conditions. def get_ic(coors, ic): x, y, z = coors.T return 2 - 40.0 * x + options.ic_max * nm.sin(4 * nm.pi * x / 0.1) ic_fun = Function('ic_fun', get_ic) ic = InitialCondition('ic', omega, {'T.0' : ic_fun}) pb = Problem('heat', equations=eqs) pb.set_bcs(ebcs=Conditions([ebc1, ebc2])) pb.set_ics(
Conditions([ic])
sfepy.discrete.conditions.Conditions
#!/usr/bin/env python """ Transient Laplace equation (heat equation) with non-constant initial conditions given by a function, using commands for interactive use. The script allows setting various simulation parameters, namely: - the diffusivity coefficient - the max. initial condition value - temperature field approximation order - uniform mesh refinement The example shows also how to probe the results. In the SfePy top-level directory the following command can be used to get usage information:: python examples/diffusion/time_poisson_interactive.py -h """ 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, Function, Equation, Equations, Problem) from sfepy.discrete.problem import prepare_matrix 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.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.discrete.probes import LineProbe, CircleProbe from sfepy.discrete.projections import project_by_component def gen_probes(problem): """ Define a line probe and a circle probe. """ # Use enough points for higher order approximations. n_point = 1000 p0, p1 = nm.array([0.0, 0.0, 0.0]), nm.array([0.1, 0.0, 0.0]) line = LineProbe(p0, p1, n_point, share_geometry=True) # Workaround current probe code shortcoming. line.set_options(close_limit=0.5) centre = 0.5 * (p0 + p1) normal = [0.0, 1.0, 0.0] r = 0.019 circle = CircleProbe(centre, normal, r, n_point, share_geometry=True) circle.set_options(close_limit=0.0) probes = [line, circle] labels = ['%s -> %s' % (p0, p1), 'circle(%s, %s, %s' % (centre, normal, r)] return probes, labels def probe_results(ax_num, T, dvel, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(T) results['T'] = (pars, vals) pars, vals = probe(dvel) results['dvel'] = (pars, vals) fig = plt.figure(1) ax = plt.subplot(2, 2, 2 * ax_num + 1) ax.cla() pars, vals = results['T'] ax.plot(pars, vals, label=r'$T$', lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('temperature') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) ax = plt.subplot(2, 2, 2 * ax_num + 2) ax.cla() pars, vals = results['dvel'] for ic in range(vals.shape[1]): ax.plot(pars, vals[:, ic], label=r'$w_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('diffusion velocity') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) return fig, results helps = { 'diffusivity' : 'the diffusivity coefficient [default: %(default)s]', 'ic_max' : 'the max. initial condition value [default: %(default)s]', 'order' : 'temperature field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the probing results figure, if --probe is used', } 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('--diffusivity', metavar='float', type=float, action='store', dest='diffusivity', default=1e-5, help=helps['diffusivity']) parser.add_argument('--ic-max', metavar='float', type=float, action='store', dest='ic_max', default=2.0, help=helps['ic_max']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=2, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() assert_((0 < options.order), 'temperature approximation order must be at least 1!') output('using values:') output(' diffusivity:', options.diffusivity) output(' max. IC value:', options.ic_max) output('uniform mesh refinement level:', options.refine) mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine):
output('refine %d...' % ii)
sfepy.base.base.output
#!/usr/bin/env python """ Transient Laplace equation (heat equation) with non-constant initial conditions given by a function, using commands for interactive use. The script allows setting various simulation parameters, namely: - the diffusivity coefficient - the max. initial condition value - temperature field approximation order - uniform mesh refinement The example shows also how to probe the results. In the SfePy top-level directory the following command can be used to get usage information:: python examples/diffusion/time_poisson_interactive.py -h """ 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, Function, Equation, Equations, Problem) from sfepy.discrete.problem import prepare_matrix 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.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.discrete.probes import LineProbe, CircleProbe from sfepy.discrete.projections import project_by_component def gen_probes(problem): """ Define a line probe and a circle probe. """ # Use enough points for higher order approximations. n_point = 1000 p0, p1 = nm.array([0.0, 0.0, 0.0]), nm.array([0.1, 0.0, 0.0]) line = LineProbe(p0, p1, n_point, share_geometry=True) # Workaround current probe code shortcoming. line.set_options(close_limit=0.5) centre = 0.5 * (p0 + p1) normal = [0.0, 1.0, 0.0] r = 0.019 circle = CircleProbe(centre, normal, r, n_point, share_geometry=True) circle.set_options(close_limit=0.0) probes = [line, circle] labels = ['%s -> %s' % (p0, p1), 'circle(%s, %s, %s' % (centre, normal, r)] return probes, labels def probe_results(ax_num, T, dvel, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(T) results['T'] = (pars, vals) pars, vals = probe(dvel) results['dvel'] = (pars, vals) fig = plt.figure(1) ax = plt.subplot(2, 2, 2 * ax_num + 1) ax.cla() pars, vals = results['T'] ax.plot(pars, vals, label=r'$T$', lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('temperature') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) ax = plt.subplot(2, 2, 2 * ax_num + 2) ax.cla() pars, vals = results['dvel'] for ic in range(vals.shape[1]): ax.plot(pars, vals[:, ic], label=r'$w_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('diffusion velocity') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) return fig, results helps = { 'diffusivity' : 'the diffusivity coefficient [default: %(default)s]', 'ic_max' : 'the max. initial condition value [default: %(default)s]', 'order' : 'temperature field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the probing results figure, if --probe is used', } 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('--diffusivity', metavar='float', type=float, action='store', dest='diffusivity', default=1e-5, help=helps['diffusivity']) parser.add_argument('--ic-max', metavar='float', type=float, action='store', dest='ic_max', default=2.0, help=helps['ic_max']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=2, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() assert_((0 < options.order), 'temperature approximation order must be at least 1!') output('using values:') output(' diffusivity:', options.diffusivity) output(' max. IC value:', options.ic_max) output('uniform mesh refinement level:', options.refine) mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.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.00001', 'facet') right = domain.create_region('Right', 'vertices in x > 0.099999', 'facet') field = Field.from_args('fu', nm.float64, 'scalar', omega, approx_order=options.order) T = FieldVariable('T', 'unknown', field, history=1) s = FieldVariable('s', 'test', field, primary_var_name='T') m = Material('m', diffusivity=options.diffusivity * nm.eye(3)) integral = Integral('i', order=2*options.order) t1 = Term.new('dw_diffusion(m.diffusivity, s, T)', integral, omega, m=m, s=s, T=T) t2 = Term.new('dw_volume_dot(s, dT/dt)', integral, omega, s=s, T=T) eq = Equation('balance', t1 + t2) eqs = Equations([eq]) # Boundary conditions. ebc1 = EssentialBC('T1', left, {'T.0' : 2.0}) ebc2 = EssentialBC('T2', right, {'T.0' : -2.0}) # Initial conditions. def get_ic(coors, ic): x, y, z = coors.T return 2 - 40.0 * x + options.ic_max * nm.sin(4 * nm.pi * x / 0.1) ic_fun = Function('ic_fun', get_ic) ic = InitialCondition('ic', omega, {'T.0' : ic_fun}) pb = Problem('heat', equations=eqs) pb.set_bcs(ebcs=
Conditions([ebc1, ebc2])
sfepy.discrete.conditions.Conditions
#!/usr/bin/env python """ Transient Laplace equation (heat equation) with non-constant initial conditions given by a function, using commands for interactive use. The script allows setting various simulation parameters, namely: - the diffusivity coefficient - the max. initial condition value - temperature field approximation order - uniform mesh refinement The example shows also how to probe the results. In the SfePy top-level directory the following command can be used to get usage information:: python examples/diffusion/time_poisson_interactive.py -h """ 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, Function, Equation, Equations, Problem) from sfepy.discrete.problem import prepare_matrix 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.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.discrete.probes import LineProbe, CircleProbe from sfepy.discrete.projections import project_by_component def gen_probes(problem): """ Define a line probe and a circle probe. """ # Use enough points for higher order approximations. n_point = 1000 p0, p1 = nm.array([0.0, 0.0, 0.0]), nm.array([0.1, 0.0, 0.0]) line = LineProbe(p0, p1, n_point, share_geometry=True) # Workaround current probe code shortcoming. line.set_options(close_limit=0.5) centre = 0.5 * (p0 + p1) normal = [0.0, 1.0, 0.0] r = 0.019 circle = CircleProbe(centre, normal, r, n_point, share_geometry=True) circle.set_options(close_limit=0.0) probes = [line, circle] labels = ['%s -> %s' % (p0, p1), 'circle(%s, %s, %s' % (centre, normal, r)] return probes, labels def probe_results(ax_num, T, dvel, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(T) results['T'] = (pars, vals) pars, vals = probe(dvel) results['dvel'] = (pars, vals) fig = plt.figure(1) ax = plt.subplot(2, 2, 2 * ax_num + 1) ax.cla() pars, vals = results['T'] ax.plot(pars, vals, label=r'$T$', lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('temperature') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) ax = plt.subplot(2, 2, 2 * ax_num + 2) ax.cla() pars, vals = results['dvel'] for ic in range(vals.shape[1]): ax.plot(pars, vals[:, ic], label=r'$w_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('diffusion velocity') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) return fig, results helps = { 'diffusivity' : 'the diffusivity coefficient [default: %(default)s]', 'ic_max' : 'the max. initial condition value [default: %(default)s]', 'order' : 'temperature field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the probing results figure, if --probe is used', } 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('--diffusivity', metavar='float', type=float, action='store', dest='diffusivity', default=1e-5, help=helps['diffusivity']) parser.add_argument('--ic-max', metavar='float', type=float, action='store', dest='ic_max', default=2.0, help=helps['ic_max']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=2, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() assert_((0 < options.order), 'temperature approximation order must be at least 1!') output('using values:') output(' diffusivity:', options.diffusivity) output(' max. IC value:', options.ic_max) output('uniform mesh refinement level:', options.refine) mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.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.00001', 'facet') right = domain.create_region('Right', 'vertices in x > 0.099999', 'facet') field = Field.from_args('fu', nm.float64, 'scalar', omega, approx_order=options.order) T = FieldVariable('T', 'unknown', field, history=1) s = FieldVariable('s', 'test', field, primary_var_name='T') m = Material('m', diffusivity=options.diffusivity * nm.eye(3)) integral = Integral('i', order=2*options.order) t1 = Term.new('dw_diffusion(m.diffusivity, s, T)', integral, omega, m=m, s=s, T=T) t2 = Term.new('dw_volume_dot(s, dT/dt)', integral, omega, s=s, T=T) eq = Equation('balance', t1 + t2) eqs = Equations([eq]) # Boundary conditions. ebc1 = EssentialBC('T1', left, {'T.0' : 2.0}) ebc2 = EssentialBC('T2', right, {'T.0' : -2.0}) # Initial conditions. def get_ic(coors, ic): x, y, z = coors.T return 2 - 40.0 * x + options.ic_max * nm.sin(4 * nm.pi * x / 0.1) ic_fun = Function('ic_fun', get_ic) ic = InitialCondition('ic', omega, {'T.0' : ic_fun}) pb = Problem('heat', equations=eqs) pb.set_bcs(ebcs=Conditions([ebc1, ebc2])) pb.set_ics(Conditions([ic])) state0 = pb.get_initial_state() init_fun, prestep_fun, _poststep_fun = pb.get_tss_functions(state0) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({'is_linear' : True}, lin_solver=ls, status=nls_status) tss = SimpleTimeSteppingSolver({'t0' : 0.0, 't1' : 100.0, 'n_step' : 11}, nls=nls, context=pb, verbose=True) pb.set_solver(tss) if options.probe: # Prepare probe data. probes, labels = gen_probes(pb) ev = pb.evaluate order = 2 * (options.order - 1) gfield = Field.from_args('gu', nm.float64, 'vector', omega, approx_order=options.order - 1) dvel = FieldVariable('dvel', 'parameter', gfield, primary_var_name='(set-to-None)') cfield = Field.from_args('gu', nm.float64, 'scalar', omega, approx_order=options.order - 1) component = FieldVariable('component', 'parameter', cfield, primary_var_name='(set-to-None)') nls_options = {'eps_a' : 1e-16, 'i_max' : 1} suffix = tss.ts.suffix def poststep_fun(ts, vec): _poststep_fun(ts, vec) # Probe the solution. dvel_qp = ev('ev_diffusion_velocity.%d.Omega(m.diffusivity, T)' % order, copy_materials=False, mode='qp') project_by_component(dvel, dvel_qp, component, order, nls_options=nls_options) all_results = [] for ii, probe in enumerate(probes): fig, results = probe_results(ii, T, dvel, probe, labels[ii]) all_results.append(results) plt.tight_layout() fig.savefig('time_poisson_interactive_probe_%s.png' % (suffix % ts.step), bbox_inches='tight') for ii, results in enumerate(all_results):
output('probe %d (%s):' % (ii, probes[ii].name))
sfepy.base.base.output
#!/usr/bin/env python """ Transient Laplace equation (heat equation) with non-constant initial conditions given by a function, using commands for interactive use. The script allows setting various simulation parameters, namely: - the diffusivity coefficient - the max. initial condition value - temperature field approximation order - uniform mesh refinement The example shows also how to probe the results. In the SfePy top-level directory the following command can be used to get usage information:: python examples/diffusion/time_poisson_interactive.py -h """ 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, Function, Equation, Equations, Problem) from sfepy.discrete.problem import prepare_matrix 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.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.discrete.probes import LineProbe, CircleProbe from sfepy.discrete.projections import project_by_component def gen_probes(problem): """ Define a line probe and a circle probe. """ # Use enough points for higher order approximations. n_point = 1000 p0, p1 = nm.array([0.0, 0.0, 0.0]), nm.array([0.1, 0.0, 0.0]) line = LineProbe(p0, p1, n_point, share_geometry=True) # Workaround current probe code shortcoming. line.set_options(close_limit=0.5) centre = 0.5 * (p0 + p1) normal = [0.0, 1.0, 0.0] r = 0.019 circle = CircleProbe(centre, normal, r, n_point, share_geometry=True) circle.set_options(close_limit=0.0) probes = [line, circle] labels = ['%s -> %s' % (p0, p1), 'circle(%s, %s, %s' % (centre, normal, r)] return probes, labels def probe_results(ax_num, T, dvel, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(T) results['T'] = (pars, vals) pars, vals = probe(dvel) results['dvel'] = (pars, vals) fig = plt.figure(1) ax = plt.subplot(2, 2, 2 * ax_num + 1) ax.cla() pars, vals = results['T'] ax.plot(pars, vals, label=r'$T$', lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('temperature') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) ax = plt.subplot(2, 2, 2 * ax_num + 2) ax.cla() pars, vals = results['dvel'] for ic in range(vals.shape[1]): ax.plot(pars, vals[:, ic], label=r'$w_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('diffusion velocity') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) return fig, results helps = { 'diffusivity' : 'the diffusivity coefficient [default: %(default)s]', 'ic_max' : 'the max. initial condition value [default: %(default)s]', 'order' : 'temperature field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the probing results figure, if --probe is used', } 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('--diffusivity', metavar='float', type=float, action='store', dest='diffusivity', default=1e-5, help=helps['diffusivity']) parser.add_argument('--ic-max', metavar='float', type=float, action='store', dest='ic_max', default=2.0, help=helps['ic_max']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=2, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() assert_((0 < options.order), 'temperature approximation order must be at least 1!') output('using values:') output(' diffusivity:', options.diffusivity) output(' max. IC value:', options.ic_max) output('uniform mesh refinement level:', options.refine) mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.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.00001', 'facet') right = domain.create_region('Right', 'vertices in x > 0.099999', 'facet') field = Field.from_args('fu', nm.float64, 'scalar', omega, approx_order=options.order) T = FieldVariable('T', 'unknown', field, history=1) s = FieldVariable('s', 'test', field, primary_var_name='T') m = Material('m', diffusivity=options.diffusivity * nm.eye(3)) integral = Integral('i', order=2*options.order) t1 = Term.new('dw_diffusion(m.diffusivity, s, T)', integral, omega, m=m, s=s, T=T) t2 = Term.new('dw_volume_dot(s, dT/dt)', integral, omega, s=s, T=T) eq = Equation('balance', t1 + t2) eqs = Equations([eq]) # Boundary conditions. ebc1 = EssentialBC('T1', left, {'T.0' : 2.0}) ebc2 = EssentialBC('T2', right, {'T.0' : -2.0}) # Initial conditions. def get_ic(coors, ic): x, y, z = coors.T return 2 - 40.0 * x + options.ic_max * nm.sin(4 * nm.pi * x / 0.1) ic_fun = Function('ic_fun', get_ic) ic = InitialCondition('ic', omega, {'T.0' : ic_fun}) pb = Problem('heat', equations=eqs) pb.set_bcs(ebcs=Conditions([ebc1, ebc2])) pb.set_ics(Conditions([ic])) state0 = pb.get_initial_state() init_fun, prestep_fun, _poststep_fun = pb.get_tss_functions(state0) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({'is_linear' : True}, lin_solver=ls, status=nls_status) tss = SimpleTimeSteppingSolver({'t0' : 0.0, 't1' : 100.0, 'n_step' : 11}, nls=nls, context=pb, verbose=True) pb.set_solver(tss) if options.probe: # Prepare probe data. probes, labels = gen_probes(pb) ev = pb.evaluate order = 2 * (options.order - 1) gfield = Field.from_args('gu', nm.float64, 'vector', omega, approx_order=options.order - 1) dvel = FieldVariable('dvel', 'parameter', gfield, primary_var_name='(set-to-None)') cfield = Field.from_args('gu', nm.float64, 'scalar', omega, approx_order=options.order - 1) component = FieldVariable('component', 'parameter', cfield, primary_var_name='(set-to-None)') nls_options = {'eps_a' : 1e-16, 'i_max' : 1} suffix = tss.ts.suffix def poststep_fun(ts, vec): _poststep_fun(ts, vec) # Probe the solution. dvel_qp = ev('ev_diffusion_velocity.%d.Omega(m.diffusivity, T)' % order, copy_materials=False, mode='qp') project_by_component(dvel, dvel_qp, component, order, nls_options=nls_options) all_results = [] for ii, probe in enumerate(probes): fig, results = probe_results(ii, T, dvel, probe, labels[ii]) all_results.append(results) plt.tight_layout() fig.savefig('time_poisson_interactive_probe_%s.png' % (suffix % ts.step), bbox_inches='tight') for ii, results in enumerate(all_results): output('probe %d (%s):' % (ii, probes[ii].name)) output.level += 2 for key, res in
ordered_iteritems(results)
sfepy.base.base.ordered_iteritems
#!/usr/bin/env python """ Transient Laplace equation (heat equation) with non-constant initial conditions given by a function, using commands for interactive use. The script allows setting various simulation parameters, namely: - the diffusivity coefficient - the max. initial condition value - temperature field approximation order - uniform mesh refinement The example shows also how to probe the results. In the SfePy top-level directory the following command can be used to get usage information:: python examples/diffusion/time_poisson_interactive.py -h """ 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, Function, Equation, Equations, Problem) from sfepy.discrete.problem import prepare_matrix 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.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.discrete.probes import LineProbe, CircleProbe from sfepy.discrete.projections import project_by_component def gen_probes(problem): """ Define a line probe and a circle probe. """ # Use enough points for higher order approximations. n_point = 1000 p0, p1 = nm.array([0.0, 0.0, 0.0]), nm.array([0.1, 0.0, 0.0]) line = LineProbe(p0, p1, n_point, share_geometry=True) # Workaround current probe code shortcoming. line.set_options(close_limit=0.5) centre = 0.5 * (p0 + p1) normal = [0.0, 1.0, 0.0] r = 0.019 circle = CircleProbe(centre, normal, r, n_point, share_geometry=True) circle.set_options(close_limit=0.0) probes = [line, circle] labels = ['%s -> %s' % (p0, p1), 'circle(%s, %s, %s' % (centre, normal, r)] return probes, labels def probe_results(ax_num, T, dvel, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(T) results['T'] = (pars, vals) pars, vals = probe(dvel) results['dvel'] = (pars, vals) fig = plt.figure(1) ax = plt.subplot(2, 2, 2 * ax_num + 1) ax.cla() pars, vals = results['T'] ax.plot(pars, vals, label=r'$T$', lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('temperature') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) ax = plt.subplot(2, 2, 2 * ax_num + 2) ax.cla() pars, vals = results['dvel'] for ic in range(vals.shape[1]): ax.plot(pars, vals[:, ic], label=r'$w_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) dx = 0.05 * (pars[-1] - pars[0]) ax.set_xlim(pars[0] - dx, pars[-1] + dx) ax.set_ylabel('diffusion velocity') ax.set_xlabel('probe %s' % label, fontsize=8) ax.legend(loc='best', fontsize=10) return fig, results helps = { 'diffusivity' : 'the diffusivity coefficient [default: %(default)s]', 'ic_max' : 'the max. initial condition value [default: %(default)s]', 'order' : 'temperature field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the probing results figure, if --probe is used', } 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('--diffusivity', metavar='float', type=float, action='store', dest='diffusivity', default=1e-5, help=helps['diffusivity']) parser.add_argument('--ic-max', metavar='float', type=float, action='store', dest='ic_max', default=2.0, help=helps['ic_max']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=2, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() assert_((0 < options.order), 'temperature approximation order must be at least 1!') output('using values:') output(' diffusivity:', options.diffusivity) output(' max. IC value:', options.ic_max) output('uniform mesh refinement level:', options.refine) mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.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.00001', 'facet') right = domain.create_region('Right', 'vertices in x > 0.099999', 'facet') field = Field.from_args('fu', nm.float64, 'scalar', omega, approx_order=options.order) T = FieldVariable('T', 'unknown', field, history=1) s = FieldVariable('s', 'test', field, primary_var_name='T') m = Material('m', diffusivity=options.diffusivity * nm.eye(3)) integral = Integral('i', order=2*options.order) t1 = Term.new('dw_diffusion(m.diffusivity, s, T)', integral, omega, m=m, s=s, T=T) t2 = Term.new('dw_volume_dot(s, dT/dt)', integral, omega, s=s, T=T) eq = Equation('balance', t1 + t2) eqs = Equations([eq]) # Boundary conditions. ebc1 = EssentialBC('T1', left, {'T.0' : 2.0}) ebc2 = EssentialBC('T2', right, {'T.0' : -2.0}) # Initial conditions. def get_ic(coors, ic): x, y, z = coors.T return 2 - 40.0 * x + options.ic_max * nm.sin(4 * nm.pi * x / 0.1) ic_fun = Function('ic_fun', get_ic) ic = InitialCondition('ic', omega, {'T.0' : ic_fun}) pb = Problem('heat', equations=eqs) pb.set_bcs(ebcs=Conditions([ebc1, ebc2])) pb.set_ics(Conditions([ic])) state0 = pb.get_initial_state() init_fun, prestep_fun, _poststep_fun = pb.get_tss_functions(state0) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({'is_linear' : True}, lin_solver=ls, status=nls_status) tss = SimpleTimeSteppingSolver({'t0' : 0.0, 't1' : 100.0, 'n_step' : 11}, nls=nls, context=pb, verbose=True) pb.set_solver(tss) if options.probe: # Prepare probe data. probes, labels = gen_probes(pb) ev = pb.evaluate order = 2 * (options.order - 1) gfield = Field.from_args('gu', nm.float64, 'vector', omega, approx_order=options.order - 1) dvel = FieldVariable('dvel', 'parameter', gfield, primary_var_name='(set-to-None)') cfield = Field.from_args('gu', nm.float64, 'scalar', omega, approx_order=options.order - 1) component = FieldVariable('component', 'parameter', cfield, primary_var_name='(set-to-None)') nls_options = {'eps_a' : 1e-16, 'i_max' : 1} suffix = tss.ts.suffix def poststep_fun(ts, vec): _poststep_fun(ts, vec) # Probe the solution. dvel_qp = ev('ev_diffusion_velocity.%d.Omega(m.diffusivity, T)' % order, copy_materials=False, mode='qp') project_by_component(dvel, dvel_qp, component, order, nls_options=nls_options) all_results = [] for ii, probe in enumerate(probes): fig, results = probe_results(ii, T, dvel, probe, labels[ii]) all_results.append(results) plt.tight_layout() fig.savefig('time_poisson_interactive_probe_%s.png' % (suffix % ts.step), bbox_inches='tight') for ii, results in enumerate(all_results): output('probe %d (%s):' % (ii, probes[ii].name)) output.level += 2 for key, res in ordered_iteritems(results):
output(key + ':')
sfepy.base.base.output
import numpy as np from sfepy.base.conf import ProblemConf from sfepy.discrete.problem import Problem from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.postprocess.viewer import Viewer from scipy.interpolate import interpn import matplotlib.pyplot as plt from matplotlib import ticker class Block2d: """ Small wrapper for sfepy problem class. Constructs a rectangle of specificed dimensions with a rectangular FEM mesh. Rectangle is gripped at one end and pulled away at the other end, by a specified distance. FEM mesh sixe can be specified. Centre of rectangle can be specified. Having done this, this class exposes the stretch amount and the distribution of the stiffness tensor D as paramters that can be set, and allows querying of the displacement at a set of points in the domain. rectangle is stretched parallel to the y-axis. short side of rectangle is x-axis. Also drawing. """ def __init__(self, dims, center_location, cell_sizes=np.array([2,2]), prob_file="C:\\Users\\wbald\\sfepythings\\blocks\\fem\\prob_desc_2d.py", put_mesh="C:\\Users\\wbald\\sfepythings"): """ dims: array, dimensions of rectangle [x,y] center_location: array, centre of rectangle [x,y] cell sizes: array, x and y side length of FEM rectangular elements stretch: default distance by which to displace the upper y axis edge. prob_file: problem description file put_mesh: where to save the mesh file """ assert(dims.shape[0] == 2) assert(cell_sizes.shape[0] == 2) # assume linear elasticity. Fix strain of rectangle to 0.001 and query # at different strains by scaling linearly self.dims = dims self.prob_file = prob_file self.FEM_model_strain = 0.001 self.elongation= self.FEM_model_strain * self.dims[1] nums = np.divide(dims, cell_sizes) nums = np.around(nums).astype(int) + np.array([1,1]) blockmesh =
gen_block_mesh(dims, nums, center_location)
sfepy.mesh.mesh_generators.gen_block_mesh
import numpy as np from sfepy.base.conf import ProblemConf from sfepy.discrete.problem import Problem from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.postprocess.viewer import Viewer from scipy.interpolate import interpn import matplotlib.pyplot as plt from matplotlib import ticker class Block2d: """ Small wrapper for sfepy problem class. Constructs a rectangle of specificed dimensions with a rectangular FEM mesh. Rectangle is gripped at one end and pulled away at the other end, by a specified distance. FEM mesh sixe can be specified. Centre of rectangle can be specified. Having done this, this class exposes the stretch amount and the distribution of the stiffness tensor D as paramters that can be set, and allows querying of the displacement at a set of points in the domain. rectangle is stretched parallel to the y-axis. short side of rectangle is x-axis. Also drawing. """ def __init__(self, dims, center_location, cell_sizes=np.array([2,2]), prob_file="C:\\Users\\wbald\\sfepythings\\blocks\\fem\\prob_desc_2d.py", put_mesh="C:\\Users\\wbald\\sfepythings"): """ dims: array, dimensions of rectangle [x,y] center_location: array, centre of rectangle [x,y] cell sizes: array, x and y side length of FEM rectangular elements stretch: default distance by which to displace the upper y axis edge. prob_file: problem description file put_mesh: where to save the mesh file """ assert(dims.shape[0] == 2) assert(cell_sizes.shape[0] == 2) # assume linear elasticity. Fix strain of rectangle to 0.001 and query # at different strains by scaling linearly self.dims = dims self.prob_file = prob_file self.FEM_model_strain = 0.001 self.elongation= self.FEM_model_strain * self.dims[1] nums = np.divide(dims, cell_sizes) nums = np.around(nums).astype(int) + np.array([1,1]) blockmesh = gen_block_mesh(dims, nums, center_location) blockmesh.write(put_mesh + '\\mesh.vtk') conf =
ProblemConf.from_file(prob_file)
sfepy.base.conf.ProblemConf.from_file
import numpy as np from sfepy.base.conf import ProblemConf from sfepy.discrete.problem import Problem from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.postprocess.viewer import Viewer from scipy.interpolate import interpn import matplotlib.pyplot as plt from matplotlib import ticker class Block2d: """ Small wrapper for sfepy problem class. Constructs a rectangle of specificed dimensions with a rectangular FEM mesh. Rectangle is gripped at one end and pulled away at the other end, by a specified distance. FEM mesh sixe can be specified. Centre of rectangle can be specified. Having done this, this class exposes the stretch amount and the distribution of the stiffness tensor D as paramters that can be set, and allows querying of the displacement at a set of points in the domain. rectangle is stretched parallel to the y-axis. short side of rectangle is x-axis. Also drawing. """ def __init__(self, dims, center_location, cell_sizes=np.array([2,2]), prob_file="C:\\Users\\wbald\\sfepythings\\blocks\\fem\\prob_desc_2d.py", put_mesh="C:\\Users\\wbald\\sfepythings"): """ dims: array, dimensions of rectangle [x,y] center_location: array, centre of rectangle [x,y] cell sizes: array, x and y side length of FEM rectangular elements stretch: default distance by which to displace the upper y axis edge. prob_file: problem description file put_mesh: where to save the mesh file """ assert(dims.shape[0] == 2) assert(cell_sizes.shape[0] == 2) # assume linear elasticity. Fix strain of rectangle to 0.001 and query # at different strains by scaling linearly self.dims = dims self.prob_file = prob_file self.FEM_model_strain = 0.001 self.elongation= self.FEM_model_strain * self.dims[1] nums = np.divide(dims, cell_sizes) nums = np.around(nums).astype(int) + np.array([1,1]) blockmesh = gen_block_mesh(dims, nums, center_location) blockmesh.write(put_mesh + '\\mesh.vtk') conf = ProblemConf.from_file(prob_file) # 'region_ylower__1' holds the edge to be fixed # 'region_yupper__2' holds the edge to be displaced conf.regions['region_ylower__1'].select = 'vertices in (y < ' + str(0.01) + ')' conf.regions['region_yupper__2'].select = 'vertices in (y > ' + str(dims[1] - 0.01) + ')' conf.ebcs['ebc_Displaced__1'].dofs['u.1'] = self.elongation self.prob =
Problem.from_conf(conf)
sfepy.discrete.problem.Problem.from_conf
import numpy as np from sfepy.base.conf import ProblemConf from sfepy.discrete.problem import Problem from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.postprocess.viewer import Viewer from scipy.interpolate import interpn import matplotlib.pyplot as plt from matplotlib import ticker class Block2d: """ Small wrapper for sfepy problem class. Constructs a rectangle of specificed dimensions with a rectangular FEM mesh. Rectangle is gripped at one end and pulled away at the other end, by a specified distance. FEM mesh sixe can be specified. Centre of rectangle can be specified. Having done this, this class exposes the stretch amount and the distribution of the stiffness tensor D as paramters that can be set, and allows querying of the displacement at a set of points in the domain. rectangle is stretched parallel to the y-axis. short side of rectangle is x-axis. Also drawing. """ def __init__(self, dims, center_location, cell_sizes=np.array([2,2]), prob_file="C:\\Users\\wbald\\sfepythings\\blocks\\fem\\prob_desc_2d.py", put_mesh="C:\\Users\\wbald\\sfepythings"): """ dims: array, dimensions of rectangle [x,y] center_location: array, centre of rectangle [x,y] cell sizes: array, x and y side length of FEM rectangular elements stretch: default distance by which to displace the upper y axis edge. prob_file: problem description file put_mesh: where to save the mesh file """ assert(dims.shape[0] == 2) assert(cell_sizes.shape[0] == 2) # assume linear elasticity. Fix strain of rectangle to 0.001 and query # at different strains by scaling linearly self.dims = dims self.prob_file = prob_file self.FEM_model_strain = 0.001 self.elongation= self.FEM_model_strain * self.dims[1] nums = np.divide(dims, cell_sizes) nums = np.around(nums).astype(int) + np.array([1,1]) blockmesh = gen_block_mesh(dims, nums, center_location) blockmesh.write(put_mesh + '\\mesh.vtk') conf = ProblemConf.from_file(prob_file) # 'region_ylower__1' holds the edge to be fixed # 'region_yupper__2' holds the edge to be displaced conf.regions['region_ylower__1'].select = 'vertices in (y < ' + str(0.01) + ')' conf.regions['region_yupper__2'].select = 'vertices in (y > ' + str(dims[1] - 0.01) + ')' conf.ebcs['ebc_Displaced__1'].dofs['u.1'] = self.elongation self.prob = Problem.from_conf(conf) # for reshaping sfepy output into xyz displacements self.reshape_tuple = ((self.prob.fields['displacement'].n_nod, self.prob.fields['displacement'].n_components)) def _set_param_field(self, query): # the stiffness is specified by the voigt notation tensor D, which is # passed to the problem class as a queryable function of position def fun(ts, coors, mode=None, **kwargs): if mode=='qp': return {'D' : query(coors)} self.prob.functions._objs[0].function = fun def get_disp_at_coords(self, D_query_function, strain, coords): # get the displacement given a stiffness field D and displacement strain. self._set_param_field(D_query_function) state = self.prob.solve() displacement = self.prob.fields['displacement'].evaluate_at(coords, state.vec.reshape(self.reshape_tuple)) displacement *= strain / self.FEM_model_strain return displacement def drawstate(self, state): # draw the object with sfepy's viewer # state can be obtained from prob.solve() self.prob.save_state('curr_run_demo.vtk', state) view =
Viewer('curr_run_demo.vtk')
sfepy.postprocess.viewer.Viewer
# 04.08.2009 #! #! Homogenization: Linear Elasticity #! ================================= #$ \centerline{Example input file, \today} #! Homogenization of heterogeneous linear elastic material import sfepy.discrete.fem.periodic as per from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.homogenization.utils import define_box_regions 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 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 ) out['u_mic'] = Struct( name = 'output_data', mode = 'vertex', data = mic_u, var_name = 'u', 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'] ) 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 #! ---- filename_mesh = data_dir + '/meshes/3d/matrix_fiber.mesh' dim = 3 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(dim, 7.0e9, 0.4)
sfepy.mechanics.matcoefs.stiffness_from_youngpoisson
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 from sfepy.mechanics.matcoefs import ElasticConstants ok = True names = ['bulk', 'lam', 'mu', 'young', 'poisson', 'p_wave'] ec =
ElasticConstants(lam=1.0, mu=1.5)
sfepy.mechanics.matcoefs.ElasticConstants
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out)
output('dumping to VTK...')
sfepy.base.base.output
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io =
MeshIO.any_from_filename(filename)
sfepy.discrete.fem.meshio.MeshIO.any_from_filename
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh =
Mesh.from_file(filename, io=io)
sfepy.discrete.fem.mesh.Mesh.from_file
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk = get_trunk(filename) try: ts = TimeStepper(*io.read_time_stepper()) all_steps, times, nts, dts = extract_times(filename) except ValueError: output('no time stepping info found, assuming single step') out = io.read_data(0) if out is not None: _save_step('.vtk', out, mesh) ret = None else: ts.times = times ts.n_step = times.shape[0] if steps is None: ii0 = nm.searchsorted(all_steps, step0) iterator = ((all_steps[ii], times[ii]) for ii in range(ii0, len(times))) else: iterator = [(step, ts.times[step]) for step in steps] max_step = all_steps.max() for step, time in iterator: output(ts.format % (step, max_step)) out = io.read_data(step) if out is None: break _save_step('.' + ts.suffix % step + '.vtk', out, mesh) ret = ts.suffix
output('...done')
sfepy.base.base.output
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk = get_trunk(filename) try: ts = TimeStepper(*io.read_time_stepper()) all_steps, times, nts, dts = extract_times(filename) except ValueError: output('no time stepping info found, assuming single step') out = io.read_data(0) if out is not None: _save_step('.vtk', out, mesh) ret = None else: ts.times = times ts.n_step = times.shape[0] if steps is None: ii0 = nm.searchsorted(all_steps, step0) iterator = ((all_steps[ii], times[ii]) for ii in range(ii0, len(times))) else: iterator = [(step, ts.times[step]) for step in steps] max_step = all_steps.max() for step, time in iterator: output(ts.format % (step, max_step)) out = io.read_data(step) if out is None: break _save_step('.' + ts.suffix % step + '.vtk', out, mesh) ret = ts.suffix output('...done') return ret def extract_times(filename): """ Read true time step data from individual time steps. Returns ------- steps : array The time steps. times : array The times of the time steps. nts : array The normalized times of the time steps, in [0, 1]. dts : array The true time deltas. """ io =
MeshIO.any_from_filename(filename)
sfepy.discrete.fem.meshio.MeshIO.any_from_filename
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk = get_trunk(filename) try: ts = TimeStepper(*io.read_time_stepper()) all_steps, times, nts, dts = extract_times(filename) except ValueError: output('no time stepping info found, assuming single step') out = io.read_data(0) if out is not None: _save_step('.vtk', out, mesh) ret = None else: ts.times = times ts.n_step = times.shape[0] if steps is None: ii0 = nm.searchsorted(all_steps, step0) iterator = ((all_steps[ii], times[ii]) for ii in range(ii0, len(times))) else: iterator = [(step, ts.times[step]) for step in steps] max_step = all_steps.max() for step, time in iterator: output(ts.format % (step, max_step)) out = io.read_data(step) if out is None: break _save_step('.' + ts.suffix % step + '.vtk', out, mesh) ret = ts.suffix output('...done') return ret def extract_times(filename): """ Read true time step data from individual time steps. Returns ------- steps : array The time steps. times : array The times of the time steps. nts : array The normalized times of the time steps, in [0, 1]. dts : array The true time deltas. """ io = MeshIO.any_from_filename(filename) steps, times, nts = io.read_times() dts = nm.ediff1d(times, to_end=0) return steps, times, nts, dts def extract_time_history(filename, extract, verbose=True): """Extract time history of a variable from a multi-time-step results file. Parameters ---------- filename : str The name of file to extract from. extract : str The description of what to extract in a string of comma-separated description items. A description item consists of: name of the variable to extract, mode ('e' for elements, 'n' for nodes), ids of the nodes or elements (given by the mode). Example: 'u n 10 15, p e 0' means variable 'u' in nodes 10, 15 and variable 'p' in element 0. verbose : bool Verbosity control. Returns ------- ths : dict The time histories in a dict with variable names as keys. If a nodal variable is requested in elements, its value is a dict of histories in the element nodes. ts : TimeStepper instance The time stepping information. """
output('extracting selected data...', verbose=verbose)
sfepy.base.base.output
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk = get_trunk(filename) try: ts = TimeStepper(*io.read_time_stepper()) all_steps, times, nts, dts = extract_times(filename) except ValueError: output('no time stepping info found, assuming single step') out = io.read_data(0) if out is not None: _save_step('.vtk', out, mesh) ret = None else: ts.times = times ts.n_step = times.shape[0] if steps is None: ii0 = nm.searchsorted(all_steps, step0) iterator = ((all_steps[ii], times[ii]) for ii in range(ii0, len(times))) else: iterator = [(step, ts.times[step]) for step in steps] max_step = all_steps.max() for step, time in iterator: output(ts.format % (step, max_step)) out = io.read_data(step) if out is None: break _save_step('.' + ts.suffix % step + '.vtk', out, mesh) ret = ts.suffix output('...done') return ret def extract_times(filename): """ Read true time step data from individual time steps. Returns ------- steps : array The time steps. times : array The times of the time steps. nts : array The normalized times of the time steps, in [0, 1]. dts : array The true time deltas. """ io = MeshIO.any_from_filename(filename) steps, times, nts = io.read_times() dts = nm.ediff1d(times, to_end=0) return steps, times, nts, dts def extract_time_history(filename, extract, verbose=True): """Extract time history of a variable from a multi-time-step results file. Parameters ---------- filename : str The name of file to extract from. extract : str The description of what to extract in a string of comma-separated description items. A description item consists of: name of the variable to extract, mode ('e' for elements, 'n' for nodes), ids of the nodes or elements (given by the mode). Example: 'u n 10 15, p e 0' means variable 'u' in nodes 10, 15 and variable 'p' in element 0. verbose : bool Verbosity control. Returns ------- ths : dict The time histories in a dict with variable names as keys. If a nodal variable is requested in elements, its value is a dict of histories in the element nodes. ts : TimeStepper instance The time stepping information. """ output('extracting selected data...', verbose=verbose)
output('selection:', extract, verbose=verbose)
sfepy.base.base.output
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk = get_trunk(filename) try: ts = TimeStepper(*io.read_time_stepper()) all_steps, times, nts, dts = extract_times(filename) except ValueError: output('no time stepping info found, assuming single step') out = io.read_data(0) if out is not None: _save_step('.vtk', out, mesh) ret = None else: ts.times = times ts.n_step = times.shape[0] if steps is None: ii0 = nm.searchsorted(all_steps, step0) iterator = ((all_steps[ii], times[ii]) for ii in range(ii0, len(times))) else: iterator = [(step, ts.times[step]) for step in steps] max_step = all_steps.max() for step, time in iterator: output(ts.format % (step, max_step)) out = io.read_data(step) if out is None: break _save_step('.' + ts.suffix % step + '.vtk', out, mesh) ret = ts.suffix output('...done') return ret def extract_times(filename): """ Read true time step data from individual time steps. Returns ------- steps : array The time steps. times : array The times of the time steps. nts : array The normalized times of the time steps, in [0, 1]. dts : array The true time deltas. """ io = MeshIO.any_from_filename(filename) steps, times, nts = io.read_times() dts = nm.ediff1d(times, to_end=0) return steps, times, nts, dts def extract_time_history(filename, extract, verbose=True): """Extract time history of a variable from a multi-time-step results file. Parameters ---------- filename : str The name of file to extract from. extract : str The description of what to extract in a string of comma-separated description items. A description item consists of: name of the variable to extract, mode ('e' for elements, 'n' for nodes), ids of the nodes or elements (given by the mode). Example: 'u n 10 15, p e 0' means variable 'u' in nodes 10, 15 and variable 'p' in element 0. verbose : bool Verbosity control. Returns ------- ths : dict The time histories in a dict with variable names as keys. If a nodal variable is requested in elements, its value is a dict of histories in the element nodes. ts : TimeStepper instance The time stepping information. """ output('extracting selected data...', verbose=verbose) output('selection:', extract, verbose=verbose) ## # Parse extractions. pes =
OneTypeList(Struct)
sfepy.base.base.OneTypeList
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk = get_trunk(filename) try: ts = TimeStepper(*io.read_time_stepper()) all_steps, times, nts, dts = extract_times(filename) except ValueError: output('no time stepping info found, assuming single step') out = io.read_data(0) if out is not None: _save_step('.vtk', out, mesh) ret = None else: ts.times = times ts.n_step = times.shape[0] if steps is None: ii0 = nm.searchsorted(all_steps, step0) iterator = ((all_steps[ii], times[ii]) for ii in range(ii0, len(times))) else: iterator = [(step, ts.times[step]) for step in steps] max_step = all_steps.max() for step, time in iterator: output(ts.format % (step, max_step)) out = io.read_data(step) if out is None: break _save_step('.' + ts.suffix % step + '.vtk', out, mesh) ret = ts.suffix output('...done') return ret def extract_times(filename): """ Read true time step data from individual time steps. Returns ------- steps : array The time steps. times : array The times of the time steps. nts : array The normalized times of the time steps, in [0, 1]. dts : array The true time deltas. """ io = MeshIO.any_from_filename(filename) steps, times, nts = io.read_times() dts = nm.ediff1d(times, to_end=0) return steps, times, nts, dts def extract_time_history(filename, extract, verbose=True): """Extract time history of a variable from a multi-time-step results file. Parameters ---------- filename : str The name of file to extract from. extract : str The description of what to extract in a string of comma-separated description items. A description item consists of: name of the variable to extract, mode ('e' for elements, 'n' for nodes), ids of the nodes or elements (given by the mode). Example: 'u n 10 15, p e 0' means variable 'u' in nodes 10, 15 and variable 'p' in element 0. verbose : bool Verbosity control. Returns ------- ths : dict The time histories in a dict with variable names as keys. If a nodal variable is requested in elements, its value is a dict of histories in the element nodes. ts : TimeStepper instance The time stepping information. """ output('extracting selected data...', verbose=verbose) output('selection:', extract, verbose=verbose) ## # Parse extractions. pes = OneTypeList(Struct) for chunk in extract.split(','): aux = chunk.strip().split() pes.append(Struct(var=aux[0], mode=aux[1], indx=map(int, aux[2:]))) ## # Verify array limits. mesh =
Mesh.from_file(filename)
sfepy.discrete.fem.mesh.Mesh.from_file
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk = get_trunk(filename) try: ts = TimeStepper(*io.read_time_stepper()) all_steps, times, nts, dts = extract_times(filename) except ValueError: output('no time stepping info found, assuming single step') out = io.read_data(0) if out is not None: _save_step('.vtk', out, mesh) ret = None else: ts.times = times ts.n_step = times.shape[0] if steps is None: ii0 = nm.searchsorted(all_steps, step0) iterator = ((all_steps[ii], times[ii]) for ii in range(ii0, len(times))) else: iterator = [(step, ts.times[step]) for step in steps] max_step = all_steps.max() for step, time in iterator: output(ts.format % (step, max_step)) out = io.read_data(step) if out is None: break _save_step('.' + ts.suffix % step + '.vtk', out, mesh) ret = ts.suffix output('...done') return ret def extract_times(filename): """ Read true time step data from individual time steps. Returns ------- steps : array The time steps. times : array The times of the time steps. nts : array The normalized times of the time steps, in [0, 1]. dts : array The true time deltas. """ io = MeshIO.any_from_filename(filename) steps, times, nts = io.read_times() dts = nm.ediff1d(times, to_end=0) return steps, times, nts, dts def extract_time_history(filename, extract, verbose=True): """Extract time history of a variable from a multi-time-step results file. Parameters ---------- filename : str The name of file to extract from. extract : str The description of what to extract in a string of comma-separated description items. A description item consists of: name of the variable to extract, mode ('e' for elements, 'n' for nodes), ids of the nodes or elements (given by the mode). Example: 'u n 10 15, p e 0' means variable 'u' in nodes 10, 15 and variable 'p' in element 0. verbose : bool Verbosity control. Returns ------- ths : dict The time histories in a dict with variable names as keys. If a nodal variable is requested in elements, its value is a dict of histories in the element nodes. ts : TimeStepper instance The time stepping information. """ output('extracting selected data...', verbose=verbose) output('selection:', extract, verbose=verbose) ## # Parse extractions. pes = OneTypeList(Struct) for chunk in extract.split(','): aux = chunk.strip().split() pes.append(Struct(var=aux[0], mode=aux[1], indx=map(int, aux[2:]))) ## # Verify array limits. mesh = Mesh.from_file(filename) for pe in pes: if pe.mode == 'n': for ii in pe.indx: if (ii < 0) or (ii >= mesh.n_nod): raise ValueError('node index 0 <= %d < %d!' % (ii, mesh.n_nod)) if pe.mode == 'e': for ii, ie in enumerate(pe.indx[:]): if (ie < 0) or (ie >= mesh.n_el): raise ValueError('element index 0 <= %d < %d!' % (ie, mesh.n_el)) pe.indx[ii] = ie ## # Extract data. io =
MeshIO.any_from_filename(filename)
sfepy.discrete.fem.meshio.MeshIO.any_from_filename
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk = get_trunk(filename) try: ts = TimeStepper(*io.read_time_stepper()) all_steps, times, nts, dts = extract_times(filename) except ValueError: output('no time stepping info found, assuming single step') out = io.read_data(0) if out is not None: _save_step('.vtk', out, mesh) ret = None else: ts.times = times ts.n_step = times.shape[0] if steps is None: ii0 = nm.searchsorted(all_steps, step0) iterator = ((all_steps[ii], times[ii]) for ii in range(ii0, len(times))) else: iterator = [(step, ts.times[step]) for step in steps] max_step = all_steps.max() for step, time in iterator: output(ts.format % (step, max_step)) out = io.read_data(step) if out is None: break _save_step('.' + ts.suffix % step + '.vtk', out, mesh) ret = ts.suffix output('...done') return ret def extract_times(filename): """ Read true time step data from individual time steps. Returns ------- steps : array The time steps. times : array The times of the time steps. nts : array The normalized times of the time steps, in [0, 1]. dts : array The true time deltas. """ io = MeshIO.any_from_filename(filename) steps, times, nts = io.read_times() dts = nm.ediff1d(times, to_end=0) return steps, times, nts, dts def extract_time_history(filename, extract, verbose=True): """Extract time history of a variable from a multi-time-step results file. Parameters ---------- filename : str The name of file to extract from. extract : str The description of what to extract in a string of comma-separated description items. A description item consists of: name of the variable to extract, mode ('e' for elements, 'n' for nodes), ids of the nodes or elements (given by the mode). Example: 'u n 10 15, p e 0' means variable 'u' in nodes 10, 15 and variable 'p' in element 0. verbose : bool Verbosity control. Returns ------- ths : dict The time histories in a dict with variable names as keys. If a nodal variable is requested in elements, its value is a dict of histories in the element nodes. ts : TimeStepper instance The time stepping information. """ output('extracting selected data...', verbose=verbose) output('selection:', extract, verbose=verbose) ## # Parse extractions. pes = OneTypeList(Struct) for chunk in extract.split(','): aux = chunk.strip().split() pes.append(Struct(var=aux[0], mode=aux[1], indx=map(int, aux[2:]))) ## # Verify array limits. mesh = Mesh.from_file(filename) for pe in pes: if pe.mode == 'n': for ii in pe.indx: if (ii < 0) or (ii >= mesh.n_nod): raise ValueError('node index 0 <= %d < %d!' % (ii, mesh.n_nod)) if pe.mode == 'e': for ii, ie in enumerate(pe.indx[:]): if (ie < 0) or (ie >= mesh.n_el): raise ValueError('element index 0 <= %d < %d!' % (ie, mesh.n_el)) pe.indx[ii] = ie ## # Extract data. io = MeshIO.any_from_filename(filename) ths = {} for pe in pes: mode, nname = io.read_data_header(pe.var) output(mode, nname, verbose=verbose) if ((pe.mode == 'n' and mode == 'vertex') or (pe.mode == 'e' and mode == 'cell')): th = io.read_time_history(nname, pe.indx) elif pe.mode == 'e' and mode == 'vertex': conn = mesh.conns[0] th = {} for iel in pe.indx: ips = conn[iel] th[iel] = io.read_time_history(nname, ips) else: raise ValueError('cannot extract cell data %s in nodes!' % pe.var) ths[pe.var] = th
output('...done', verbose=verbose)
sfepy.base.base.output
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk = get_trunk(filename) try: ts = TimeStepper(*io.read_time_stepper()) all_steps, times, nts, dts = extract_times(filename) except ValueError: output('no time stepping info found, assuming single step') out = io.read_data(0) if out is not None: _save_step('.vtk', out, mesh) ret = None else: ts.times = times ts.n_step = times.shape[0] if steps is None: ii0 = nm.searchsorted(all_steps, step0) iterator = ((all_steps[ii], times[ii]) for ii in range(ii0, len(times))) else: iterator = [(step, ts.times[step]) for step in steps] max_step = all_steps.max() for step, time in iterator: output(ts.format % (step, max_step)) out = io.read_data(step) if out is None: break _save_step('.' + ts.suffix % step + '.vtk', out, mesh) ret = ts.suffix output('...done') return ret def extract_times(filename): """ Read true time step data from individual time steps. Returns ------- steps : array The time steps. times : array The times of the time steps. nts : array The normalized times of the time steps, in [0, 1]. dts : array The true time deltas. """ io = MeshIO.any_from_filename(filename) steps, times, nts = io.read_times() dts = nm.ediff1d(times, to_end=0) return steps, times, nts, dts def extract_time_history(filename, extract, verbose=True): """Extract time history of a variable from a multi-time-step results file. Parameters ---------- filename : str The name of file to extract from. extract : str The description of what to extract in a string of comma-separated description items. A description item consists of: name of the variable to extract, mode ('e' for elements, 'n' for nodes), ids of the nodes or elements (given by the mode). Example: 'u n 10 15, p e 0' means variable 'u' in nodes 10, 15 and variable 'p' in element 0. verbose : bool Verbosity control. Returns ------- ths : dict The time histories in a dict with variable names as keys. If a nodal variable is requested in elements, its value is a dict of histories in the element nodes. ts : TimeStepper instance The time stepping information. """ output('extracting selected data...', verbose=verbose) output('selection:', extract, verbose=verbose) ## # Parse extractions. pes = OneTypeList(Struct) for chunk in extract.split(','): aux = chunk.strip().split() pes.append(Struct(var=aux[0], mode=aux[1], indx=map(int, aux[2:]))) ## # Verify array limits. mesh = Mesh.from_file(filename) for pe in pes: if pe.mode == 'n': for ii in pe.indx: if (ii < 0) or (ii >= mesh.n_nod): raise ValueError('node index 0 <= %d < %d!' % (ii, mesh.n_nod)) if pe.mode == 'e': for ii, ie in enumerate(pe.indx[:]): if (ie < 0) or (ie >= mesh.n_el): raise ValueError('element index 0 <= %d < %d!' % (ie, mesh.n_el)) pe.indx[ii] = ie ## # Extract data. io = MeshIO.any_from_filename(filename) ths = {} for pe in pes: mode, nname = io.read_data_header(pe.var) output(mode, nname, verbose=verbose) if ((pe.mode == 'n' and mode == 'vertex') or (pe.mode == 'e' and mode == 'cell')): th = io.read_time_history(nname, pe.indx) elif pe.mode == 'e' and mode == 'vertex': conn = mesh.conns[0] th = {} for iel in pe.indx: ips = conn[iel] th[iel] = io.read_time_history(nname, ips) else: raise ValueError('cannot extract cell data %s in nodes!' % pe.var) ths[pe.var] = th output('...done', verbose=verbose) ts = TimeStepper(*io.read_time_stepper()) return ths, ts def average_vertex_var_in_cells(ths_in): """Average histories in the element nodes for each nodal variable originally requested in elements.""" ths = dict.fromkeys(list(ths_in.keys())) for var, th in six.iteritems(ths_in): aux = dict.fromkeys(list(th.keys())) for ir, data in six.iteritems(th): if isinstance(data, dict): for ic, ndata in six.iteritems(data): if aux[ir] is None: aux[ir] = ndata else: aux[ir] += ndata aux[ir] /= float(len(data)) else: aux[ir] = data ths[var] = aux return ths def save_time_history(ths, ts, filename_out): """Save time history and time-stepping information in a HDF5 file.""" ths.update({'times' : ts.times, 'dt' : ts.dt})
write_dict_hdf5(filename_out, ths)
sfepy.base.ioutils.write_dict_hdf5
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk =
get_trunk(filename)
sfepy.base.ioutils.get_trunk
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk = get_trunk(filename) try: ts = TimeStepper(*io.read_time_stepper()) all_steps, times, nts, dts = extract_times(filename) except ValueError: output('no time stepping info found, assuming single step') out = io.read_data(0) if out is not None: _save_step('.vtk', out, mesh) ret = None else: ts.times = times ts.n_step = times.shape[0] if steps is None: ii0 = nm.searchsorted(all_steps, step0) iterator = ((all_steps[ii], times[ii]) for ii in range(ii0, len(times))) else: iterator = [(step, ts.times[step]) for step in steps] max_step = all_steps.max() for step, time in iterator: output(ts.format % (step, max_step)) out = io.read_data(step) if out is None: break _save_step('.' + ts.suffix % step + '.vtk', out, mesh) ret = ts.suffix output('...done') return ret def extract_times(filename): """ Read true time step data from individual time steps. Returns ------- steps : array The time steps. times : array The times of the time steps. nts : array The normalized times of the time steps, in [0, 1]. dts : array The true time deltas. """ io = MeshIO.any_from_filename(filename) steps, times, nts = io.read_times() dts = nm.ediff1d(times, to_end=0) return steps, times, nts, dts def extract_time_history(filename, extract, verbose=True): """Extract time history of a variable from a multi-time-step results file. Parameters ---------- filename : str The name of file to extract from. extract : str The description of what to extract in a string of comma-separated description items. A description item consists of: name of the variable to extract, mode ('e' for elements, 'n' for nodes), ids of the nodes or elements (given by the mode). Example: 'u n 10 15, p e 0' means variable 'u' in nodes 10, 15 and variable 'p' in element 0. verbose : bool Verbosity control. Returns ------- ths : dict The time histories in a dict with variable names as keys. If a nodal variable is requested in elements, its value is a dict of histories in the element nodes. ts : TimeStepper instance The time stepping information. """ output('extracting selected data...', verbose=verbose) output('selection:', extract, verbose=verbose) ## # Parse extractions. pes = OneTypeList(Struct) for chunk in extract.split(','): aux = chunk.strip().split() pes.append(Struct(var=aux[0], mode=aux[1], indx=map(int, aux[2:]))) ## # Verify array limits. mesh = Mesh.from_file(filename) for pe in pes: if pe.mode == 'n': for ii in pe.indx: if (ii < 0) or (ii >= mesh.n_nod): raise ValueError('node index 0 <= %d < %d!' % (ii, mesh.n_nod)) if pe.mode == 'e': for ii, ie in enumerate(pe.indx[:]): if (ie < 0) or (ie >= mesh.n_el): raise ValueError('element index 0 <= %d < %d!' % (ie, mesh.n_el)) pe.indx[ii] = ie ## # Extract data. io = MeshIO.any_from_filename(filename) ths = {} for pe in pes: mode, nname = io.read_data_header(pe.var)
output(mode, nname, verbose=verbose)
sfepy.base.base.output
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None:
output('linearizing...')
sfepy.base.base.output
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization)
output('...done')
sfepy.base.base.output
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk = get_trunk(filename) try: ts = TimeStepper(*io.read_time_stepper()) all_steps, times, nts, dts = extract_times(filename) except ValueError:
output('no time stepping info found, assuming single step')
sfepy.base.base.output
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'): output('max. refinement per group:', val.levels) else: mesh.write(output_filename_trunk + suffix, io='auto', out=out) output('dumping to VTK...') io = MeshIO.any_from_filename(filename) mesh = Mesh.from_file(filename, io=io) if output_filename_trunk is None: output_filename_trunk = get_trunk(filename) try: ts = TimeStepper(*io.read_time_stepper()) all_steps, times, nts, dts = extract_times(filename) except ValueError: output('no time stepping info found, assuming single step') out = io.read_data(0) if out is not None: _save_step('.vtk', out, mesh) ret = None else: ts.times = times ts.n_step = times.shape[0] if steps is None: ii0 = nm.searchsorted(all_steps, step0) iterator = ((all_steps[ii], times[ii]) for ii in range(ii0, len(times))) else: iterator = [(step, ts.times[step]) for step in steps] max_step = all_steps.max() for step, time in iterator:
output(ts.format % (step, max_step))
sfepy.base.base.output
from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, OneTypeList, Struct from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import MeshIO from sfepy.solvers.ts import TimeStepper from sfepy.base.ioutils import get_trunk, write_dict_hdf5 import six from six.moves import range def _linearize(out, fields, linearization): new = {} for key, val in six.iteritems(out): field = fields[val.field_name] new.update(field.create_output(val.data, var_name=key, dof_names=val.dofs, key=key, linearization=linearization)) return new def dump_to_vtk(filename, output_filename_trunk=None, step0=0, steps=None, fields=None, linearization=None): """Dump a multi-time-step results file into a sequence of VTK files.""" def _save_step(suffix, out, mesh): if linearization is not None: output('linearizing...') out = _linearize(out, fields, linearization) output('...done') for key, val in six.iteritems(out): lmesh = val.get('mesh', mesh) lmesh.write(output_filename_trunk + '_' + key + suffix, io='auto', out={key : val}) if hasattr(val, 'levels'):
output('max. refinement per group:', val.levels)
sfepy.base.base.output
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm = la.insert_strided_axis(mtx, 0, self.bounds.shape[0]) rbounds = la.dot_sequences(mm, self.bounds) bounds2d = rbounds[:, :2] assert_(nm.allclose(nm.dot(mtx, self.normal), e3, rtol=0.0, atol=1e-12)) self.adotn = nm.dot(self.anchor, self.normal) self.rot_angle = rot_angle self.mtx = mtx self.bounds2d = bounds2d def mask_points(self, points): mm = la.insert_strided_axis(self.mtx, 0, points.shape[0]) points2d = la.dot_sequences(mm, points)[:, :2] return la.flag_points_in_polygon2d(self.bounds2d, points2d) def get_distance(self, points): dist = la.dot_sequences(points, self.normal) - self.adotn return dist class ContactSphere(Struct): def __init__(self, centre, radius): self.centre = nm.asarray(centre) self.radius = radius def mask_points(self, points, eps): dist2 = la.norm_l2_along_axis(points - self.centre, squared=True) radius2 = self.radius**2 mask = dist2 <= ((1 + eps)**2) * radius2 return mask def get_distance(self, points): """ Get the penetration distance and normals of points w.r.t. the sphere surface. Returns ------- d : array The penetration distance. normals : array The normals from the points to the sphere centre. """ vecs = self.centre - points dist = la.norm_l2_along_axis(vecs) # Prevent zero division. ii = dist > 1e-8 normals = nm.where(ii[:, None], vecs[ii] / dist[ii][:, None], vecs[ii]) return self.radius - dist, normals def _get_derivatives(self, points): vecs = self.centre - points dist = la.norm_l2_along_axis(vecs) # Distance derivative w.r.t. point coordinates. dd = vecs / dist[:, None] normals = dd # Unit normal derivative w.r.t. point coordinates. dim = points.shape[1] ee = nm.eye(dim)[None, ...] nnt = normals[..., None] * normals[..., None, :] dn = - (ee - nnt) / dist[:, None, None] return dd, dn def plot_polygon(ax, polygon): from sfepy.postprocess.plot_dofs import _get_axes dim = polygon.shape[1] ax =
_get_axes(ax, dim)
sfepy.postprocess.plot_dofs._get_axes
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm = la.insert_strided_axis(mtx, 0, self.bounds.shape[0]) rbounds = la.dot_sequences(mm, self.bounds) bounds2d = rbounds[:, :2] assert_(nm.allclose(nm.dot(mtx, self.normal), e3, rtol=0.0, atol=1e-12)) self.adotn = nm.dot(self.anchor, self.normal) self.rot_angle = rot_angle self.mtx = mtx self.bounds2d = bounds2d def mask_points(self, points): mm = la.insert_strided_axis(self.mtx, 0, points.shape[0]) points2d = la.dot_sequences(mm, points)[:, :2] return la.flag_points_in_polygon2d(self.bounds2d, points2d) def get_distance(self, points): dist = la.dot_sequences(points, self.normal) - self.adotn return dist class ContactSphere(Struct): def __init__(self, centre, radius): self.centre = nm.asarray(centre) self.radius = radius def mask_points(self, points, eps): dist2 = la.norm_l2_along_axis(points - self.centre, squared=True) radius2 = self.radius**2 mask = dist2 <= ((1 + eps)**2) * radius2 return mask def get_distance(self, points): """ Get the penetration distance and normals of points w.r.t. the sphere surface. Returns ------- d : array The penetration distance. normals : array The normals from the points to the sphere centre. """ vecs = self.centre - points dist = la.norm_l2_along_axis(vecs) # Prevent zero division. ii = dist > 1e-8 normals = nm.where(ii[:, None], vecs[ii] / dist[ii][:, None], vecs[ii]) return self.radius - dist, normals def _get_derivatives(self, points): vecs = self.centre - points dist = la.norm_l2_along_axis(vecs) # Distance derivative w.r.t. point coordinates. dd = vecs / dist[:, None] normals = dd # Unit normal derivative w.r.t. point coordinates. dim = points.shape[1] ee = nm.eye(dim)[None, ...] nnt = normals[..., None] * normals[..., None, :] dn = - (ee - nnt) / dist[:, None, None] return dd, dn def plot_polygon(ax, polygon): from sfepy.postprocess.plot_dofs import _get_axes dim = polygon.shape[1] ax = _get_axes(ax, dim) pp = nm.r_[polygon, polygon[:1]] px, py = pp[:, 0], pp[:, 1] if dim == 2: ax.plot(px, py) else: pz = pp[:, 2] ax.plot(px, py, pz) return ax def plot_points(ax, points, marker, **kwargs): from sfepy.postprocess.plot_dofs import _get_axes dim = points.shape[1] ax =
_get_axes(ax, dim)
sfepy.postprocess.plot_dofs._get_axes
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm = la.insert_strided_axis(mtx, 0, self.bounds.shape[0]) rbounds = la.dot_sequences(mm, self.bounds) bounds2d = rbounds[:, :2] assert_(nm.allclose(nm.dot(mtx, self.normal), e3, rtol=0.0, atol=1e-12)) self.adotn = nm.dot(self.anchor, self.normal) self.rot_angle = rot_angle self.mtx = mtx self.bounds2d = bounds2d def mask_points(self, points): mm = la.insert_strided_axis(self.mtx, 0, points.shape[0]) points2d = la.dot_sequences(mm, points)[:, :2] return la.flag_points_in_polygon2d(self.bounds2d, points2d) def get_distance(self, points): dist = la.dot_sequences(points, self.normal) - self.adotn return dist class ContactSphere(Struct): def __init__(self, centre, radius): self.centre = nm.asarray(centre) self.radius = radius def mask_points(self, points, eps): dist2 = la.norm_l2_along_axis(points - self.centre, squared=True) radius2 = self.radius**2 mask = dist2 <= ((1 + eps)**2) * radius2 return mask def get_distance(self, points): """ Get the penetration distance and normals of points w.r.t. the sphere surface. Returns ------- d : array The penetration distance. normals : array The normals from the points to the sphere centre. """ vecs = self.centre - points dist = la.norm_l2_along_axis(vecs) # Prevent zero division. ii = dist > 1e-8 normals = nm.where(ii[:, None], vecs[ii] / dist[ii][:, None], vecs[ii]) return self.radius - dist, normals def _get_derivatives(self, points): vecs = self.centre - points dist = la.norm_l2_along_axis(vecs) # Distance derivative w.r.t. point coordinates. dd = vecs / dist[:, None] normals = dd # Unit normal derivative w.r.t. point coordinates. dim = points.shape[1] ee = nm.eye(dim)[None, ...] nnt = normals[..., None] * normals[..., None, :] dn = - (ee - nnt) / dist[:, None, None] return dd, dn def plot_polygon(ax, polygon): from sfepy.postprocess.plot_dofs import _get_axes dim = polygon.shape[1] ax = _get_axes(ax, dim) pp = nm.r_[polygon, polygon[:1]] px, py = pp[:, 0], pp[:, 1] if dim == 2: ax.plot(px, py) else: pz = pp[:, 2] ax.plot(px, py, pz) return ax def plot_points(ax, points, marker, **kwargs): from sfepy.postprocess.plot_dofs import _get_axes dim = points.shape[1] ax = _get_axes(ax, dim) px, py = points[:, 0], points[:, 1] if dim == 2: ax.plot(px, py, marker, **kwargs) else: pz = points[:, 2] ax.plot(px, py, pz, marker, **kwargs) return ax if __name__ == '__main__': import matplotlib.pyplot as plt # Test and draw the plane. anchor = [1, 1, 1] normal = [2, -1, 1] bounds = [[-2, 0, 0], [2, 1, 0], [4, 3, 1], [1, 3, 1], [2, 2, 1]] cp = ContactPlane(anchor, normal, bounds) pps = 2 * nm.random.rand(20, 3) mask = cp.mask_points(pps) dist = cp.get_distance(pps) v1, v2 =
la.get_perpendiculars(cp.normal)
sfepy.linalg.get_perpendiculars
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm = la.insert_strided_axis(mtx, 0, self.bounds.shape[0]) rbounds = la.dot_sequences(mm, self.bounds) bounds2d = rbounds[:, :2] assert_(nm.allclose(nm.dot(mtx, self.normal), e3, rtol=0.0, atol=1e-12)) self.adotn = nm.dot(self.anchor, self.normal) self.rot_angle = rot_angle self.mtx = mtx self.bounds2d = bounds2d def mask_points(self, points): mm =
la.insert_strided_axis(self.mtx, 0, points.shape[0])
sfepy.linalg.insert_strided_axis
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm = la.insert_strided_axis(mtx, 0, self.bounds.shape[0]) rbounds = la.dot_sequences(mm, self.bounds) bounds2d = rbounds[:, :2] assert_(nm.allclose(nm.dot(mtx, self.normal), e3, rtol=0.0, atol=1e-12)) self.adotn = nm.dot(self.anchor, self.normal) self.rot_angle = rot_angle self.mtx = mtx self.bounds2d = bounds2d def mask_points(self, points): mm = la.insert_strided_axis(self.mtx, 0, points.shape[0]) points2d = la.dot_sequences(mm, points)[:, :2] return
la.flag_points_in_polygon2d(self.bounds2d, points2d)
sfepy.linalg.flag_points_in_polygon2d
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm = la.insert_strided_axis(mtx, 0, self.bounds.shape[0]) rbounds = la.dot_sequences(mm, self.bounds) bounds2d = rbounds[:, :2] assert_(nm.allclose(nm.dot(mtx, self.normal), e3, rtol=0.0, atol=1e-12)) self.adotn = nm.dot(self.anchor, self.normal) self.rot_angle = rot_angle self.mtx = mtx self.bounds2d = bounds2d def mask_points(self, points): mm = la.insert_strided_axis(self.mtx, 0, points.shape[0]) points2d = la.dot_sequences(mm, points)[:, :2] return la.flag_points_in_polygon2d(self.bounds2d, points2d) def get_distance(self, points): dist = la.dot_sequences(points, self.normal) - self.adotn return dist class ContactSphere(Struct): def __init__(self, centre, radius): self.centre = nm.asarray(centre) self.radius = radius def mask_points(self, points, eps): dist2 =
la.norm_l2_along_axis(points - self.centre, squared=True)
sfepy.linalg.norm_l2_along_axis
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm = la.insert_strided_axis(mtx, 0, self.bounds.shape[0]) rbounds = la.dot_sequences(mm, self.bounds) bounds2d = rbounds[:, :2] assert_(nm.allclose(nm.dot(mtx, self.normal), e3, rtol=0.0, atol=1e-12)) self.adotn = nm.dot(self.anchor, self.normal) self.rot_angle = rot_angle self.mtx = mtx self.bounds2d = bounds2d def mask_points(self, points): mm = la.insert_strided_axis(self.mtx, 0, points.shape[0]) points2d = la.dot_sequences(mm, points)[:, :2] return la.flag_points_in_polygon2d(self.bounds2d, points2d) def get_distance(self, points): dist = la.dot_sequences(points, self.normal) - self.adotn return dist class ContactSphere(Struct): def __init__(self, centre, radius): self.centre = nm.asarray(centre) self.radius = radius def mask_points(self, points, eps): dist2 = la.norm_l2_along_axis(points - self.centre, squared=True) radius2 = self.radius**2 mask = dist2 <= ((1 + eps)**2) * radius2 return mask def get_distance(self, points): """ Get the penetration distance and normals of points w.r.t. the sphere surface. Returns ------- d : array The penetration distance. normals : array The normals from the points to the sphere centre. """ vecs = self.centre - points dist =
la.norm_l2_along_axis(vecs)
sfepy.linalg.norm_l2_along_axis
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm = la.insert_strided_axis(mtx, 0, self.bounds.shape[0]) rbounds = la.dot_sequences(mm, self.bounds) bounds2d = rbounds[:, :2] assert_(nm.allclose(nm.dot(mtx, self.normal), e3, rtol=0.0, atol=1e-12)) self.adotn = nm.dot(self.anchor, self.normal) self.rot_angle = rot_angle self.mtx = mtx self.bounds2d = bounds2d def mask_points(self, points): mm = la.insert_strided_axis(self.mtx, 0, points.shape[0]) points2d = la.dot_sequences(mm, points)[:, :2] return la.flag_points_in_polygon2d(self.bounds2d, points2d) def get_distance(self, points): dist = la.dot_sequences(points, self.normal) - self.adotn return dist class ContactSphere(Struct): def __init__(self, centre, radius): self.centre = nm.asarray(centre) self.radius = radius def mask_points(self, points, eps): dist2 = la.norm_l2_along_axis(points - self.centre, squared=True) radius2 = self.radius**2 mask = dist2 <= ((1 + eps)**2) * radius2 return mask def get_distance(self, points): """ Get the penetration distance and normals of points w.r.t. the sphere surface. Returns ------- d : array The penetration distance. normals : array The normals from the points to the sphere centre. """ vecs = self.centre - points dist = la.norm_l2_along_axis(vecs) # Prevent zero division. ii = dist > 1e-8 normals = nm.where(ii[:, None], vecs[ii] / dist[ii][:, None], vecs[ii]) return self.radius - dist, normals def _get_derivatives(self, points): vecs = self.centre - points dist =
la.norm_l2_along_axis(vecs)
sfepy.linalg.norm_l2_along_axis
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx =
la.make_axis_rotation_matrix(rot_axis, rot_angle)
sfepy.linalg.make_axis_rotation_matrix
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm =
la.insert_strided_axis(mtx, 0, self.bounds.shape[0])
sfepy.linalg.insert_strided_axis
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm = la.insert_strided_axis(mtx, 0, self.bounds.shape[0]) rbounds =
la.dot_sequences(mm, self.bounds)
sfepy.linalg.dot_sequences
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm = la.insert_strided_axis(mtx, 0, self.bounds.shape[0]) rbounds = la.dot_sequences(mm, self.bounds) bounds2d = rbounds[:, :2] assert_(nm.allclose(nm.dot(mtx, self.normal), e3, rtol=0.0, atol=1e-12)) self.adotn = nm.dot(self.anchor, self.normal) self.rot_angle = rot_angle self.mtx = mtx self.bounds2d = bounds2d def mask_points(self, points): mm = la.insert_strided_axis(self.mtx, 0, points.shape[0]) points2d =
la.dot_sequences(mm, points)
sfepy.linalg.dot_sequences
import numpy as nm from sfepy.base.base import assert_, Struct import sfepy.linalg as la class ContactPlane(Struct): def __init__(self, anchor, normal, bounds): Struct.__init__(self, anchor=nm.array(anchor, dtype=nm.float64), bounds=nm.asarray(bounds, dtype=nm.float64)) self.normal = nm.asarray(normal, dtype=nm.float64) norm = nm.linalg.norm self.normal /= norm(self.normal) e3 = [0.0, 0.0, 1.0] dd = nm.dot(e3, self.normal) rot_angle = nm.arccos(dd) if nm.abs(rot_angle) < 1e-14: mtx = nm.eye(3, dtype=nm.float64) bounds2d = self.bounds[:, :2] else: rot_axis = nm.cross([0.0, 0.0, 1.0], self.normal) mtx = la.make_axis_rotation_matrix(rot_axis, rot_angle) mm = la.insert_strided_axis(mtx, 0, self.bounds.shape[0]) rbounds = la.dot_sequences(mm, self.bounds) bounds2d = rbounds[:, :2] assert_(nm.allclose(nm.dot(mtx, self.normal), e3, rtol=0.0, atol=1e-12)) self.adotn = nm.dot(self.anchor, self.normal) self.rot_angle = rot_angle self.mtx = mtx self.bounds2d = bounds2d def mask_points(self, points): mm = la.insert_strided_axis(self.mtx, 0, points.shape[0]) points2d = la.dot_sequences(mm, points)[:, :2] return la.flag_points_in_polygon2d(self.bounds2d, points2d) def get_distance(self, points): dist =
la.dot_sequences(points, self.normal)
sfepy.linalg.dot_sequences
#!/usr/bin/env python # 12.01.2007, c import os.path as op import shutil from optparse import OptionParser import sfepy from sfepy.base.base import * from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.fem import ProblemDefinition from sfepy.fem.evaluate import assemble_by_blocks from sfepy.homogenization.phono import transform_plot_data, plot_logs, \ plot_gaps, detect_band_gaps, compute_cat, compute_polarization_angles from sfepy.homogenization.engine import HomogenizationEngine from sfepy.applications import SimpleApp from sfepy.solvers import Solver, eig from sfepy.base.plotutils import plt def make_save_hook( base_name, post_process_hook = None, file_per_var = None ): def save_phono_correctors( state, problem, ir, ic ): problem.save_state( (base_name % (ir, ic)) + '.vtk', state, post_process_hook = post_process_hook, file_per_var = file_per_var ) return save_phono_correctors def try_set_defaults( obj, attr, defaults ): try: values = getattr( obj, attr ) set_defaults( values, defaults ) except: values = defaults return values def report_iw_cat( iw_dir, christoffel ): output( 'incident wave direction:' ) output( iw_dir ) output( 'Christoffel acoustic tensor:' ) output( christoffel ) class AcousticBandGapsApp( SimpleApp ): def process_options( options ): """Application options setup. Sets default values for missing non-compulsory options.""" get = options.get_default_attr clear_cache = get( 'clear_cache', {} ) eigensolver = get( 'eigensolver', 'eig.sgscipy' ) eig_problem = get( 'eig_problem', 'simple' ) schur = get( 'schur', None ) elasticity_contrast = get( 'elasticity_contrast', 1.0 ) scale_epsilon = get( 'scale_epsilon', 1.0 ) incident_wave_dir = get( 'incident_wave_dir', None ) dispersion = get( 'dispersion', 'simple' ) dispersion_conf = get( 'dispersion_conf', None ) homogeneous = get( 'homogeneous', False ) save = get( 'save_eig_vectors', (0, 0) ) eig_range = get( 'eig_range', None ) freq_margins = get( 'freq_margins', (5, 5) ) # Given in per cent. freq_margins = 0.01 * nm.array( freq_margins, dtype = nm.float64 ) fixed_eig_range = get( 'fixed_eig_range', None ) # Given in per cent. freq_step = 0.01 * get( 'freq_step', 5 ) feps = get( 'feps', 1e-8 ) zeps = get( 'zeps', 1e-8 ) teps = get( 'teps', 1e-4 ) teps_rel = get( 'teps_rel', True ) eig_vector_transform = get( 'eig_vector_transform', 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', {'show' : True,'legend' : False,} ) fig_name = get( 'fig_name', None ) fig_name_wave = get( 'fig_name_wave', None ) fig_name_angle = get( 'fig_name_angle', None ) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : 'min eig($M^*$)', 'eig_mid' : 'mid eig($M^*$)', 'eig_max' : 'max eig($M^*$)', 'y_axis' : 'eigenvalues of mass matrix $M^*$', } plot_labels = try_set_defaults( options, 'plot_labels', aux ) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'$\kappa$(min)', 'eig_mid' : r'$\kappa$(mid)', 'eig_max' : r'$\kappa$(max)', '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)', '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' : 0.5, 'color' : 'b', 'linestyle' : '--' }, 'eig_mid' : {'linewidth' : 0.5, 'color' : 'b', 'linestyle' : '-.' }, 'eig_max' : {'linewidth' : 0.5, 'color' : 'b', 'linestyle' : '-' }, 'strong_gap' : {'linewidth' : 0, 'facecolor' : (1, 1, 0.5) }, 'weak_gap' : {'linewidth' : 0, 'facecolor' : (1, 1, 1) }, 'propagation' : {'linewidth' : 0, 'facecolor' : (0.5, 1, 0.5) }, 'params' : {'axes.labelsize': 'large', 'text.fontsize': 'large', 'legend.fontsize': 'large', 'xtick.labelsize': 'large', 'ytick.labelsize': 'large', 'text.usetex': False}, } plot_rsc = try_set_defaults( options, 'plot_rsc', plot_rsc ) eigenmomentum = get( 'eigenmomentum', None, 'missing "eigenmomentum" in options!' ) region_to_material = get( 'region_to_material', None, 'missing "region_to_material" in options!' ) tensor_names = get( 'tensor_names', None, 'missing "tensor_names" in options!' ) volume = get( 'volume', None, 'missing "volume" in options!' ) if eig_problem == 'simple_liquid': liquid_region = get('liquid_region', None, 'missing "liquid_region" in options!') else: liquid_region = None return Struct( **locals() ) process_options = staticmethod( process_options ) def process_options_pv( options ): """Application options setup for phase velocity computation. Sets default values for missing non-compulsory options.""" get = options.get_default_attr clear_cache = get( 'clear_cache', {} ) eigensolver = get( 'eigensolver', 'eig.sgscipy' ) incident_wave_dir = get( 'incident_wave_dir', None ) dispersion = get( 'dispersion', 'simple' ) dispersion_conf = get( 'dispersion_conf', None ) homogeneous = get( 'homogeneous', False ) fig_suffix = get( 'fig_suffix', '.pdf' ) region_to_material = get( 'region_to_material', None, 'missing "region_to_material" in options!' ) tensor_names = get( 'tensor_names', None, 'missing "tensor_names" in options!' ) volume = get( 'volume', None, 'missing "volume" in options!' ) return Struct( **locals() ) process_options_pv = staticmethod( process_options_pv ) def __init__( self, conf, options, output_prefix, **kwargs ): SimpleApp.__init__( self, conf, options, output_prefix, init_equations = False ) self.setup_options() self.cached_coefs = None self.cached_iw_dir = None self.cached_christoffel = None self.cached_evp = None output_dir = self.problem.output_dir shutil.copyfile( conf._filename, op.join( output_dir, op.basename( conf._filename ) ) ) def setup_options( self ): SimpleApp.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 ): """In parametric runs, cached data (homogenized coefficients, Christoffel acoustic tensor and eigenvalue problem solution) are cleared according to 'clear_cache' aplication options. Example: clear_cache = {'cached_christoffel' : True, 'cached_evp' : True} """ options = self.options for key, val in self.app_options.clear_cache.iteritems(): if val and key.startswith('cached_'): setattr(self, key, None) if options.phase_velocity: # No band gaps in this case. return self.compute_phase_velocity() evp = self.solve_eigen_problem() self.fix_eig_range( evp.eigs.shape[0] ) if options.detect_band_gaps: bg = detect_band_gaps( self.problem, evp.kind, evp.eigs_rescaled, evp.eig_vectors, self.app_options, self.conf.funmod ) if options.plot: plot_range, teigs = transform_plot_data( bg.logs.eigs, bg.opts.plot_transform, self.conf.funmod ) plot_rsc = bg.opts.plot_rsc plot_opts = bg.opts.plot_options plot_labels = bg.opts.plot_labels plt.rcParams.update( plot_rsc['params'] ) fig = plot_gaps( 1, plot_rsc, bg.gaps, bg.kinds, bg.freq_range_margins, plot_range, clear = True ) fig = plot_logs( 1, plot_rsc, plot_labels, bg.logs.freqs, teigs, bg.valid[bg.eig_range], bg.freq_range_initial, plot_range, False, show_legend = plot_opts['legend'], new_axes = True ) fig_name = bg.opts.fig_name if fig_name is not None: fig.savefig( fig_name ) if plot_opts['show']: plt.show() elif options.analyze_dispersion: christoffel, iw_dir = self.compute_cat(ret_iw_dir=True) bg = detect_band_gaps( self.problem, evp.kind, evp.eigs_rescaled, evp.eig_vectors, self.app_options, self.conf.funmod, christoffel = christoffel ) output( 'computing polarization angles...' ) pas = compute_polarization_angles( iw_dir, bg.logs.eig_vectors ) output( '...done' ) bg.polarization_angles = pas output( 'computing phase velocity...' ) bg.phase_velocity = self.compute_phase_velocity() output( '...done' ) if options.plot: plot_rsc = bg.opts.plot_rsc plot_opts = bg.opts.plot_options plt.rcParams.update( plot_rsc['params'] ) aux = transform_plot_data( pas, bg.opts.plot_transform_angle, self.conf.funmod ) plot_range, pas = aux plot_labels = bg.opts.plot_labels_angle fig = plot_gaps( 1, plot_rsc, bg.gaps, bg.kinds, 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, False, show_legend = plot_opts['legend'], new_axes = True ) fig_name = bg.opts.fig_name_angle if fig_name is not None: fig.savefig( fig_name ) aux = transform_plot_data( bg.logs.eigs, bg.opts.plot_transform_wave, self.conf.funmod ) plot_range, teigs = aux plot_labels = bg.opts.plot_labels_wave fig = plot_gaps( 2, plot_rsc, bg.gaps, bg.kinds, 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, False, show_legend = plot_opts['legend'], new_axes = True ) fig_name = bg.opts.fig_name_wave if fig_name is not None: fig.savefig( fig_name ) if plot_opts['show']: plt.show() else: bg = None return evp, bg def fix_eig_range( self, n_eigs ): eig_range = get_default( self.app_options.eig_range, (0, n_eigs) ) if eig_range[-1] < 0: eig_range[-1] += n_eigs + 1 assert_( eig_range[0] < (eig_range[1] - 1) ) assert_( eig_range[1] <= n_eigs ) self.app_options.eig_range = eig_range def solve_eigen_problem( self, ofn_trunk = None, post_process_hook = None ): if self.cached_evp is not None: return self.cached_evp problem = self.problem ofn_trunk = get_default( ofn_trunk, problem.ofn_trunk, 'output file name trunk missing!' ) post_process_hook = get_default( post_process_hook, self.post_process_hook ) conf = self.conf eig_problem = self.app_options.eig_problem if eig_problem in ['simple', 'simple_liquid']: problem.set_equations( conf.equations ) problem.time_update() mtx_a = problem.evaluate(conf.equations['lhs'], mode='weak', auto_init=True, dw_mode='matrix') mtx_m = problem.evaluate(conf.equations['rhs'], mode='weak', dw_mode='matrix') elif eig_problem == 'schur': # A = K + B^T D^{-1} B. mtx = assemble_by_blocks( conf.equations, self.problem, ebcs = conf.ebcs, epbcs = conf.epbcs ) problem.set_equations( conf.equations ) problem.time_update() ls = Solver.any_from_conf( problem.ls_conf, presolve = True, mtx = mtx['D'] ) mtx_b, mtx_m = mtx['B'], mtx['M'] mtx_dib = nm.empty( mtx_b.shape, dtype = mtx_b.dtype ) for ic in xrange( mtx_b.shape[1] ): mtx_dib[:,ic] = ls( mtx_b[:,ic].toarray().squeeze() ) mtx_a = mtx['K'] + mtx_b.T * mtx_dib else: raise NotImplementedError ## from sfepy.base.plotutils import spy, plt ## spy( mtx_b, eps = 1e-12 ) ## plt.show() ## mtx_a.save( 'a.txt', format='%d %d %.12f\n' ) ## mtx_b.save( 'b.txt', format='%d %d %.12f\n' ) ## pause() output( 'computing resonance frequencies...' ) tt = [0] if isinstance( mtx_a, sc.sparse.spmatrix ): mtx_a = mtx_a.toarray() if isinstance( mtx_m, sc.sparse.spmatrix ): mtx_m = mtx_m.toarray() eigs, mtx_s_phi = eig(mtx_a, mtx_m, return_time=tt, method=self.app_options.eigensolver) eigs[eigs<0.0] = 0.0 output( '...done in %.2f s' % tt[0] ) output( 'original eigenfrequencies:' ) output( eigs ) opts = self.app_options epsilon2 = opts.scale_epsilon * opts.scale_epsilon eigs_rescaled = (opts.elasticity_contrast / epsilon2) * eigs output( 'rescaled eigenfrequencies:' ) output( eigs_rescaled ) output( 'number of eigenfrequencies: %d' % eigs.shape[0] ) try: assert_( nm.isfinite( eigs ).all() ) except ValueError: debug() # B-orthogonality check. ## print nm.dot( mtx_s_phi[:,5], nm.dot( mtx_m, mtx_s_phi[:,5] ) ) ## print nm.dot( mtx_s_phi[:,5], nm.dot( mtx_m, mtx_s_phi[:,0] ) ) ## debug() n_eigs = eigs.shape[0] variables = problem.get_variables() mtx_phi = nm.empty( (variables.di.ptr[-1], mtx_s_phi.shape[1]), dtype = nm.float64 ) make_full = variables.make_full_vec if eig_problem in ['simple', 'simple_liquid']: for ii in xrange( n_eigs ): mtx_phi[:,ii] = make_full( mtx_s_phi[:,ii] ) eig_vectors = mtx_phi elif eig_problem == 'schur': # Update also eliminated variables. schur = self.app_options.schur primary_var = schur['primary_var'] eliminated_var = schur['eliminated_var'] mtx_s_phi_schur = - sc.dot( mtx_dib, mtx_s_phi ) aux = nm.empty( (variables.adi.ptr[-1],), dtype = nm.float64 ) set = variables.set_state_part for ii in xrange( n_eigs ): set( aux, mtx_s_phi[:,ii], primary_var, stripped = True ) set( aux, mtx_s_phi_schur[:,ii], eliminated_var, stripped = True ) mtx_phi[:,ii] = make_full( aux ) indx = variables.get_indx( primary_var ) eig_vectors = mtx_phi[indx,:] save = self.app_options.save out = {} for ii in xrange( n_eigs ): if (ii >= save[0]) and (ii < (n_eigs - save[1])): continue aux = problem.state_to_output( mtx_phi[:,ii] ) for name, val in aux.iteritems(): out[name+'%03d' % ii] = val if post_process_hook is not None: out = post_process_hook( out, problem, mtx_phi ) problem.domain.mesh.write( ofn_trunk + '.vtk', io = 'auto', out = out ) fd = open( ofn_trunk + '_eigs.txt', 'w' ) eigs.tofile( fd, ' ' ) fd.close() evp = Struct( kind = eig_problem, eigs = eigs, eigs_rescaled = eigs_rescaled, eig_vectors = eig_vectors ) self.cached_evp = evp return evp def eval_homogenized_coefs( self ): if self.cached_coefs is not None: return self.cached_coefs opts = self.app_options if opts.homogeneous: rtm = opts.region_to_material mat_region = rtm.keys()[0] mat_name = rtm[mat_region] self.problem.update_materials() mat = self.problem.materials[mat_name] coefs = mat.get_data( mat_region, 0, opts.tensor_names ) else: dc = opts.dispersion_conf dconf = ProblemConf.from_dict( dc['input'], dc['module'] ) dconf.materials = self.conf.materials dconf.fe = self.conf.fe dconf.regions.update( self.conf.regions ) dconf.options['output_dir'] = self.problem.output_dir volume = opts.volume(self.problem, 'Y') problem = ProblemDefinition.from_conf(dconf, init_equations=False) he = HomogenizationEngine( problem, self.options, volume = volume ) coefs = he() ## print coefs ## pause() output.prefix = self.output_prefix self.cached_coefs = coefs return coefs def compute_cat( self, ret_iw_dir=False ): """Compute the Christoffel acoustic tensor, given the incident wave direction.""" opts = self.app_options iw_dir = nm.array( opts.incident_wave_dir, dtype = nm.float64 ) dim = self.problem.get_dim() assert_( dim == iw_dir.shape[0] ) iw_dir = iw_dir / nla.norm( iw_dir ) if self.cached_christoffel is not None: christoffel = self.cached_christoffel else: coefs = self.eval_homogenized_coefs() christoffel = compute_cat( coefs, iw_dir, self.app_options.dispersion ) report_iw_cat( iw_dir, christoffel ) self.cached_christoffel = christoffel if ret_iw_dir: return christoffel, iw_dir else: return christoffel def compute_phase_velocity( self ): from sfepy.homogenization.phono import compute_density_volume_info opts = self.app_options dim = self.problem.domain.mesh.dim christoffel = self.compute_cat() self.problem.update_materials() dv_info = compute_density_volume_info( self.problem, opts.volume, opts.region_to_material ) output( 'average density:', dv_info.average_density ) eye = nm.eye( dim, dim, dtype = nm.float64 ) mtx_mass = eye * dv_info.average_density meigs, mvecs = eig( mtx_mass, mtx_b = christoffel, eigenvectors = True, method = opts.eigensolver ) phase_velocity = 1.0 / nm.sqrt( meigs ) return phase_velocity usage = """%prog [options] filename_in""" help = { '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 = OptionParser(usage = usage, version = "%prog " + sfepy.__version__) parser.add_option( "-o", "", metavar = 'filename', action = "store", dest = "output_filename_trunk", default = None, help = help['filename'] ) parser.add_option( "-b", "--band-gaps", action = "store_true", dest = "detect_band_gaps", default = False, help = help['detect_band_gaps'] ) parser.add_option( "-d", "--dispersion", action = "store_true", dest = "analyze_dispersion", default = False, help = help['analyze_dispersion'] ) parser.add_option( "-p", "--plot", action = "store_true", dest = "plot", default = False, help = help['plot'] ) parser.add_option( "--phase-velocity", action = "store_true", dest = "phase_velocity", default = False, help = help['phase_velocity'] ) options, args = parser.parse_args() 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 if (len( args ) == 1): filename_in = args[0]; else: parser.print_help(), return required, other =
get_standard_keywords()
sfepy.base.conf.get_standard_keywords
#!/usr/bin/env python # 12.01.2007, c import os.path as op import shutil from optparse import OptionParser import sfepy from sfepy.base.base import * from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.fem import ProblemDefinition from sfepy.fem.evaluate import assemble_by_blocks from sfepy.homogenization.phono import transform_plot_data, plot_logs, \ plot_gaps, detect_band_gaps, compute_cat, compute_polarization_angles from sfepy.homogenization.engine import HomogenizationEngine from sfepy.applications import SimpleApp from sfepy.solvers import Solver, eig from sfepy.base.plotutils import plt def make_save_hook( base_name, post_process_hook = None, file_per_var = None ): def save_phono_correctors( state, problem, ir, ic ): problem.save_state( (base_name % (ir, ic)) + '.vtk', state, post_process_hook = post_process_hook, file_per_var = file_per_var ) return save_phono_correctors def try_set_defaults( obj, attr, defaults ): try: values = getattr( obj, attr ) set_defaults( values, defaults ) except: values = defaults return values def report_iw_cat( iw_dir, christoffel ): output( 'incident wave direction:' ) output( iw_dir ) output( 'Christoffel acoustic tensor:' ) output( christoffel ) class AcousticBandGapsApp( SimpleApp ): def process_options( options ): """Application options setup. Sets default values for missing non-compulsory options.""" get = options.get_default_attr clear_cache = get( 'clear_cache', {} ) eigensolver = get( 'eigensolver', 'eig.sgscipy' ) eig_problem = get( 'eig_problem', 'simple' ) schur = get( 'schur', None ) elasticity_contrast = get( 'elasticity_contrast', 1.0 ) scale_epsilon = get( 'scale_epsilon', 1.0 ) incident_wave_dir = get( 'incident_wave_dir', None ) dispersion = get( 'dispersion', 'simple' ) dispersion_conf = get( 'dispersion_conf', None ) homogeneous = get( 'homogeneous', False ) save = get( 'save_eig_vectors', (0, 0) ) eig_range = get( 'eig_range', None ) freq_margins = get( 'freq_margins', (5, 5) ) # Given in per cent. freq_margins = 0.01 * nm.array( freq_margins, dtype = nm.float64 ) fixed_eig_range = get( 'fixed_eig_range', None ) # Given in per cent. freq_step = 0.01 * get( 'freq_step', 5 ) feps = get( 'feps', 1e-8 ) zeps = get( 'zeps', 1e-8 ) teps = get( 'teps', 1e-4 ) teps_rel = get( 'teps_rel', True ) eig_vector_transform = get( 'eig_vector_transform', 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', {'show' : True,'legend' : False,} ) fig_name = get( 'fig_name', None ) fig_name_wave = get( 'fig_name_wave', None ) fig_name_angle = get( 'fig_name_angle', None ) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : 'min eig($M^*$)', 'eig_mid' : 'mid eig($M^*$)', 'eig_max' : 'max eig($M^*$)', 'y_axis' : 'eigenvalues of mass matrix $M^*$', } plot_labels = try_set_defaults( options, 'plot_labels', aux ) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'$\kappa$(min)', 'eig_mid' : r'$\kappa$(mid)', 'eig_max' : r'$\kappa$(max)', '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)', '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' : 0.5, 'color' : 'b', 'linestyle' : '--' }, 'eig_mid' : {'linewidth' : 0.5, 'color' : 'b', 'linestyle' : '-.' }, 'eig_max' : {'linewidth' : 0.5, 'color' : 'b', 'linestyle' : '-' }, 'strong_gap' : {'linewidth' : 0, 'facecolor' : (1, 1, 0.5) }, 'weak_gap' : {'linewidth' : 0, 'facecolor' : (1, 1, 1) }, 'propagation' : {'linewidth' : 0, 'facecolor' : (0.5, 1, 0.5) }, 'params' : {'axes.labelsize': 'large', 'text.fontsize': 'large', 'legend.fontsize': 'large', 'xtick.labelsize': 'large', 'ytick.labelsize': 'large', 'text.usetex': False}, } plot_rsc = try_set_defaults( options, 'plot_rsc', plot_rsc ) eigenmomentum = get( 'eigenmomentum', None, 'missing "eigenmomentum" in options!' ) region_to_material = get( 'region_to_material', None, 'missing "region_to_material" in options!' ) tensor_names = get( 'tensor_names', None, 'missing "tensor_names" in options!' ) volume = get( 'volume', None, 'missing "volume" in options!' ) if eig_problem == 'simple_liquid': liquid_region = get('liquid_region', None, 'missing "liquid_region" in options!') else: liquid_region = None return Struct( **locals() ) process_options = staticmethod( process_options ) def process_options_pv( options ): """Application options setup for phase velocity computation. Sets default values for missing non-compulsory options.""" get = options.get_default_attr clear_cache = get( 'clear_cache', {} ) eigensolver = get( 'eigensolver', 'eig.sgscipy' ) incident_wave_dir = get( 'incident_wave_dir', None ) dispersion = get( 'dispersion', 'simple' ) dispersion_conf = get( 'dispersion_conf', None ) homogeneous = get( 'homogeneous', False ) fig_suffix = get( 'fig_suffix', '.pdf' ) region_to_material = get( 'region_to_material', None, 'missing "region_to_material" in options!' ) tensor_names = get( 'tensor_names', None, 'missing "tensor_names" in options!' ) volume = get( 'volume', None, 'missing "volume" in options!' ) return Struct( **locals() ) process_options_pv = staticmethod( process_options_pv ) def __init__( self, conf, options, output_prefix, **kwargs ): SimpleApp.__init__( self, conf, options, output_prefix, init_equations = False ) self.setup_options() self.cached_coefs = None self.cached_iw_dir = None self.cached_christoffel = None self.cached_evp = None output_dir = self.problem.output_dir shutil.copyfile( conf._filename, op.join( output_dir, op.basename( conf._filename ) ) ) def setup_options( self ): SimpleApp.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 ): """In parametric runs, cached data (homogenized coefficients, Christoffel acoustic tensor and eigenvalue problem solution) are cleared according to 'clear_cache' aplication options. Example: clear_cache = {'cached_christoffel' : True, 'cached_evp' : True} """ options = self.options for key, val in self.app_options.clear_cache.iteritems(): if val and key.startswith('cached_'): setattr(self, key, None) if options.phase_velocity: # No band gaps in this case. return self.compute_phase_velocity() evp = self.solve_eigen_problem() self.fix_eig_range( evp.eigs.shape[0] ) if options.detect_band_gaps: bg = detect_band_gaps( self.problem, evp.kind, evp.eigs_rescaled, evp.eig_vectors, self.app_options, self.conf.funmod ) if options.plot: plot_range, teigs = transform_plot_data( bg.logs.eigs, bg.opts.plot_transform, self.conf.funmod ) plot_rsc = bg.opts.plot_rsc plot_opts = bg.opts.plot_options plot_labels = bg.opts.plot_labels plt.rcParams.update( plot_rsc['params'] ) fig = plot_gaps( 1, plot_rsc, bg.gaps, bg.kinds, bg.freq_range_margins, plot_range, clear = True ) fig = plot_logs( 1, plot_rsc, plot_labels, bg.logs.freqs, teigs, bg.valid[bg.eig_range], bg.freq_range_initial, plot_range, False, show_legend = plot_opts['legend'], new_axes = True ) fig_name = bg.opts.fig_name if fig_name is not None: fig.savefig( fig_name ) if plot_opts['show']: plt.show() elif options.analyze_dispersion: christoffel, iw_dir = self.compute_cat(ret_iw_dir=True) bg = detect_band_gaps( self.problem, evp.kind, evp.eigs_rescaled, evp.eig_vectors, self.app_options, self.conf.funmod, christoffel = christoffel ) output( 'computing polarization angles...' ) pas = compute_polarization_angles( iw_dir, bg.logs.eig_vectors ) output( '...done' ) bg.polarization_angles = pas output( 'computing phase velocity...' ) bg.phase_velocity = self.compute_phase_velocity() output( '...done' ) if options.plot: plot_rsc = bg.opts.plot_rsc plot_opts = bg.opts.plot_options plt.rcParams.update( plot_rsc['params'] ) aux = transform_plot_data( pas, bg.opts.plot_transform_angle, self.conf.funmod ) plot_range, pas = aux plot_labels = bg.opts.plot_labels_angle fig = plot_gaps( 1, plot_rsc, bg.gaps, bg.kinds, 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, False, show_legend = plot_opts['legend'], new_axes = True ) fig_name = bg.opts.fig_name_angle if fig_name is not None: fig.savefig( fig_name ) aux = transform_plot_data( bg.logs.eigs, bg.opts.plot_transform_wave, self.conf.funmod ) plot_range, teigs = aux plot_labels = bg.opts.plot_labels_wave fig = plot_gaps( 2, plot_rsc, bg.gaps, bg.kinds, 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, False, show_legend = plot_opts['legend'], new_axes = True ) fig_name = bg.opts.fig_name_wave if fig_name is not None: fig.savefig( fig_name ) if plot_opts['show']: plt.show() else: bg = None return evp, bg def fix_eig_range( self, n_eigs ): eig_range = get_default( self.app_options.eig_range, (0, n_eigs) ) if eig_range[-1] < 0: eig_range[-1] += n_eigs + 1 assert_( eig_range[0] < (eig_range[1] - 1) ) assert_( eig_range[1] <= n_eigs ) self.app_options.eig_range = eig_range def solve_eigen_problem( self, ofn_trunk = None, post_process_hook = None ): if self.cached_evp is not None: return self.cached_evp problem = self.problem ofn_trunk = get_default( ofn_trunk, problem.ofn_trunk, 'output file name trunk missing!' ) post_process_hook = get_default( post_process_hook, self.post_process_hook ) conf = self.conf eig_problem = self.app_options.eig_problem if eig_problem in ['simple', 'simple_liquid']: problem.set_equations( conf.equations ) problem.time_update() mtx_a = problem.evaluate(conf.equations['lhs'], mode='weak', auto_init=True, dw_mode='matrix') mtx_m = problem.evaluate(conf.equations['rhs'], mode='weak', dw_mode='matrix') elif eig_problem == 'schur': # A = K + B^T D^{-1} B. mtx = assemble_by_blocks( conf.equations, self.problem, ebcs = conf.ebcs, epbcs = conf.epbcs ) problem.set_equations( conf.equations ) problem.time_update() ls = Solver.any_from_conf( problem.ls_conf, presolve = True, mtx = mtx['D'] ) mtx_b, mtx_m = mtx['B'], mtx['M'] mtx_dib = nm.empty( mtx_b.shape, dtype = mtx_b.dtype ) for ic in xrange( mtx_b.shape[1] ): mtx_dib[:,ic] = ls( mtx_b[:,ic].toarray().squeeze() ) mtx_a = mtx['K'] + mtx_b.T * mtx_dib else: raise NotImplementedError ## from sfepy.base.plotutils import spy, plt ## spy( mtx_b, eps = 1e-12 ) ## plt.show() ## mtx_a.save( 'a.txt', format='%d %d %.12f\n' ) ## mtx_b.save( 'b.txt', format='%d %d %.12f\n' ) ## pause() output( 'computing resonance frequencies...' ) tt = [0] if isinstance( mtx_a, sc.sparse.spmatrix ): mtx_a = mtx_a.toarray() if isinstance( mtx_m, sc.sparse.spmatrix ): mtx_m = mtx_m.toarray() eigs, mtx_s_phi = eig(mtx_a, mtx_m, return_time=tt, method=self.app_options.eigensolver) eigs[eigs<0.0] = 0.0 output( '...done in %.2f s' % tt[0] ) output( 'original eigenfrequencies:' ) output( eigs ) opts = self.app_options epsilon2 = opts.scale_epsilon * opts.scale_epsilon eigs_rescaled = (opts.elasticity_contrast / epsilon2) * eigs output( 'rescaled eigenfrequencies:' ) output( eigs_rescaled ) output( 'number of eigenfrequencies: %d' % eigs.shape[0] ) try: assert_( nm.isfinite( eigs ).all() ) except ValueError: debug() # B-orthogonality check. ## print nm.dot( mtx_s_phi[:,5], nm.dot( mtx_m, mtx_s_phi[:,5] ) ) ## print nm.dot( mtx_s_phi[:,5], nm.dot( mtx_m, mtx_s_phi[:,0] ) ) ## debug() n_eigs = eigs.shape[0] variables = problem.get_variables() mtx_phi = nm.empty( (variables.di.ptr[-1], mtx_s_phi.shape[1]), dtype = nm.float64 ) make_full = variables.make_full_vec if eig_problem in ['simple', 'simple_liquid']: for ii in xrange( n_eigs ): mtx_phi[:,ii] = make_full( mtx_s_phi[:,ii] ) eig_vectors = mtx_phi elif eig_problem == 'schur': # Update also eliminated variables. schur = self.app_options.schur primary_var = schur['primary_var'] eliminated_var = schur['eliminated_var'] mtx_s_phi_schur = - sc.dot( mtx_dib, mtx_s_phi ) aux = nm.empty( (variables.adi.ptr[-1],), dtype = nm.float64 ) set = variables.set_state_part for ii in xrange( n_eigs ): set( aux, mtx_s_phi[:,ii], primary_var, stripped = True ) set( aux, mtx_s_phi_schur[:,ii], eliminated_var, stripped = True ) mtx_phi[:,ii] = make_full( aux ) indx = variables.get_indx( primary_var ) eig_vectors = mtx_phi[indx,:] save = self.app_options.save out = {} for ii in xrange( n_eigs ): if (ii >= save[0]) and (ii < (n_eigs - save[1])): continue aux = problem.state_to_output( mtx_phi[:,ii] ) for name, val in aux.iteritems(): out[name+'%03d' % ii] = val if post_process_hook is not None: out = post_process_hook( out, problem, mtx_phi ) problem.domain.mesh.write( ofn_trunk + '.vtk', io = 'auto', out = out ) fd = open( ofn_trunk + '_eigs.txt', 'w' ) eigs.tofile( fd, ' ' ) fd.close() evp = Struct( kind = eig_problem, eigs = eigs, eigs_rescaled = eigs_rescaled, eig_vectors = eig_vectors ) self.cached_evp = evp return evp def eval_homogenized_coefs( self ): if self.cached_coefs is not None: return self.cached_coefs opts = self.app_options if opts.homogeneous: rtm = opts.region_to_material mat_region = rtm.keys()[0] mat_name = rtm[mat_region] self.problem.update_materials() mat = self.problem.materials[mat_name] coefs = mat.get_data( mat_region, 0, opts.tensor_names ) else: dc = opts.dispersion_conf dconf = ProblemConf.from_dict( dc['input'], dc['module'] ) dconf.materials = self.conf.materials dconf.fe = self.conf.fe dconf.regions.update( self.conf.regions ) dconf.options['output_dir'] = self.problem.output_dir volume = opts.volume(self.problem, 'Y') problem =
ProblemDefinition.from_conf(dconf, init_equations=False)
sfepy.fem.ProblemDefinition.from_conf
#!/usr/bin/env python # 12.01.2007, c import os.path as op import shutil from optparse import OptionParser import sfepy from sfepy.base.base import * from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.fem import ProblemDefinition from sfepy.fem.evaluate import assemble_by_blocks from sfepy.homogenization.phono import transform_plot_data, plot_logs, \ plot_gaps, detect_band_gaps, compute_cat, compute_polarization_angles from sfepy.homogenization.engine import HomogenizationEngine from sfepy.applications import SimpleApp from sfepy.solvers import Solver, eig from sfepy.base.plotutils import plt def make_save_hook( base_name, post_process_hook = None, file_per_var = None ): def save_phono_correctors( state, problem, ir, ic ): problem.save_state( (base_name % (ir, ic)) + '.vtk', state, post_process_hook = post_process_hook, file_per_var = file_per_var ) return save_phono_correctors def try_set_defaults( obj, attr, defaults ): try: values = getattr( obj, attr ) set_defaults( values, defaults ) except: values = defaults return values def report_iw_cat( iw_dir, christoffel ): output( 'incident wave direction:' ) output( iw_dir ) output( 'Christoffel acoustic tensor:' ) output( christoffel ) class AcousticBandGapsApp( SimpleApp ): def process_options( options ): """Application options setup. Sets default values for missing non-compulsory options.""" get = options.get_default_attr clear_cache = get( 'clear_cache', {} ) eigensolver = get( 'eigensolver', 'eig.sgscipy' ) eig_problem = get( 'eig_problem', 'simple' ) schur = get( 'schur', None ) elasticity_contrast = get( 'elasticity_contrast', 1.0 ) scale_epsilon = get( 'scale_epsilon', 1.0 ) incident_wave_dir = get( 'incident_wave_dir', None ) dispersion = get( 'dispersion', 'simple' ) dispersion_conf = get( 'dispersion_conf', None ) homogeneous = get( 'homogeneous', False ) save = get( 'save_eig_vectors', (0, 0) ) eig_range = get( 'eig_range', None ) freq_margins = get( 'freq_margins', (5, 5) ) # Given in per cent. freq_margins = 0.01 * nm.array( freq_margins, dtype = nm.float64 ) fixed_eig_range = get( 'fixed_eig_range', None ) # Given in per cent. freq_step = 0.01 * get( 'freq_step', 5 ) feps = get( 'feps', 1e-8 ) zeps = get( 'zeps', 1e-8 ) teps = get( 'teps', 1e-4 ) teps_rel = get( 'teps_rel', True ) eig_vector_transform = get( 'eig_vector_transform', 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', {'show' : True,'legend' : False,} ) fig_name = get( 'fig_name', None ) fig_name_wave = get( 'fig_name_wave', None ) fig_name_angle = get( 'fig_name_angle', None ) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : 'min eig($M^*$)', 'eig_mid' : 'mid eig($M^*$)', 'eig_max' : 'max eig($M^*$)', 'y_axis' : 'eigenvalues of mass matrix $M^*$', } plot_labels = try_set_defaults( options, 'plot_labels', aux ) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'$\kappa$(min)', 'eig_mid' : r'$\kappa$(mid)', 'eig_max' : r'$\kappa$(max)', '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)', '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' : 0.5, 'color' : 'b', 'linestyle' : '--' }, 'eig_mid' : {'linewidth' : 0.5, 'color' : 'b', 'linestyle' : '-.' }, 'eig_max' : {'linewidth' : 0.5, 'color' : 'b', 'linestyle' : '-' }, 'strong_gap' : {'linewidth' : 0, 'facecolor' : (1, 1, 0.5) }, 'weak_gap' : {'linewidth' : 0, 'facecolor' : (1, 1, 1) }, 'propagation' : {'linewidth' : 0, 'facecolor' : (0.5, 1, 0.5) }, 'params' : {'axes.labelsize': 'large', 'text.fontsize': 'large', 'legend.fontsize': 'large', 'xtick.labelsize': 'large', 'ytick.labelsize': 'large', 'text.usetex': False}, } plot_rsc = try_set_defaults( options, 'plot_rsc', plot_rsc ) eigenmomentum = get( 'eigenmomentum', None, 'missing "eigenmomentum" in options!' ) region_to_material = get( 'region_to_material', None, 'missing "region_to_material" in options!' ) tensor_names = get( 'tensor_names', None, 'missing "tensor_names" in options!' ) volume = get( 'volume', None, 'missing "volume" in options!' ) if eig_problem == 'simple_liquid': liquid_region = get('liquid_region', None, 'missing "liquid_region" in options!') else: liquid_region = None return Struct( **locals() ) process_options = staticmethod( process_options ) def process_options_pv( options ): """Application options setup for phase velocity computation. Sets default values for missing non-compulsory options.""" get = options.get_default_attr clear_cache = get( 'clear_cache', {} ) eigensolver = get( 'eigensolver', 'eig.sgscipy' ) incident_wave_dir = get( 'incident_wave_dir', None ) dispersion = get( 'dispersion', 'simple' ) dispersion_conf = get( 'dispersion_conf', None ) homogeneous = get( 'homogeneous', False ) fig_suffix = get( 'fig_suffix', '.pdf' ) region_to_material = get( 'region_to_material', None, 'missing "region_to_material" in options!' ) tensor_names = get( 'tensor_names', None, 'missing "tensor_names" in options!' ) volume = get( 'volume', None, 'missing "volume" in options!' ) return Struct( **locals() ) process_options_pv = staticmethod( process_options_pv ) def __init__( self, conf, options, output_prefix, **kwargs ): SimpleApp.__init__( self, conf, options, output_prefix, init_equations = False ) self.setup_options() self.cached_coefs = None self.cached_iw_dir = None self.cached_christoffel = None self.cached_evp = None output_dir = self.problem.output_dir shutil.copyfile( conf._filename, op.join( output_dir, op.basename( conf._filename ) ) ) def setup_options( self ): SimpleApp.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 ): """In parametric runs, cached data (homogenized coefficients, Christoffel acoustic tensor and eigenvalue problem solution) are cleared according to 'clear_cache' aplication options. Example: clear_cache = {'cached_christoffel' : True, 'cached_evp' : True} """ options = self.options for key, val in self.app_options.clear_cache.iteritems(): if val and key.startswith('cached_'): setattr(self, key, None) if options.phase_velocity: # No band gaps in this case. return self.compute_phase_velocity() evp = self.solve_eigen_problem() self.fix_eig_range( evp.eigs.shape[0] ) if options.detect_band_gaps: bg = detect_band_gaps( self.problem, evp.kind, evp.eigs_rescaled, evp.eig_vectors, self.app_options, self.conf.funmod ) if options.plot: plot_range, teigs = transform_plot_data( bg.logs.eigs, bg.opts.plot_transform, self.conf.funmod ) plot_rsc = bg.opts.plot_rsc plot_opts = bg.opts.plot_options plot_labels = bg.opts.plot_labels plt.rcParams.update( plot_rsc['params'] ) fig = plot_gaps( 1, plot_rsc, bg.gaps, bg.kinds, bg.freq_range_margins, plot_range, clear = True ) fig = plot_logs( 1, plot_rsc, plot_labels, bg.logs.freqs, teigs, bg.valid[bg.eig_range], bg.freq_range_initial, plot_range, False, show_legend = plot_opts['legend'], new_axes = True ) fig_name = bg.opts.fig_name if fig_name is not None: fig.savefig( fig_name ) if plot_opts['show']:
plt.show()
sfepy.base.plotutils.plt.show
#!/usr/bin/env python # 12.01.2007, c import os.path as op import shutil from optparse import OptionParser import sfepy from sfepy.base.base import * from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.fem import ProblemDefinition from sfepy.fem.evaluate import assemble_by_blocks from sfepy.homogenization.phono import transform_plot_data, plot_logs, \ plot_gaps, detect_band_gaps, compute_cat, compute_polarization_angles from sfepy.homogenization.engine import HomogenizationEngine from sfepy.applications import SimpleApp from sfepy.solvers import Solver, eig from sfepy.base.plotutils import plt def make_save_hook( base_name, post_process_hook = None, file_per_var = None ): def save_phono_correctors( state, problem, ir, ic ): problem.save_state( (base_name % (ir, ic)) + '.vtk', state, post_process_hook = post_process_hook, file_per_var = file_per_var ) return save_phono_correctors def try_set_defaults( obj, attr, defaults ): try: values = getattr( obj, attr ) set_defaults( values, defaults ) except: values = defaults return values def report_iw_cat( iw_dir, christoffel ): output( 'incident wave direction:' ) output( iw_dir ) output( 'Christoffel acoustic tensor:' ) output( christoffel ) class AcousticBandGapsApp( SimpleApp ): def process_options( options ): """Application options setup. Sets default values for missing non-compulsory options.""" get = options.get_default_attr clear_cache = get( 'clear_cache', {} ) eigensolver = get( 'eigensolver', 'eig.sgscipy' ) eig_problem = get( 'eig_problem', 'simple' ) schur = get( 'schur', None ) elasticity_contrast = get( 'elasticity_contrast', 1.0 ) scale_epsilon = get( 'scale_epsilon', 1.0 ) incident_wave_dir = get( 'incident_wave_dir', None ) dispersion = get( 'dispersion', 'simple' ) dispersion_conf = get( 'dispersion_conf', None ) homogeneous = get( 'homogeneous', False ) save = get( 'save_eig_vectors', (0, 0) ) eig_range = get( 'eig_range', None ) freq_margins = get( 'freq_margins', (5, 5) ) # Given in per cent. freq_margins = 0.01 * nm.array( freq_margins, dtype = nm.float64 ) fixed_eig_range = get( 'fixed_eig_range', None ) # Given in per cent. freq_step = 0.01 * get( 'freq_step', 5 ) feps = get( 'feps', 1e-8 ) zeps = get( 'zeps', 1e-8 ) teps = get( 'teps', 1e-4 ) teps_rel = get( 'teps_rel', True ) eig_vector_transform = get( 'eig_vector_transform', 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', {'show' : True,'legend' : False,} ) fig_name = get( 'fig_name', None ) fig_name_wave = get( 'fig_name_wave', None ) fig_name_angle = get( 'fig_name_angle', None ) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : 'min eig($M^*$)', 'eig_mid' : 'mid eig($M^*$)', 'eig_max' : 'max eig($M^*$)', 'y_axis' : 'eigenvalues of mass matrix $M^*$', } plot_labels = try_set_defaults( options, 'plot_labels', aux ) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'$\kappa$(min)', 'eig_mid' : r'$\kappa$(mid)', 'eig_max' : r'$\kappa$(max)', '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)', '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' : 0.5, 'color' : 'b', 'linestyle' : '--' }, 'eig_mid' : {'linewidth' : 0.5, 'color' : 'b', 'linestyle' : '-.' }, 'eig_max' : {'linewidth' : 0.5, 'color' : 'b', 'linestyle' : '-' }, 'strong_gap' : {'linewidth' : 0, 'facecolor' : (1, 1, 0.5) }, 'weak_gap' : {'linewidth' : 0, 'facecolor' : (1, 1, 1) }, 'propagation' : {'linewidth' : 0, 'facecolor' : (0.5, 1, 0.5) }, 'params' : {'axes.labelsize': 'large', 'text.fontsize': 'large', 'legend.fontsize': 'large', 'xtick.labelsize': 'large', 'ytick.labelsize': 'large', 'text.usetex': False}, } plot_rsc = try_set_defaults( options, 'plot_rsc', plot_rsc ) eigenmomentum = get( 'eigenmomentum', None, 'missing "eigenmomentum" in options!' ) region_to_material = get( 'region_to_material', None, 'missing "region_to_material" in options!' ) tensor_names = get( 'tensor_names', None, 'missing "tensor_names" in options!' ) volume = get( 'volume', None, 'missing "volume" in options!' ) if eig_problem == 'simple_liquid': liquid_region = get('liquid_region', None, 'missing "liquid_region" in options!') else: liquid_region = None return Struct( **locals() ) process_options = staticmethod( process_options ) def process_options_pv( options ): """Application options setup for phase velocity computation. Sets default values for missing non-compulsory options.""" get = options.get_default_attr clear_cache = get( 'clear_cache', {} ) eigensolver = get( 'eigensolver', 'eig.sgscipy' ) incident_wave_dir = get( 'incident_wave_dir', None ) dispersion = get( 'dispersion', 'simple' ) dispersion_conf = get( 'dispersion_conf', None ) homogeneous = get( 'homogeneous', False ) fig_suffix = get( 'fig_suffix', '.pdf' ) region_to_material = get( 'region_to_material', None, 'missing "region_to_material" in options!' ) tensor_names = get( 'tensor_names', None, 'missing "tensor_names" in options!' ) volume = get( 'volume', None, 'missing "volume" in options!' ) return Struct( **locals() ) process_options_pv = staticmethod( process_options_pv ) def __init__( self, conf, options, output_prefix, **kwargs ): SimpleApp.__init__( self, conf, options, output_prefix, init_equations = False ) self.setup_options() self.cached_coefs = None self.cached_iw_dir = None self.cached_christoffel = None self.cached_evp = None output_dir = self.problem.output_dir shutil.copyfile( conf._filename, op.join( output_dir, op.basename( conf._filename ) ) ) def setup_options( self ): SimpleApp.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 ): """In parametric runs, cached data (homogenized coefficients, Christoffel acoustic tensor and eigenvalue problem solution) are cleared according to 'clear_cache' aplication options. Example: clear_cache = {'cached_christoffel' : True, 'cached_evp' : True} """ options = self.options for key, val in self.app_options.clear_cache.iteritems(): if val and key.startswith('cached_'): setattr(self, key, None) if options.phase_velocity: # No band gaps in this case. return self.compute_phase_velocity() evp = self.solve_eigen_problem() self.fix_eig_range( evp.eigs.shape[0] ) if options.detect_band_gaps: bg = detect_band_gaps( self.problem, evp.kind, evp.eigs_rescaled, evp.eig_vectors, self.app_options, self.conf.funmod ) if options.plot: plot_range, teigs = transform_plot_data( bg.logs.eigs, bg.opts.plot_transform, self.conf.funmod ) plot_rsc = bg.opts.plot_rsc plot_opts = bg.opts.plot_options plot_labels = bg.opts.plot_labels plt.rcParams.update( plot_rsc['params'] ) fig = plot_gaps( 1, plot_rsc, bg.gaps, bg.kinds, bg.freq_range_margins, plot_range, clear = True ) fig = plot_logs( 1, plot_rsc, plot_labels, bg.logs.freqs, teigs, bg.valid[bg.eig_range], bg.freq_range_initial, plot_range, False, show_legend = plot_opts['legend'], new_axes = True ) fig_name = bg.opts.fig_name if fig_name is not None: fig.savefig( fig_name ) if plot_opts['show']: plt.show() elif options.analyze_dispersion: christoffel, iw_dir = self.compute_cat(ret_iw_dir=True) bg = detect_band_gaps( self.problem, evp.kind, evp.eigs_rescaled, evp.eig_vectors, self.app_options, self.conf.funmod, christoffel = christoffel ) output( 'computing polarization angles...' ) pas = compute_polarization_angles( iw_dir, bg.logs.eig_vectors ) output( '...done' ) bg.polarization_angles = pas output( 'computing phase velocity...' ) bg.phase_velocity = self.compute_phase_velocity() output( '...done' ) if options.plot: plot_rsc = bg.opts.plot_rsc plot_opts = bg.opts.plot_options plt.rcParams.update( plot_rsc['params'] ) aux = transform_plot_data( pas, bg.opts.plot_transform_angle, self.conf.funmod ) plot_range, pas = aux plot_labels = bg.opts.plot_labels_angle fig = plot_gaps( 1, plot_rsc, bg.gaps, bg.kinds, 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, False, show_legend = plot_opts['legend'], new_axes = True ) fig_name = bg.opts.fig_name_angle if fig_name is not None: fig.savefig( fig_name ) aux = transform_plot_data( bg.logs.eigs, bg.opts.plot_transform_wave, self.conf.funmod ) plot_range, teigs = aux plot_labels = bg.opts.plot_labels_wave fig = plot_gaps( 2, plot_rsc, bg.gaps, bg.kinds, 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, False, show_legend = plot_opts['legend'], new_axes = True ) fig_name = bg.opts.fig_name_wave if fig_name is not None: fig.savefig( fig_name ) if plot_opts['show']:
plt.show()
sfepy.base.plotutils.plt.show
import numpy as nm from sfepy.base.base import Struct class SplineBox(Struct): """ B-spline geometry parametrization. Geometry can be modified by moving spline control points. """ @staticmethod def mmax(x, y): n = len(x) aux = nm.zeros((2,n), dtype=nm.int) aux[0,:] = x[:] aux[1,:] = nm.ones((1,n)) * y out = nm.max(aux, axis=0) return out @staticmethod def spsorted(meshsites, sites): n1 = len(meshsites) n2 = len(sites) aux = nm.zeros((n1 + n2,), dtype=nm.double) aux[:n1] = meshsites aux[n1:] = sites inx = nm.argsort(aux) out = nm.where(inx >= len(meshsites)) - nm.arange(len(sites)) return out[0] @staticmethod def augknt(knots, k, mults=1): if mults > 1: aux = [] for j in k[1:-1]: aux += [j] * mults; else: aux = knots[1:-1] augknot = [knots[0]] * k + list(aux) + [knots[-1]] * k return augknot @staticmethod def spcol(knots, k, tau): npk = len(knots) n = npk - k nrows = tau.shape[0] pts = tau km1 = k - 1 savl = SplineBox.mmax(SplineBox.spsorted(knots[:n], pts), k) b = nm.zeros((nrows, k), dtype=nm.double) b[:,0] = nm.ones((nrows,), dtype=nm.double) for j in range(km1): saved = nm.zeros((nrows,), dtype=nm.double); for r in range(j+1): tr = knots[savl + r] - pts tl = pts - knots[savl + r - j - 1] term = nm.double(b[:,r]) / (tr + tl) b[:,r] = saved + tr * term saved = tl * term b[:,j+1] = saved idx = nm.where((tau < knots[0]) | (tau > knots[npk-1]))[0] if len(idx) > 0: b[idx,:] = 0 idx1 = nm.tile(nm.arange(1-nrows, 1), (k,)) idx2 = nm.tile(nrows * savl, (k,)) idx3 = nm.tile(nrows * nm.arange(-km1, 1), (nrows, 1)) idx3 = nm.reshape(idx3, (nrows * k,), order='F') width = n + km1 + km1 nn = nrows * width cc = nm.zeros((nn,), dtype=nm.double) idx = idx1 + idx2 + idx3 - 1 cc[idx] = b.reshape((len(idx),), order='F') idx1 = nm.tile(nm.arange(1-nrows, 1), (n,)) idx2 = nm.tile(nrows * nm.arange(1, n + 1), (nrows, 1)) idx2 = nm.reshape(idx2, (nrows * n,), order='F') idx = idx1 + idx2 - 1 colloc = cc[idx].reshape((nrows, n), order='F') return colloc @staticmethod def create_spb(bbox, coors, nsg=None): if type(bbox) is not nm.ndarray: bbox = nm.array(bbox) if type(coors) is not nm.ndarray: coors = nm.array(coors) dim = coors.shape[1] axes = [] if nsg is None: nsg = nm.ones((dim,), dtype=nm.int) else: nsg = nm.array(nsg) cpt = [] ncpt = [] for idim in range(dim): axes.append({}) aux = nm.linspace(bbox[idim,0], bbox[idim,1], nsg[idim] + 1) knots = nm.array(SplineBox.augknt(aux, 4)) axes[idim]['knots'] = knots nn = 4 + nsg[idim] - 1 ncpt.append(nn) cpt.append(nm.zeros((nn,), dtype=nm.double)) for j in range(nn): cpt[idim][j] = nm.sum(knots[(j+1):(j+4)]) / 3.0 inx = nm.argsort(coors[:,idim]) aux = SplineBox.spcol(knots, 4, coors[inx,idim]) axes[idim]['bsc'] = nm.zeros_like(aux) axes[idim]['bsc'][inx,:] = aux[:,:] ncpts = nm.prod(ncpt) cpoints = nm.zeros((ncpts, dim), dtype=nm.double) cpoints_idx = nm.zeros(ncpt, dtype=nm.int) n2 = nm.prod(ncpt[:2]) aux = nm.arange(n2).reshape(ncpt[:2], order='F') if dim == 2: idx = nm.mgrid[0:ncpt[1],0:ncpt[0]] cpoints[:,0] = cpt[0][idx[1].reshape((ncpts,))] cpoints[:,1] = cpt[1][idx[0].reshape((ncpts,))] cpoints_idx[:,:] = aux elif dim == 3: idx = nm.mgrid[0:ncpt[2],0:ncpt[1],0:ncpt[0]] cpoints[:,0] = cpt[0][idx[2].reshape((ncpts,))] cpoints[:,1] = cpt[1][idx[1].reshape((ncpts,))] cpoints[:,2] = cpt[2][idx[0].reshape((ncpts,))] for j in range(ncpt[2]): cpoints_idx[:,:,j] = aux + j * n2 return axes, cpoints, cpoints_idx def __init__(self, bbox, coors, name='spbox', **kwargs): """ Create a SplineBox. Parameters ---------- bbox : array Mesh bounding box. coors : array Coordinates of mesh nodes. name : str Object name. """
Struct.__init__(self, name=name, **kwargs)
sfepy.base.base.Struct.__init__
import numpy as nm from sfepy.terms.terms import Term, terms from sfepy.base.base import get_default def grad_as_vector(grad): grad = grad.transpose((0, 1, 3, 2)) sh = grad.shape return grad.reshape((sh[0], sh[1], sh[2] * sh[3], 1)) class AdjDivGradTerm(Term): r""" Gateaux differential of :math:`\Psi(\ul{u}) = \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}` w.r.t. :math:`\ul{u}` in the direction :math:`\ul{v}` or adjoint term to `dw_div_grad`. :Definition: .. math:: w \delta_{u} \Psi(\ul{u}) \circ \ul{v} :Arguments: - material_1 : :math:`w` (weight) - material_2 : :math:`\nu` (viscosity) - virtual : :math:`\ul{v}` - state : :math:`\ul{u}` """ name = 'dw_adj_div_grad' arg_types = ('material_1', 'material_2', 'virtual', 'parameter') arg_shapes = {'material_1' : '1, 1', 'material_2' : '1, 1', 'virtual' : ('D', None), 'parameter' : 'D'} function = staticmethod(terms.term_ns_asm_div_grad) def get_fargs(self, mat1, mat2, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) if diff_var is None: grad = grad_as_vector(self.get(state, 'grad')) fmode = 0 else: grad = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return grad, mat1 * mat2, vg, fmode class AdjConvect1Term(Term): r""" The first adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{v} \cdot \nabla) \ul{u}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect1' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect1) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') grad_u = self.get(parameter, 'grad') # No transposition here! fmode = diff_var is not None return val_w, grad_u, vg, fmode class AdjConvect2Term(Term): r""" The second adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{u} \cdot \nabla) \ul{v}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect2' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect2) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') val_u = self.get(parameter, 'val') fmode = diff_var is not None return val_w, val_u, vg, fmode class SUPGCAdjStabilizationTerm(Term): r""" Adjoint term to SUPG stabilization term `dw_st_supg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ ((\ul{v} \cdot \nabla) \ul{u}) ((\ul{u} \cdot \nabla) \ul{w}) + ((\ul{u} \cdot \nabla) \ul{u}) ((\ul{v} \cdot \nabla) \ul{w}) ] :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_st_adj_supg_c' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj_supg_c) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_u = self.get(parameter, 'val') grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), val_u, grad_u, mat, vg, conn, fmode class SUPGPAdj1StabilizationTerm(Term): r""" The first adjoint term to SUPG stabilization term `dw_st_supg_p`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ \nabla p (\ul{v} \cdot \nabla \ul{w}) :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`p` """ name = 'dw_st_adj1_supg_p' arg_types = ('material', 'virtual', 'state', 'parameter') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 1} function = staticmethod(terms.dw_st_adj1_supg_p) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg_w, _ = self.get_mapping(state) grad_p = self.get(parameter, 'grad') conn_w = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), grad_p, mat, vg_w, conn_w, fmode class SUPGPAdj2StabilizationTerm(Term): r""" The second adjoint term to SUPG stabilization term `dw_st_supg_p` as well as adjoint term to PSPG stabilization term `dw_st_pspg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \tau_K\ \nabla r (\ul{v} \cdot \nabla \ul{u}) :Arguments: - material : :math:`\tau_K` - virtual : :math:`\ul{v}` - parameter : :math:`\ul{u}` - state : :math:`r` """ name = 'dw_st_adj2_supg_p' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 1, 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj2_supg_p) def get_fargs(self, mat, virtual, parameter, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg_r, _ = self.get_mapping(state) vg_u, _ = self.get_mapping(parameter) grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn_r = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return grad_u, state(), mat, vg_u, vg_r, conn_r, fmode class SDDotVolumeTerm(Term): r""" Sensitivity (shape derivative) of dot product of scalars or vectors. :Definition: .. math:: \int_{\Omega} p q (\nabla \cdot \ul{\Vcal}) \mbox{ , } \int_{\Omega} (\ul{u} \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) :Arguments: - parameter_1 : :math:`p` or :math:`\ul{u}` - parameter_2 : :math:`q` or :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_volume_dot' arg_types = ('parameter_1', 'parameter_2', 'parameter_mv') arg_shapes = [{'parameter_1' : 'D', 'parameter_2' : 'D', 'parameter_mv' : 'D'}, {'parameter_1' : 1, 'parameter_2' : 1}] function = staticmethod(terms.d_sd_volume_dot) def get_fargs(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par1) val1 = self.get(par1, 'val') val2 = self.get(par2, 'val') div_mv = self.get(par_mv, 'div') return val1, val2, div_mv, vg,
get_default(term_mode, 1)
sfepy.base.base.get_default
import numpy as nm from sfepy.terms.terms import Term, terms from sfepy.base.base import get_default def grad_as_vector(grad): grad = grad.transpose((0, 1, 3, 2)) sh = grad.shape return grad.reshape((sh[0], sh[1], sh[2] * sh[3], 1)) class AdjDivGradTerm(Term): r""" Gateaux differential of :math:`\Psi(\ul{u}) = \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}` w.r.t. :math:`\ul{u}` in the direction :math:`\ul{v}` or adjoint term to `dw_div_grad`. :Definition: .. math:: w \delta_{u} \Psi(\ul{u}) \circ \ul{v} :Arguments: - material_1 : :math:`w` (weight) - material_2 : :math:`\nu` (viscosity) - virtual : :math:`\ul{v}` - state : :math:`\ul{u}` """ name = 'dw_adj_div_grad' arg_types = ('material_1', 'material_2', 'virtual', 'parameter') arg_shapes = {'material_1' : '1, 1', 'material_2' : '1, 1', 'virtual' : ('D', None), 'parameter' : 'D'} function = staticmethod(terms.term_ns_asm_div_grad) def get_fargs(self, mat1, mat2, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) if diff_var is None: grad = grad_as_vector(self.get(state, 'grad')) fmode = 0 else: grad = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return grad, mat1 * mat2, vg, fmode class AdjConvect1Term(Term): r""" The first adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{v} \cdot \nabla) \ul{u}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect1' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect1) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') grad_u = self.get(parameter, 'grad') # No transposition here! fmode = diff_var is not None return val_w, grad_u, vg, fmode class AdjConvect2Term(Term): r""" The second adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{u} \cdot \nabla) \ul{v}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect2' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect2) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') val_u = self.get(parameter, 'val') fmode = diff_var is not None return val_w, val_u, vg, fmode class SUPGCAdjStabilizationTerm(Term): r""" Adjoint term to SUPG stabilization term `dw_st_supg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ ((\ul{v} \cdot \nabla) \ul{u}) ((\ul{u} \cdot \nabla) \ul{w}) + ((\ul{u} \cdot \nabla) \ul{u}) ((\ul{v} \cdot \nabla) \ul{w}) ] :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_st_adj_supg_c' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj_supg_c) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_u = self.get(parameter, 'val') grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), val_u, grad_u, mat, vg, conn, fmode class SUPGPAdj1StabilizationTerm(Term): r""" The first adjoint term to SUPG stabilization term `dw_st_supg_p`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ \nabla p (\ul{v} \cdot \nabla \ul{w}) :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`p` """ name = 'dw_st_adj1_supg_p' arg_types = ('material', 'virtual', 'state', 'parameter') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 1} function = staticmethod(terms.dw_st_adj1_supg_p) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg_w, _ = self.get_mapping(state) grad_p = self.get(parameter, 'grad') conn_w = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), grad_p, mat, vg_w, conn_w, fmode class SUPGPAdj2StabilizationTerm(Term): r""" The second adjoint term to SUPG stabilization term `dw_st_supg_p` as well as adjoint term to PSPG stabilization term `dw_st_pspg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \tau_K\ \nabla r (\ul{v} \cdot \nabla \ul{u}) :Arguments: - material : :math:`\tau_K` - virtual : :math:`\ul{v}` - parameter : :math:`\ul{u}` - state : :math:`r` """ name = 'dw_st_adj2_supg_p' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 1, 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj2_supg_p) def get_fargs(self, mat, virtual, parameter, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg_r, _ = self.get_mapping(state) vg_u, _ = self.get_mapping(parameter) grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn_r = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return grad_u, state(), mat, vg_u, vg_r, conn_r, fmode class SDDotVolumeTerm(Term): r""" Sensitivity (shape derivative) of dot product of scalars or vectors. :Definition: .. math:: \int_{\Omega} p q (\nabla \cdot \ul{\Vcal}) \mbox{ , } \int_{\Omega} (\ul{u} \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) :Arguments: - parameter_1 : :math:`p` or :math:`\ul{u}` - parameter_2 : :math:`q` or :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_volume_dot' arg_types = ('parameter_1', 'parameter_2', 'parameter_mv') arg_shapes = [{'parameter_1' : 'D', 'parameter_2' : 'D', 'parameter_mv' : 'D'}, {'parameter_1' : 1, 'parameter_2' : 1}] function = staticmethod(terms.d_sd_volume_dot) def get_fargs(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par1) val1 = self.get(par1, 'val') val2 = self.get(par2, 'val') div_mv = self.get(par_mv, 'div') return val1, val2, div_mv, vg, get_default(term_mode, 1) def get_eval_shape(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par1) return (n_el, 1, 1, 1), par1.dtype class SDDivTerm(Term): r""" Sensitivity (shape derivative) of Stokes term `dw_stokes` in 'div' mode. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: \int_{\Omega} p [ (\nabla \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_k}{x_i} \pdiff{w_i}{x_k} ] :Arguments: - parameter_u : :math:`\ul{u}` - parameter_p : :math:`p` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div' arg_types = ('parameter_u', 'parameter_p', 'parameter_mv') arg_shapes = {'parameter_u' : 'D', 'parameter_p' : 1, 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div) def get_fargs(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) div_u = self.get(par_u, 'div') grad_u = grad_as_vector(self.get(par_u, 'grad')) val_p = self.get(par_p, 'val') div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (div_u, grad_u, val_p, div_mv, grad_mv, vg,
get_default(term_mode, 1)
sfepy.base.base.get_default
import numpy as nm from sfepy.terms.terms import Term, terms from sfepy.base.base import get_default def grad_as_vector(grad): grad = grad.transpose((0, 1, 3, 2)) sh = grad.shape return grad.reshape((sh[0], sh[1], sh[2] * sh[3], 1)) class AdjDivGradTerm(Term): r""" Gateaux differential of :math:`\Psi(\ul{u}) = \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}` w.r.t. :math:`\ul{u}` in the direction :math:`\ul{v}` or adjoint term to `dw_div_grad`. :Definition: .. math:: w \delta_{u} \Psi(\ul{u}) \circ \ul{v} :Arguments: - material_1 : :math:`w` (weight) - material_2 : :math:`\nu` (viscosity) - virtual : :math:`\ul{v}` - state : :math:`\ul{u}` """ name = 'dw_adj_div_grad' arg_types = ('material_1', 'material_2', 'virtual', 'parameter') arg_shapes = {'material_1' : '1, 1', 'material_2' : '1, 1', 'virtual' : ('D', None), 'parameter' : 'D'} function = staticmethod(terms.term_ns_asm_div_grad) def get_fargs(self, mat1, mat2, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) if diff_var is None: grad = grad_as_vector(self.get(state, 'grad')) fmode = 0 else: grad = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return grad, mat1 * mat2, vg, fmode class AdjConvect1Term(Term): r""" The first adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{v} \cdot \nabla) \ul{u}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect1' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect1) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') grad_u = self.get(parameter, 'grad') # No transposition here! fmode = diff_var is not None return val_w, grad_u, vg, fmode class AdjConvect2Term(Term): r""" The second adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{u} \cdot \nabla) \ul{v}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect2' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect2) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') val_u = self.get(parameter, 'val') fmode = diff_var is not None return val_w, val_u, vg, fmode class SUPGCAdjStabilizationTerm(Term): r""" Adjoint term to SUPG stabilization term `dw_st_supg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ ((\ul{v} \cdot \nabla) \ul{u}) ((\ul{u} \cdot \nabla) \ul{w}) + ((\ul{u} \cdot \nabla) \ul{u}) ((\ul{v} \cdot \nabla) \ul{w}) ] :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_st_adj_supg_c' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj_supg_c) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_u = self.get(parameter, 'val') grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), val_u, grad_u, mat, vg, conn, fmode class SUPGPAdj1StabilizationTerm(Term): r""" The first adjoint term to SUPG stabilization term `dw_st_supg_p`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ \nabla p (\ul{v} \cdot \nabla \ul{w}) :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`p` """ name = 'dw_st_adj1_supg_p' arg_types = ('material', 'virtual', 'state', 'parameter') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 1} function = staticmethod(terms.dw_st_adj1_supg_p) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg_w, _ = self.get_mapping(state) grad_p = self.get(parameter, 'grad') conn_w = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), grad_p, mat, vg_w, conn_w, fmode class SUPGPAdj2StabilizationTerm(Term): r""" The second adjoint term to SUPG stabilization term `dw_st_supg_p` as well as adjoint term to PSPG stabilization term `dw_st_pspg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \tau_K\ \nabla r (\ul{v} \cdot \nabla \ul{u}) :Arguments: - material : :math:`\tau_K` - virtual : :math:`\ul{v}` - parameter : :math:`\ul{u}` - state : :math:`r` """ name = 'dw_st_adj2_supg_p' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 1, 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj2_supg_p) def get_fargs(self, mat, virtual, parameter, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg_r, _ = self.get_mapping(state) vg_u, _ = self.get_mapping(parameter) grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn_r = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return grad_u, state(), mat, vg_u, vg_r, conn_r, fmode class SDDotVolumeTerm(Term): r""" Sensitivity (shape derivative) of dot product of scalars or vectors. :Definition: .. math:: \int_{\Omega} p q (\nabla \cdot \ul{\Vcal}) \mbox{ , } \int_{\Omega} (\ul{u} \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) :Arguments: - parameter_1 : :math:`p` or :math:`\ul{u}` - parameter_2 : :math:`q` or :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_volume_dot' arg_types = ('parameter_1', 'parameter_2', 'parameter_mv') arg_shapes = [{'parameter_1' : 'D', 'parameter_2' : 'D', 'parameter_mv' : 'D'}, {'parameter_1' : 1, 'parameter_2' : 1}] function = staticmethod(terms.d_sd_volume_dot) def get_fargs(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par1) val1 = self.get(par1, 'val') val2 = self.get(par2, 'val') div_mv = self.get(par_mv, 'div') return val1, val2, div_mv, vg, get_default(term_mode, 1) def get_eval_shape(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par1) return (n_el, 1, 1, 1), par1.dtype class SDDivTerm(Term): r""" Sensitivity (shape derivative) of Stokes term `dw_stokes` in 'div' mode. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: \int_{\Omega} p [ (\nabla \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_k}{x_i} \pdiff{w_i}{x_k} ] :Arguments: - parameter_u : :math:`\ul{u}` - parameter_p : :math:`p` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div' arg_types = ('parameter_u', 'parameter_p', 'parameter_mv') arg_shapes = {'parameter_u' : 'D', 'parameter_p' : 1, 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div) def get_fargs(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) div_u = self.get(par_u, 'div') grad_u = grad_as_vector(self.get(par_u, 'grad')) val_p = self.get(par_p, 'val') div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (div_u, grad_u, val_p, div_mv, grad_mv, vg, get_default(term_mode, 1)) def get_eval_shape(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDDivGradTerm(Term): r""" Sensitivity (shape derivative) of diffusion term `dw_div_grad`. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: w \nu \int_{\Omega} [ \pdiff{u_i}{x_k} \pdiff{w_i}{x_k} (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_j}{x_k} \pdiff{u_i}{x_j} \pdiff{w_i}{x_k} - \pdiff{u_i}{x_k} \pdiff{\Vcal_l}{x_k} \pdiff{w_i}{x_k} ] :Arguments: - material : :math:`\nu` (viscosity, optional) - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div_grad' arg_types = ('opt_material', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'opt_material' : '1, 1', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div_grad) def get_fargs(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) grad_u = grad_as_vector(self.get(par_u, 'grad')) grad_w = grad_as_vector(self.get(par_w, 'grad')) div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (grad_u, grad_w, div_mv, grad_mv, mat, vg,
get_default(term_mode, 1)
sfepy.base.base.get_default
import numpy as nm from sfepy.terms.terms import Term, terms from sfepy.base.base import get_default def grad_as_vector(grad): grad = grad.transpose((0, 1, 3, 2)) sh = grad.shape return grad.reshape((sh[0], sh[1], sh[2] * sh[3], 1)) class AdjDivGradTerm(Term): r""" Gateaux differential of :math:`\Psi(\ul{u}) = \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}` w.r.t. :math:`\ul{u}` in the direction :math:`\ul{v}` or adjoint term to `dw_div_grad`. :Definition: .. math:: w \delta_{u} \Psi(\ul{u}) \circ \ul{v} :Arguments: - material_1 : :math:`w` (weight) - material_2 : :math:`\nu` (viscosity) - virtual : :math:`\ul{v}` - state : :math:`\ul{u}` """ name = 'dw_adj_div_grad' arg_types = ('material_1', 'material_2', 'virtual', 'parameter') arg_shapes = {'material_1' : '1, 1', 'material_2' : '1, 1', 'virtual' : ('D', None), 'parameter' : 'D'} function = staticmethod(terms.term_ns_asm_div_grad) def get_fargs(self, mat1, mat2, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) if diff_var is None: grad = grad_as_vector(self.get(state, 'grad')) fmode = 0 else: grad = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return grad, mat1 * mat2, vg, fmode class AdjConvect1Term(Term): r""" The first adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{v} \cdot \nabla) \ul{u}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect1' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect1) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') grad_u = self.get(parameter, 'grad') # No transposition here! fmode = diff_var is not None return val_w, grad_u, vg, fmode class AdjConvect2Term(Term): r""" The second adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{u} \cdot \nabla) \ul{v}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect2' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect2) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') val_u = self.get(parameter, 'val') fmode = diff_var is not None return val_w, val_u, vg, fmode class SUPGCAdjStabilizationTerm(Term): r""" Adjoint term to SUPG stabilization term `dw_st_supg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ ((\ul{v} \cdot \nabla) \ul{u}) ((\ul{u} \cdot \nabla) \ul{w}) + ((\ul{u} \cdot \nabla) \ul{u}) ((\ul{v} \cdot \nabla) \ul{w}) ] :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_st_adj_supg_c' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj_supg_c) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_u = self.get(parameter, 'val') grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), val_u, grad_u, mat, vg, conn, fmode class SUPGPAdj1StabilizationTerm(Term): r""" The first adjoint term to SUPG stabilization term `dw_st_supg_p`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ \nabla p (\ul{v} \cdot \nabla \ul{w}) :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`p` """ name = 'dw_st_adj1_supg_p' arg_types = ('material', 'virtual', 'state', 'parameter') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 1} function = staticmethod(terms.dw_st_adj1_supg_p) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg_w, _ = self.get_mapping(state) grad_p = self.get(parameter, 'grad') conn_w = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), grad_p, mat, vg_w, conn_w, fmode class SUPGPAdj2StabilizationTerm(Term): r""" The second adjoint term to SUPG stabilization term `dw_st_supg_p` as well as adjoint term to PSPG stabilization term `dw_st_pspg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \tau_K\ \nabla r (\ul{v} \cdot \nabla \ul{u}) :Arguments: - material : :math:`\tau_K` - virtual : :math:`\ul{v}` - parameter : :math:`\ul{u}` - state : :math:`r` """ name = 'dw_st_adj2_supg_p' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 1, 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj2_supg_p) def get_fargs(self, mat, virtual, parameter, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg_r, _ = self.get_mapping(state) vg_u, _ = self.get_mapping(parameter) grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn_r = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return grad_u, state(), mat, vg_u, vg_r, conn_r, fmode class SDDotVolumeTerm(Term): r""" Sensitivity (shape derivative) of dot product of scalars or vectors. :Definition: .. math:: \int_{\Omega} p q (\nabla \cdot \ul{\Vcal}) \mbox{ , } \int_{\Omega} (\ul{u} \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) :Arguments: - parameter_1 : :math:`p` or :math:`\ul{u}` - parameter_2 : :math:`q` or :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_volume_dot' arg_types = ('parameter_1', 'parameter_2', 'parameter_mv') arg_shapes = [{'parameter_1' : 'D', 'parameter_2' : 'D', 'parameter_mv' : 'D'}, {'parameter_1' : 1, 'parameter_2' : 1}] function = staticmethod(terms.d_sd_volume_dot) def get_fargs(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par1) val1 = self.get(par1, 'val') val2 = self.get(par2, 'val') div_mv = self.get(par_mv, 'div') return val1, val2, div_mv, vg, get_default(term_mode, 1) def get_eval_shape(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par1) return (n_el, 1, 1, 1), par1.dtype class SDDivTerm(Term): r""" Sensitivity (shape derivative) of Stokes term `dw_stokes` in 'div' mode. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: \int_{\Omega} p [ (\nabla \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_k}{x_i} \pdiff{w_i}{x_k} ] :Arguments: - parameter_u : :math:`\ul{u}` - parameter_p : :math:`p` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div' arg_types = ('parameter_u', 'parameter_p', 'parameter_mv') arg_shapes = {'parameter_u' : 'D', 'parameter_p' : 1, 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div) def get_fargs(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) div_u = self.get(par_u, 'div') grad_u = grad_as_vector(self.get(par_u, 'grad')) val_p = self.get(par_p, 'val') div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (div_u, grad_u, val_p, div_mv, grad_mv, vg, get_default(term_mode, 1)) def get_eval_shape(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDDivGradTerm(Term): r""" Sensitivity (shape derivative) of diffusion term `dw_div_grad`. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: w \nu \int_{\Omega} [ \pdiff{u_i}{x_k} \pdiff{w_i}{x_k} (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_j}{x_k} \pdiff{u_i}{x_j} \pdiff{w_i}{x_k} - \pdiff{u_i}{x_k} \pdiff{\Vcal_l}{x_k} \pdiff{w_i}{x_k} ] :Arguments: - material : :math:`\nu` (viscosity, optional) - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div_grad' arg_types = ('opt_material', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'opt_material' : '1, 1', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div_grad) def get_fargs(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) grad_u = grad_as_vector(self.get(par_u, 'grad')) grad_w = grad_as_vector(self.get(par_w, 'grad')) div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (grad_u, grad_w, div_mv, grad_mv, mat, vg, get_default(term_mode, 1)) def get_eval_shape(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDConvectTerm(Term): r""" Sensitivity (shape derivative) of convective term `dw_convect`. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: \int_{\Omega} [ u_k \pdiff{u_i}{x_k} w_i (\nabla \cdot \Vcal) - u_k \pdiff{\Vcal_j}{x_k} \pdiff{u_i}{x_j} w_i ] :Arguments: - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_convect' arg_types = ('parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_convect) def get_fargs(self, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) val_u = self.get(par_u, 'val') grad_u = grad_as_vector(self.get(par_u, 'grad')) val_w = self.get(par_w, 'val') div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (val_u, grad_u, val_w, div_mv, grad_mv, vg,
get_default(term_mode, 1)
sfepy.base.base.get_default
import numpy as nm from sfepy.terms.terms import Term, terms from sfepy.base.base import get_default def grad_as_vector(grad): grad = grad.transpose((0, 1, 3, 2)) sh = grad.shape return grad.reshape((sh[0], sh[1], sh[2] * sh[3], 1)) class AdjDivGradTerm(Term): r""" Gateaux differential of :math:`\Psi(\ul{u}) = \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}` w.r.t. :math:`\ul{u}` in the direction :math:`\ul{v}` or adjoint term to `dw_div_grad`. :Definition: .. math:: w \delta_{u} \Psi(\ul{u}) \circ \ul{v} :Arguments: - material_1 : :math:`w` (weight) - material_2 : :math:`\nu` (viscosity) - virtual : :math:`\ul{v}` - state : :math:`\ul{u}` """ name = 'dw_adj_div_grad' arg_types = ('material_1', 'material_2', 'virtual', 'parameter') arg_shapes = {'material_1' : '1, 1', 'material_2' : '1, 1', 'virtual' : ('D', None), 'parameter' : 'D'} function = staticmethod(terms.term_ns_asm_div_grad) def get_fargs(self, mat1, mat2, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) if diff_var is None: grad = grad_as_vector(self.get(state, 'grad')) fmode = 0 else: grad = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return grad, mat1 * mat2, vg, fmode class AdjConvect1Term(Term): r""" The first adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{v} \cdot \nabla) \ul{u}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect1' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect1) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') grad_u = self.get(parameter, 'grad') # No transposition here! fmode = diff_var is not None return val_w, grad_u, vg, fmode class AdjConvect2Term(Term): r""" The second adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{u} \cdot \nabla) \ul{v}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect2' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect2) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') val_u = self.get(parameter, 'val') fmode = diff_var is not None return val_w, val_u, vg, fmode class SUPGCAdjStabilizationTerm(Term): r""" Adjoint term to SUPG stabilization term `dw_st_supg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ ((\ul{v} \cdot \nabla) \ul{u}) ((\ul{u} \cdot \nabla) \ul{w}) + ((\ul{u} \cdot \nabla) \ul{u}) ((\ul{v} \cdot \nabla) \ul{w}) ] :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_st_adj_supg_c' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj_supg_c) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_u = self.get(parameter, 'val') grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), val_u, grad_u, mat, vg, conn, fmode class SUPGPAdj1StabilizationTerm(Term): r""" The first adjoint term to SUPG stabilization term `dw_st_supg_p`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ \nabla p (\ul{v} \cdot \nabla \ul{w}) :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`p` """ name = 'dw_st_adj1_supg_p' arg_types = ('material', 'virtual', 'state', 'parameter') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 1} function = staticmethod(terms.dw_st_adj1_supg_p) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg_w, _ = self.get_mapping(state) grad_p = self.get(parameter, 'grad') conn_w = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), grad_p, mat, vg_w, conn_w, fmode class SUPGPAdj2StabilizationTerm(Term): r""" The second adjoint term to SUPG stabilization term `dw_st_supg_p` as well as adjoint term to PSPG stabilization term `dw_st_pspg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \tau_K\ \nabla r (\ul{v} \cdot \nabla \ul{u}) :Arguments: - material : :math:`\tau_K` - virtual : :math:`\ul{v}` - parameter : :math:`\ul{u}` - state : :math:`r` """ name = 'dw_st_adj2_supg_p' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 1, 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj2_supg_p) def get_fargs(self, mat, virtual, parameter, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg_r, _ = self.get_mapping(state) vg_u, _ = self.get_mapping(parameter) grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn_r = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return grad_u, state(), mat, vg_u, vg_r, conn_r, fmode class SDDotVolumeTerm(Term): r""" Sensitivity (shape derivative) of dot product of scalars or vectors. :Definition: .. math:: \int_{\Omega} p q (\nabla \cdot \ul{\Vcal}) \mbox{ , } \int_{\Omega} (\ul{u} \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) :Arguments: - parameter_1 : :math:`p` or :math:`\ul{u}` - parameter_2 : :math:`q` or :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_volume_dot' arg_types = ('parameter_1', 'parameter_2', 'parameter_mv') arg_shapes = [{'parameter_1' : 'D', 'parameter_2' : 'D', 'parameter_mv' : 'D'}, {'parameter_1' : 1, 'parameter_2' : 1}] function = staticmethod(terms.d_sd_volume_dot) def get_fargs(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par1) val1 = self.get(par1, 'val') val2 = self.get(par2, 'val') div_mv = self.get(par_mv, 'div') return val1, val2, div_mv, vg, get_default(term_mode, 1) def get_eval_shape(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par1) return (n_el, 1, 1, 1), par1.dtype class SDDivTerm(Term): r""" Sensitivity (shape derivative) of Stokes term `dw_stokes` in 'div' mode. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: \int_{\Omega} p [ (\nabla \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_k}{x_i} \pdiff{w_i}{x_k} ] :Arguments: - parameter_u : :math:`\ul{u}` - parameter_p : :math:`p` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div' arg_types = ('parameter_u', 'parameter_p', 'parameter_mv') arg_shapes = {'parameter_u' : 'D', 'parameter_p' : 1, 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div) def get_fargs(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) div_u = self.get(par_u, 'div') grad_u = grad_as_vector(self.get(par_u, 'grad')) val_p = self.get(par_p, 'val') div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (div_u, grad_u, val_p, div_mv, grad_mv, vg, get_default(term_mode, 1)) def get_eval_shape(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDDivGradTerm(Term): r""" Sensitivity (shape derivative) of diffusion term `dw_div_grad`. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: w \nu \int_{\Omega} [ \pdiff{u_i}{x_k} \pdiff{w_i}{x_k} (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_j}{x_k} \pdiff{u_i}{x_j} \pdiff{w_i}{x_k} - \pdiff{u_i}{x_k} \pdiff{\Vcal_l}{x_k} \pdiff{w_i}{x_k} ] :Arguments: - material : :math:`\nu` (viscosity, optional) - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div_grad' arg_types = ('opt_material', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'opt_material' : '1, 1', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div_grad) def get_fargs(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) grad_u = grad_as_vector(self.get(par_u, 'grad')) grad_w = grad_as_vector(self.get(par_w, 'grad')) div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (grad_u, grad_w, div_mv, grad_mv, mat, vg, get_default(term_mode, 1)) def get_eval_shape(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDConvectTerm(Term): r""" Sensitivity (shape derivative) of convective term `dw_convect`. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: \int_{\Omega} [ u_k \pdiff{u_i}{x_k} w_i (\nabla \cdot \Vcal) - u_k \pdiff{\Vcal_j}{x_k} \pdiff{u_i}{x_j} w_i ] :Arguments: - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_convect' arg_types = ('parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_convect) def get_fargs(self, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) val_u = self.get(par_u, 'val') grad_u = grad_as_vector(self.get(par_u, 'grad')) val_w = self.get(par_w, 'val') div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (val_u, grad_u, val_w, div_mv, grad_mv, vg, get_default(term_mode, 1)) def get_eval_shape(self, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class NSOFMinGradTerm(Term): name = 'd_of_ns_min_grad' arg_types = ('material_1', 'material_2', 'parameter') arg_shapes = {'material_1' : '1, 1', 'material_2' : '1, 1', 'parameter' : 1} function = staticmethod(terms.d_of_nsMinGrad) def get_fargs(self, weight, mat, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(parameter) grad = grad_as_vector(self.get(parameter, 'grad')) return grad, weight * mat, vg def get_eval_shape(self, weight, mat, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): return (1, 1, 1, 1), parameter.dtype class NSOFSurfMinDPressTerm(Term): r""" Sensitivity of :math:`\Psi(p)`. :Definition: .. math:: \delta \Psi(p) = \delta \left( \int_{\Gamma_{in}}p - \int_{\Gamma_{out}}bpress \right) :Arguments: - material_1 : :math:`w` (weight) - material_2 : :math:`bpress` (given pressure) - parameter : :math:`p` """ name = 'd_of_ns_surf_min_d_press' arg_types = ('material_1', 'material_2', 'parameter') arg_shapes = {'material_1' : 1, 'material_2' : 1, 'parameter' : 1} integration = 'surface' function = staticmethod(terms.d_of_nsSurfMinDPress) def get_fargs(self, weight, bpress, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): sg, _ = self.get_mapping(parameter) val_p = self.get(parameter, 'val') return val_p, weight, bpress, sg, 0 def get_eval_shape(self, weight, bpress, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): return (1, 1, 1, 1), parameter.dtype class NSOFSurfMinDPressDiffTerm(NSOFSurfMinDPressTerm): r""" Gateaux differential of :math:`\Psi(p)` w.r.t. :math:`p` in the direction :math:`q`. :Definition: .. math:: w \delta_{p} \Psi(p) \circ q :Arguments: - material : :math:`w` (weight) - virtual : :math:`q` """ name = 'dw_of_ns_surf_min_d_press_diff' arg_types = ('material', 'virtual') arg_shapes = {'material' : 1, 'virtual' : (1, None)} def get_fargs(self, weight, virtual, mode=None, term_mode=None, diff_var=None, **kwargs): sg, _ = self.get_mapping(virtual) aux = nm.array([0], ndmin=4, dtype=nm.float64) return aux, weight, 0.0, sg, 1 class SDGradDivStabilizationTerm(Term): r""" Sensitivity (shape derivative) of stabilization term `dw_st_grad_div`. :Definition: .. math:: \gamma \int_{\Omega} [ (\nabla \cdot \ul{u}) (\nabla \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) - \pdiff{u_i}{x_k} \pdiff{\Vcal_k}{x_i} (\nabla \cdot \ul{w}) - (\nabla \cdot \ul{u}) \pdiff{w_i}{x_k} \pdiff{\Vcal_k}{x_i} ] :Arguments: - material : :math:`\gamma` - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` - mode : 1 (sensitivity) or 0 (original term value) """ name = 'd_sd_st_grad_div' arg_types = ('material', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'material' : '1, 1', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_st_grad_div) def get_fargs(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) div_u = self.get(par_u, 'div') grad_u = grad_as_vector(self.get(par_u, 'grad')) div_w = self.get(par_w, 'div') grad_w = grad_as_vector(self.get(par_w, 'grad')) div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (div_u, grad_u, div_w, grad_w, div_mv, grad_mv, mat, vg,
get_default(term_mode, 1)
sfepy.base.base.get_default
import numpy as nm from sfepy.terms.terms import Term, terms from sfepy.base.base import get_default def grad_as_vector(grad): grad = grad.transpose((0, 1, 3, 2)) sh = grad.shape return grad.reshape((sh[0], sh[1], sh[2] * sh[3], 1)) class AdjDivGradTerm(Term): r""" Gateaux differential of :math:`\Psi(\ul{u}) = \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}` w.r.t. :math:`\ul{u}` in the direction :math:`\ul{v}` or adjoint term to `dw_div_grad`. :Definition: .. math:: w \delta_{u} \Psi(\ul{u}) \circ \ul{v} :Arguments: - material_1 : :math:`w` (weight) - material_2 : :math:`\nu` (viscosity) - virtual : :math:`\ul{v}` - state : :math:`\ul{u}` """ name = 'dw_adj_div_grad' arg_types = ('material_1', 'material_2', 'virtual', 'parameter') arg_shapes = {'material_1' : '1, 1', 'material_2' : '1, 1', 'virtual' : ('D', None), 'parameter' : 'D'} function = staticmethod(terms.term_ns_asm_div_grad) def get_fargs(self, mat1, mat2, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) if diff_var is None: grad = grad_as_vector(self.get(state, 'grad')) fmode = 0 else: grad = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return grad, mat1 * mat2, vg, fmode class AdjConvect1Term(Term): r""" The first adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{v} \cdot \nabla) \ul{u}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect1' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect1) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') grad_u = self.get(parameter, 'grad') # No transposition here! fmode = diff_var is not None return val_w, grad_u, vg, fmode class AdjConvect2Term(Term): r""" The second adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{u} \cdot \nabla) \ul{v}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect2' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect2) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') val_u = self.get(parameter, 'val') fmode = diff_var is not None return val_w, val_u, vg, fmode class SUPGCAdjStabilizationTerm(Term): r""" Adjoint term to SUPG stabilization term `dw_st_supg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ ((\ul{v} \cdot \nabla) \ul{u}) ((\ul{u} \cdot \nabla) \ul{w}) + ((\ul{u} \cdot \nabla) \ul{u}) ((\ul{v} \cdot \nabla) \ul{w}) ] :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_st_adj_supg_c' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj_supg_c) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_u = self.get(parameter, 'val') grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), val_u, grad_u, mat, vg, conn, fmode class SUPGPAdj1StabilizationTerm(Term): r""" The first adjoint term to SUPG stabilization term `dw_st_supg_p`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ \nabla p (\ul{v} \cdot \nabla \ul{w}) :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`p` """ name = 'dw_st_adj1_supg_p' arg_types = ('material', 'virtual', 'state', 'parameter') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 1} function = staticmethod(terms.dw_st_adj1_supg_p) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg_w, _ = self.get_mapping(state) grad_p = self.get(parameter, 'grad') conn_w = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), grad_p, mat, vg_w, conn_w, fmode class SUPGPAdj2StabilizationTerm(Term): r""" The second adjoint term to SUPG stabilization term `dw_st_supg_p` as well as adjoint term to PSPG stabilization term `dw_st_pspg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \tau_K\ \nabla r (\ul{v} \cdot \nabla \ul{u}) :Arguments: - material : :math:`\tau_K` - virtual : :math:`\ul{v}` - parameter : :math:`\ul{u}` - state : :math:`r` """ name = 'dw_st_adj2_supg_p' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 1, 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj2_supg_p) def get_fargs(self, mat, virtual, parameter, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg_r, _ = self.get_mapping(state) vg_u, _ = self.get_mapping(parameter) grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn_r = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return grad_u, state(), mat, vg_u, vg_r, conn_r, fmode class SDDotVolumeTerm(Term): r""" Sensitivity (shape derivative) of dot product of scalars or vectors. :Definition: .. math:: \int_{\Omega} p q (\nabla \cdot \ul{\Vcal}) \mbox{ , } \int_{\Omega} (\ul{u} \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) :Arguments: - parameter_1 : :math:`p` or :math:`\ul{u}` - parameter_2 : :math:`q` or :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_volume_dot' arg_types = ('parameter_1', 'parameter_2', 'parameter_mv') arg_shapes = [{'parameter_1' : 'D', 'parameter_2' : 'D', 'parameter_mv' : 'D'}, {'parameter_1' : 1, 'parameter_2' : 1}] function = staticmethod(terms.d_sd_volume_dot) def get_fargs(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par1) val1 = self.get(par1, 'val') val2 = self.get(par2, 'val') div_mv = self.get(par_mv, 'div') return val1, val2, div_mv, vg, get_default(term_mode, 1) def get_eval_shape(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par1) return (n_el, 1, 1, 1), par1.dtype class SDDivTerm(Term): r""" Sensitivity (shape derivative) of Stokes term `dw_stokes` in 'div' mode. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: \int_{\Omega} p [ (\nabla \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_k}{x_i} \pdiff{w_i}{x_k} ] :Arguments: - parameter_u : :math:`\ul{u}` - parameter_p : :math:`p` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div' arg_types = ('parameter_u', 'parameter_p', 'parameter_mv') arg_shapes = {'parameter_u' : 'D', 'parameter_p' : 1, 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div) def get_fargs(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) div_u = self.get(par_u, 'div') grad_u = grad_as_vector(self.get(par_u, 'grad')) val_p = self.get(par_p, 'val') div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (div_u, grad_u, val_p, div_mv, grad_mv, vg, get_default(term_mode, 1)) def get_eval_shape(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDDivGradTerm(Term): r""" Sensitivity (shape derivative) of diffusion term `dw_div_grad`. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: w \nu \int_{\Omega} [ \pdiff{u_i}{x_k} \pdiff{w_i}{x_k} (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_j}{x_k} \pdiff{u_i}{x_j} \pdiff{w_i}{x_k} - \pdiff{u_i}{x_k} \pdiff{\Vcal_l}{x_k} \pdiff{w_i}{x_k} ] :Arguments: - material : :math:`\nu` (viscosity, optional) - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div_grad' arg_types = ('opt_material', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'opt_material' : '1, 1', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div_grad) def get_fargs(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) grad_u = grad_as_vector(self.get(par_u, 'grad')) grad_w = grad_as_vector(self.get(par_w, 'grad')) div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (grad_u, grad_w, div_mv, grad_mv, mat, vg, get_default(term_mode, 1)) def get_eval_shape(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDConvectTerm(Term): r""" Sensitivity (shape derivative) of convective term `dw_convect`. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: \int_{\Omega} [ u_k \pdiff{u_i}{x_k} w_i (\nabla \cdot \Vcal) - u_k \pdiff{\Vcal_j}{x_k} \pdiff{u_i}{x_j} w_i ] :Arguments: - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_convect' arg_types = ('parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_convect) def get_fargs(self, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) val_u = self.get(par_u, 'val') grad_u = grad_as_vector(self.get(par_u, 'grad')) val_w = self.get(par_w, 'val') div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (val_u, grad_u, val_w, div_mv, grad_mv, vg, get_default(term_mode, 1)) def get_eval_shape(self, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class NSOFMinGradTerm(Term): name = 'd_of_ns_min_grad' arg_types = ('material_1', 'material_2', 'parameter') arg_shapes = {'material_1' : '1, 1', 'material_2' : '1, 1', 'parameter' : 1} function = staticmethod(terms.d_of_nsMinGrad) def get_fargs(self, weight, mat, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(parameter) grad = grad_as_vector(self.get(parameter, 'grad')) return grad, weight * mat, vg def get_eval_shape(self, weight, mat, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): return (1, 1, 1, 1), parameter.dtype class NSOFSurfMinDPressTerm(Term): r""" Sensitivity of :math:`\Psi(p)`. :Definition: .. math:: \delta \Psi(p) = \delta \left( \int_{\Gamma_{in}}p - \int_{\Gamma_{out}}bpress \right) :Arguments: - material_1 : :math:`w` (weight) - material_2 : :math:`bpress` (given pressure) - parameter : :math:`p` """ name = 'd_of_ns_surf_min_d_press' arg_types = ('material_1', 'material_2', 'parameter') arg_shapes = {'material_1' : 1, 'material_2' : 1, 'parameter' : 1} integration = 'surface' function = staticmethod(terms.d_of_nsSurfMinDPress) def get_fargs(self, weight, bpress, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): sg, _ = self.get_mapping(parameter) val_p = self.get(parameter, 'val') return val_p, weight, bpress, sg, 0 def get_eval_shape(self, weight, bpress, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): return (1, 1, 1, 1), parameter.dtype class NSOFSurfMinDPressDiffTerm(NSOFSurfMinDPressTerm): r""" Gateaux differential of :math:`\Psi(p)` w.r.t. :math:`p` in the direction :math:`q`. :Definition: .. math:: w \delta_{p} \Psi(p) \circ q :Arguments: - material : :math:`w` (weight) - virtual : :math:`q` """ name = 'dw_of_ns_surf_min_d_press_diff' arg_types = ('material', 'virtual') arg_shapes = {'material' : 1, 'virtual' : (1, None)} def get_fargs(self, weight, virtual, mode=None, term_mode=None, diff_var=None, **kwargs): sg, _ = self.get_mapping(virtual) aux = nm.array([0], ndmin=4, dtype=nm.float64) return aux, weight, 0.0, sg, 1 class SDGradDivStabilizationTerm(Term): r""" Sensitivity (shape derivative) of stabilization term `dw_st_grad_div`. :Definition: .. math:: \gamma \int_{\Omega} [ (\nabla \cdot \ul{u}) (\nabla \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) - \pdiff{u_i}{x_k} \pdiff{\Vcal_k}{x_i} (\nabla \cdot \ul{w}) - (\nabla \cdot \ul{u}) \pdiff{w_i}{x_k} \pdiff{\Vcal_k}{x_i} ] :Arguments: - material : :math:`\gamma` - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` - mode : 1 (sensitivity) or 0 (original term value) """ name = 'd_sd_st_grad_div' arg_types = ('material', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'material' : '1, 1', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_st_grad_div) def get_fargs(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) div_u = self.get(par_u, 'div') grad_u = grad_as_vector(self.get(par_u, 'grad')) div_w = self.get(par_w, 'div') grad_w = grad_as_vector(self.get(par_w, 'grad')) div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (div_u, grad_u, div_w, grad_w, div_mv, grad_mv, mat, vg, get_default(term_mode, 1)) def get_eval_shape(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDSUPGCStabilizationTerm(Term): r""" Sensitivity (shape derivative) of stabilization term `dw_st_supg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ (\ul{b} \cdot \nabla u_k) (\ul{b} \cdot \nabla w_k) (\nabla \cdot \Vcal) - (\ul{b} \cdot \nabla \Vcal_i) \pdiff{u_k}{x_i} (\ul{b} \cdot \nabla w_k) - (\ul{u} \cdot \nabla u_k) (\ul{b} \cdot \nabla \Vcal_i) \pdiff{w_k}{x_i} ] :Arguments: - material : :math:`\delta_K` - parameter_b : :math:`\ul{b}` - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` - mode : 1 (sensitivity) or 0 (original term value) """ name = 'd_sd_st_supg_c' arg_types = ('material', 'parameter_b', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'material' : '1, 1', 'parameter_b' : 'D', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_st_supg_c) def get_fargs(self, mat, par_b, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) val_b = self.get(par_b, 'val') grad_u = self.get(par_u, 'grad').transpose((0, 1, 3, 2)).copy() grad_w = self.get(par_w, 'grad').transpose((0, 1, 3, 2)).copy() div_mv = self.get(par_mv, 'div') grad_mv = self.get(par_mv, 'grad').transpose((0, 1, 3, 2)).copy() return (val_b, grad_u, grad_w, div_mv, grad_mv, mat, vg,
get_default(term_mode, 1)
sfepy.base.base.get_default
import numpy as nm from sfepy.terms.terms import Term, terms from sfepy.base.base import get_default def grad_as_vector(grad): grad = grad.transpose((0, 1, 3, 2)) sh = grad.shape return grad.reshape((sh[0], sh[1], sh[2] * sh[3], 1)) class AdjDivGradTerm(Term): r""" Gateaux differential of :math:`\Psi(\ul{u}) = \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}` w.r.t. :math:`\ul{u}` in the direction :math:`\ul{v}` or adjoint term to `dw_div_grad`. :Definition: .. math:: w \delta_{u} \Psi(\ul{u}) \circ \ul{v} :Arguments: - material_1 : :math:`w` (weight) - material_2 : :math:`\nu` (viscosity) - virtual : :math:`\ul{v}` - state : :math:`\ul{u}` """ name = 'dw_adj_div_grad' arg_types = ('material_1', 'material_2', 'virtual', 'parameter') arg_shapes = {'material_1' : '1, 1', 'material_2' : '1, 1', 'virtual' : ('D', None), 'parameter' : 'D'} function = staticmethod(terms.term_ns_asm_div_grad) def get_fargs(self, mat1, mat2, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) if diff_var is None: grad = grad_as_vector(self.get(state, 'grad')) fmode = 0 else: grad = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return grad, mat1 * mat2, vg, fmode class AdjConvect1Term(Term): r""" The first adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{v} \cdot \nabla) \ul{u}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect1' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect1) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') grad_u = self.get(parameter, 'grad') # No transposition here! fmode = diff_var is not None return val_w, grad_u, vg, fmode class AdjConvect2Term(Term): r""" The second adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{u} \cdot \nabla) \ul{v}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect2' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect2) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') val_u = self.get(parameter, 'val') fmode = diff_var is not None return val_w, val_u, vg, fmode class SUPGCAdjStabilizationTerm(Term): r""" Adjoint term to SUPG stabilization term `dw_st_supg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ ((\ul{v} \cdot \nabla) \ul{u}) ((\ul{u} \cdot \nabla) \ul{w}) + ((\ul{u} \cdot \nabla) \ul{u}) ((\ul{v} \cdot \nabla) \ul{w}) ] :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_st_adj_supg_c' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj_supg_c) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_u = self.get(parameter, 'val') grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), val_u, grad_u, mat, vg, conn, fmode class SUPGPAdj1StabilizationTerm(Term): r""" The first adjoint term to SUPG stabilization term `dw_st_supg_p`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ \nabla p (\ul{v} \cdot \nabla \ul{w}) :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`p` """ name = 'dw_st_adj1_supg_p' arg_types = ('material', 'virtual', 'state', 'parameter') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 1} function = staticmethod(terms.dw_st_adj1_supg_p) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg_w, _ = self.get_mapping(state) grad_p = self.get(parameter, 'grad') conn_w = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), grad_p, mat, vg_w, conn_w, fmode class SUPGPAdj2StabilizationTerm(Term): r""" The second adjoint term to SUPG stabilization term `dw_st_supg_p` as well as adjoint term to PSPG stabilization term `dw_st_pspg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \tau_K\ \nabla r (\ul{v} \cdot \nabla \ul{u}) :Arguments: - material : :math:`\tau_K` - virtual : :math:`\ul{v}` - parameter : :math:`\ul{u}` - state : :math:`r` """ name = 'dw_st_adj2_supg_p' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 1, 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj2_supg_p) def get_fargs(self, mat, virtual, parameter, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg_r, _ = self.get_mapping(state) vg_u, _ = self.get_mapping(parameter) grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn_r = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return grad_u, state(), mat, vg_u, vg_r, conn_r, fmode class SDDotVolumeTerm(Term): r""" Sensitivity (shape derivative) of dot product of scalars or vectors. :Definition: .. math:: \int_{\Omega} p q (\nabla \cdot \ul{\Vcal}) \mbox{ , } \int_{\Omega} (\ul{u} \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) :Arguments: - parameter_1 : :math:`p` or :math:`\ul{u}` - parameter_2 : :math:`q` or :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_volume_dot' arg_types = ('parameter_1', 'parameter_2', 'parameter_mv') arg_shapes = [{'parameter_1' : 'D', 'parameter_2' : 'D', 'parameter_mv' : 'D'}, {'parameter_1' : 1, 'parameter_2' : 1}] function = staticmethod(terms.d_sd_volume_dot) def get_fargs(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par1) val1 = self.get(par1, 'val') val2 = self.get(par2, 'val') div_mv = self.get(par_mv, 'div') return val1, val2, div_mv, vg, get_default(term_mode, 1) def get_eval_shape(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par1) return (n_el, 1, 1, 1), par1.dtype class SDDivTerm(Term): r""" Sensitivity (shape derivative) of Stokes term `dw_stokes` in 'div' mode. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: \int_{\Omega} p [ (\nabla \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_k}{x_i} \pdiff{w_i}{x_k} ] :Arguments: - parameter_u : :math:`\ul{u}` - parameter_p : :math:`p` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div' arg_types = ('parameter_u', 'parameter_p', 'parameter_mv') arg_shapes = {'parameter_u' : 'D', 'parameter_p' : 1, 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div) def get_fargs(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) div_u = self.get(par_u, 'div') grad_u = grad_as_vector(self.get(par_u, 'grad')) val_p = self.get(par_p, 'val') div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (div_u, grad_u, val_p, div_mv, grad_mv, vg, get_default(term_mode, 1)) def get_eval_shape(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDDivGradTerm(Term): r""" Sensitivity (shape derivative) of diffusion term `dw_div_grad`. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: w \nu \int_{\Omega} [ \pdiff{u_i}{x_k} \pdiff{w_i}{x_k} (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_j}{x_k} \pdiff{u_i}{x_j} \pdiff{w_i}{x_k} - \pdiff{u_i}{x_k} \pdiff{\Vcal_l}{x_k} \pdiff{w_i}{x_k} ] :Arguments: - material : :math:`\nu` (viscosity, optional) - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div_grad' arg_types = ('opt_material', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'opt_material' : '1, 1', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div_grad) def get_fargs(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) grad_u = grad_as_vector(self.get(par_u, 'grad')) grad_w = grad_as_vector(self.get(par_w, 'grad')) div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (grad_u, grad_w, div_mv, grad_mv, mat, vg, get_default(term_mode, 1)) def get_eval_shape(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDConvectTerm(Term): r""" Sensitivity (shape derivative) of convective term `dw_convect`. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: \int_{\Omega} [ u_k \pdiff{u_i}{x_k} w_i (\nabla \cdot \Vcal) - u_k \pdiff{\Vcal_j}{x_k} \pdiff{u_i}{x_j} w_i ] :Arguments: - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_convect' arg_types = ('parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_convect) def get_fargs(self, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) val_u = self.get(par_u, 'val') grad_u = grad_as_vector(self.get(par_u, 'grad')) val_w = self.get(par_w, 'val') div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (val_u, grad_u, val_w, div_mv, grad_mv, vg, get_default(term_mode, 1)) def get_eval_shape(self, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class NSOFMinGradTerm(Term): name = 'd_of_ns_min_grad' arg_types = ('material_1', 'material_2', 'parameter') arg_shapes = {'material_1' : '1, 1', 'material_2' : '1, 1', 'parameter' : 1} function = staticmethod(terms.d_of_nsMinGrad) def get_fargs(self, weight, mat, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(parameter) grad = grad_as_vector(self.get(parameter, 'grad')) return grad, weight * mat, vg def get_eval_shape(self, weight, mat, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): return (1, 1, 1, 1), parameter.dtype class NSOFSurfMinDPressTerm(Term): r""" Sensitivity of :math:`\Psi(p)`. :Definition: .. math:: \delta \Psi(p) = \delta \left( \int_{\Gamma_{in}}p - \int_{\Gamma_{out}}bpress \right) :Arguments: - material_1 : :math:`w` (weight) - material_2 : :math:`bpress` (given pressure) - parameter : :math:`p` """ name = 'd_of_ns_surf_min_d_press' arg_types = ('material_1', 'material_2', 'parameter') arg_shapes = {'material_1' : 1, 'material_2' : 1, 'parameter' : 1} integration = 'surface' function = staticmethod(terms.d_of_nsSurfMinDPress) def get_fargs(self, weight, bpress, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): sg, _ = self.get_mapping(parameter) val_p = self.get(parameter, 'val') return val_p, weight, bpress, sg, 0 def get_eval_shape(self, weight, bpress, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): return (1, 1, 1, 1), parameter.dtype class NSOFSurfMinDPressDiffTerm(NSOFSurfMinDPressTerm): r""" Gateaux differential of :math:`\Psi(p)` w.r.t. :math:`p` in the direction :math:`q`. :Definition: .. math:: w \delta_{p} \Psi(p) \circ q :Arguments: - material : :math:`w` (weight) - virtual : :math:`q` """ name = 'dw_of_ns_surf_min_d_press_diff' arg_types = ('material', 'virtual') arg_shapes = {'material' : 1, 'virtual' : (1, None)} def get_fargs(self, weight, virtual, mode=None, term_mode=None, diff_var=None, **kwargs): sg, _ = self.get_mapping(virtual) aux = nm.array([0], ndmin=4, dtype=nm.float64) return aux, weight, 0.0, sg, 1 class SDGradDivStabilizationTerm(Term): r""" Sensitivity (shape derivative) of stabilization term `dw_st_grad_div`. :Definition: .. math:: \gamma \int_{\Omega} [ (\nabla \cdot \ul{u}) (\nabla \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) - \pdiff{u_i}{x_k} \pdiff{\Vcal_k}{x_i} (\nabla \cdot \ul{w}) - (\nabla \cdot \ul{u}) \pdiff{w_i}{x_k} \pdiff{\Vcal_k}{x_i} ] :Arguments: - material : :math:`\gamma` - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` - mode : 1 (sensitivity) or 0 (original term value) """ name = 'd_sd_st_grad_div' arg_types = ('material', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'material' : '1, 1', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_st_grad_div) def get_fargs(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) div_u = self.get(par_u, 'div') grad_u = grad_as_vector(self.get(par_u, 'grad')) div_w = self.get(par_w, 'div') grad_w = grad_as_vector(self.get(par_w, 'grad')) div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (div_u, grad_u, div_w, grad_w, div_mv, grad_mv, mat, vg, get_default(term_mode, 1)) def get_eval_shape(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDSUPGCStabilizationTerm(Term): r""" Sensitivity (shape derivative) of stabilization term `dw_st_supg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ (\ul{b} \cdot \nabla u_k) (\ul{b} \cdot \nabla w_k) (\nabla \cdot \Vcal) - (\ul{b} \cdot \nabla \Vcal_i) \pdiff{u_k}{x_i} (\ul{b} \cdot \nabla w_k) - (\ul{u} \cdot \nabla u_k) (\ul{b} \cdot \nabla \Vcal_i) \pdiff{w_k}{x_i} ] :Arguments: - material : :math:`\delta_K` - parameter_b : :math:`\ul{b}` - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` - mode : 1 (sensitivity) or 0 (original term value) """ name = 'd_sd_st_supg_c' arg_types = ('material', 'parameter_b', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'material' : '1, 1', 'parameter_b' : 'D', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_st_supg_c) def get_fargs(self, mat, par_b, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) val_b = self.get(par_b, 'val') grad_u = self.get(par_u, 'grad').transpose((0, 1, 3, 2)).copy() grad_w = self.get(par_w, 'grad').transpose((0, 1, 3, 2)).copy() div_mv = self.get(par_mv, 'div') grad_mv = self.get(par_mv, 'grad').transpose((0, 1, 3, 2)).copy() return (val_b, grad_u, grad_w, div_mv, grad_mv, mat, vg, get_default(term_mode, 1)) def get_eval_shape(self, mat, par_b, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDPSPGCStabilizationTerm(Term): r""" Sensitivity (shape derivative) of stabilization terms `dw_st_supg_p` or `dw_st_pspg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ \pdiff{r}{x_i} (\ul{b} \cdot \nabla u_i) (\nabla \cdot \Vcal) - \pdiff{r}{x_k} \pdiff{\Vcal_k}{x_i} (\ul{b} \cdot \nabla u_i) - \pdiff{r}{x_k} (\ul{b} \cdot \nabla \Vcal_k) \pdiff{u_i}{x_k} ] :Arguments: - material : :math:`\delta_K` - parameter_b : :math:`\ul{b}` - parameter_u : :math:`\ul{u}` - parameter_r : :math:`r` - parameter_mv : :math:`\ul{\Vcal}` - mode : 1 (sensitivity) or 0 (original term value) """ name = 'd_sd_st_pspg_c' arg_types = ('material', 'parameter_b', 'parameter_u', 'parameter_r', 'parameter_mv') arg_shapes = {'material' : '1, 1', 'parameter_b' : 'D', 'parameter_u' : 'D', 'parameter_r' : 1, 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_st_pspg_c) def get_fargs(self, mat, par_b, par_u, par_r, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) val_b = self.get(par_b, 'val') grad_u = self.get(par_u, 'grad').transpose((0, 1, 3, 2)).copy() grad_r = self.get(par_r, 'grad') div_mv = self.get(par_mv, 'div') grad_mv = self.get(par_mv, 'grad').transpose((0, 1, 3, 2)).copy() return (val_b, grad_u, grad_r, div_mv, grad_mv, mat, vg,
get_default(term_mode, 1)
sfepy.base.base.get_default
import numpy as nm from sfepy.terms.terms import Term, terms from sfepy.base.base import get_default def grad_as_vector(grad): grad = grad.transpose((0, 1, 3, 2)) sh = grad.shape return grad.reshape((sh[0], sh[1], sh[2] * sh[3], 1)) class AdjDivGradTerm(Term): r""" Gateaux differential of :math:`\Psi(\ul{u}) = \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}` w.r.t. :math:`\ul{u}` in the direction :math:`\ul{v}` or adjoint term to `dw_div_grad`. :Definition: .. math:: w \delta_{u} \Psi(\ul{u}) \circ \ul{v} :Arguments: - material_1 : :math:`w` (weight) - material_2 : :math:`\nu` (viscosity) - virtual : :math:`\ul{v}` - state : :math:`\ul{u}` """ name = 'dw_adj_div_grad' arg_types = ('material_1', 'material_2', 'virtual', 'parameter') arg_shapes = {'material_1' : '1, 1', 'material_2' : '1, 1', 'virtual' : ('D', None), 'parameter' : 'D'} function = staticmethod(terms.term_ns_asm_div_grad) def get_fargs(self, mat1, mat2, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) if diff_var is None: grad = grad_as_vector(self.get(state, 'grad')) fmode = 0 else: grad = nm.array([0], ndmin=4, dtype=nm.float64) fmode = 1 return grad, mat1 * mat2, vg, fmode class AdjConvect1Term(Term): r""" The first adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{v} \cdot \nabla) \ul{u}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect1' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect1) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') grad_u = self.get(parameter, 'grad') # No transposition here! fmode = diff_var is not None return val_w, grad_u, vg, fmode class AdjConvect2Term(Term): r""" The second adjoint term to nonlinear convective term `dw_convect`. :Definition: .. math:: \int_{\Omega} ((\ul{u} \cdot \nabla) \ul{v}) \cdot \ul{w} :Arguments: - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_adj_convect2' arg_types = ('virtual', 'state', 'parameter' ) arg_shapes = {'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_adj_convect2) def get_fargs(self, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_w = self.get(state, 'val') val_u = self.get(parameter, 'val') fmode = diff_var is not None return val_w, val_u, vg, fmode class SUPGCAdjStabilizationTerm(Term): r""" Adjoint term to SUPG stabilization term `dw_st_supg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ ((\ul{v} \cdot \nabla) \ul{u}) ((\ul{u} \cdot \nabla) \ul{w}) + ((\ul{u} \cdot \nabla) \ul{u}) ((\ul{v} \cdot \nabla) \ul{w}) ] :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`\ul{u}` """ name = 'dw_st_adj_supg_c' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj_supg_c) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(state) val_u = self.get(parameter, 'val') grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), val_u, grad_u, mat, vg, conn, fmode class SUPGPAdj1StabilizationTerm(Term): r""" The first adjoint term to SUPG stabilization term `dw_st_supg_p`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ \nabla p (\ul{v} \cdot \nabla \ul{w}) :Arguments: - material : :math:`\delta_K` - virtual : :math:`\ul{v}` - state : :math:`\ul{w}` - parameter : :math:`p` """ name = 'dw_st_adj1_supg_p' arg_types = ('material', 'virtual', 'state', 'parameter') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 'D', 'parameter' : 1} function = staticmethod(terms.dw_st_adj1_supg_p) def get_fargs(self, mat, virtual, state, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg_w, _ = self.get_mapping(state) grad_p = self.get(parameter, 'grad') conn_w = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return state(), grad_p, mat, vg_w, conn_w, fmode class SUPGPAdj2StabilizationTerm(Term): r""" The second adjoint term to SUPG stabilization term `dw_st_supg_p` as well as adjoint term to PSPG stabilization term `dw_st_pspg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \tau_K\ \nabla r (\ul{v} \cdot \nabla \ul{u}) :Arguments: - material : :math:`\tau_K` - virtual : :math:`\ul{v}` - parameter : :math:`\ul{u}` - state : :math:`r` """ name = 'dw_st_adj2_supg_p' arg_types = ('material', 'virtual', 'parameter', 'state') arg_shapes = {'material' : '1, 1', 'virtual' : ('D', 'state'), 'state' : 1, 'parameter' : 'D'} function = staticmethod(terms.dw_st_adj2_supg_p) def get_fargs(self, mat, virtual, parameter, state, mode=None, term_mode=None, diff_var=None, **kwargs): vg_r, _ = self.get_mapping(state) vg_u, _ = self.get_mapping(parameter) grad_u = self.get(parameter, 'grad').transpose((0, 1, 3, 2)).copy() conn_r = state.field.get_connectivity(self.region, self.integration) fmode = diff_var is not None return grad_u, state(), mat, vg_u, vg_r, conn_r, fmode class SDDotVolumeTerm(Term): r""" Sensitivity (shape derivative) of dot product of scalars or vectors. :Definition: .. math:: \int_{\Omega} p q (\nabla \cdot \ul{\Vcal}) \mbox{ , } \int_{\Omega} (\ul{u} \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) :Arguments: - parameter_1 : :math:`p` or :math:`\ul{u}` - parameter_2 : :math:`q` or :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_volume_dot' arg_types = ('parameter_1', 'parameter_2', 'parameter_mv') arg_shapes = [{'parameter_1' : 'D', 'parameter_2' : 'D', 'parameter_mv' : 'D'}, {'parameter_1' : 1, 'parameter_2' : 1}] function = staticmethod(terms.d_sd_volume_dot) def get_fargs(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par1) val1 = self.get(par1, 'val') val2 = self.get(par2, 'val') div_mv = self.get(par_mv, 'div') return val1, val2, div_mv, vg, get_default(term_mode, 1) def get_eval_shape(self, par1, par2, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par1) return (n_el, 1, 1, 1), par1.dtype class SDDivTerm(Term): r""" Sensitivity (shape derivative) of Stokes term `dw_stokes` in 'div' mode. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: \int_{\Omega} p [ (\nabla \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_k}{x_i} \pdiff{w_i}{x_k} ] :Arguments: - parameter_u : :math:`\ul{u}` - parameter_p : :math:`p` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div' arg_types = ('parameter_u', 'parameter_p', 'parameter_mv') arg_shapes = {'parameter_u' : 'D', 'parameter_p' : 1, 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div) def get_fargs(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) div_u = self.get(par_u, 'div') grad_u = grad_as_vector(self.get(par_u, 'grad')) val_p = self.get(par_p, 'val') div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (div_u, grad_u, val_p, div_mv, grad_mv, vg, get_default(term_mode, 1)) def get_eval_shape(self, par_u, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDDivGradTerm(Term): r""" Sensitivity (shape derivative) of diffusion term `dw_div_grad`. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: w \nu \int_{\Omega} [ \pdiff{u_i}{x_k} \pdiff{w_i}{x_k} (\nabla \cdot \ul{\Vcal}) - \pdiff{\Vcal_j}{x_k} \pdiff{u_i}{x_j} \pdiff{w_i}{x_k} - \pdiff{u_i}{x_k} \pdiff{\Vcal_l}{x_k} \pdiff{w_i}{x_k} ] :Arguments: - material : :math:`\nu` (viscosity, optional) - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_div_grad' arg_types = ('opt_material', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'opt_material' : '1, 1', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_div_grad) def get_fargs(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) grad_u = grad_as_vector(self.get(par_u, 'grad')) grad_w = grad_as_vector(self.get(par_w, 'grad')) div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (grad_u, grad_w, div_mv, grad_mv, mat, vg, get_default(term_mode, 1)) def get_eval_shape(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDConvectTerm(Term): r""" Sensitivity (shape derivative) of convective term `dw_convect`. Supports the following term modes: 1 (sensitivity) or 0 (original term value). :Definition: .. math:: \int_{\Omega} [ u_k \pdiff{u_i}{x_k} w_i (\nabla \cdot \Vcal) - u_k \pdiff{\Vcal_j}{x_k} \pdiff{u_i}{x_j} w_i ] :Arguments: - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` """ name = 'd_sd_convect' arg_types = ('parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_convect) def get_fargs(self, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) val_u = self.get(par_u, 'val') grad_u = grad_as_vector(self.get(par_u, 'grad')) val_w = self.get(par_w, 'val') div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (val_u, grad_u, val_w, div_mv, grad_mv, vg, get_default(term_mode, 1)) def get_eval_shape(self, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class NSOFMinGradTerm(Term): name = 'd_of_ns_min_grad' arg_types = ('material_1', 'material_2', 'parameter') arg_shapes = {'material_1' : '1, 1', 'material_2' : '1, 1', 'parameter' : 1} function = staticmethod(terms.d_of_nsMinGrad) def get_fargs(self, weight, mat, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(parameter) grad = grad_as_vector(self.get(parameter, 'grad')) return grad, weight * mat, vg def get_eval_shape(self, weight, mat, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): return (1, 1, 1, 1), parameter.dtype class NSOFSurfMinDPressTerm(Term): r""" Sensitivity of :math:`\Psi(p)`. :Definition: .. math:: \delta \Psi(p) = \delta \left( \int_{\Gamma_{in}}p - \int_{\Gamma_{out}}bpress \right) :Arguments: - material_1 : :math:`w` (weight) - material_2 : :math:`bpress` (given pressure) - parameter : :math:`p` """ name = 'd_of_ns_surf_min_d_press' arg_types = ('material_1', 'material_2', 'parameter') arg_shapes = {'material_1' : 1, 'material_2' : 1, 'parameter' : 1} integration = 'surface' function = staticmethod(terms.d_of_nsSurfMinDPress) def get_fargs(self, weight, bpress, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): sg, _ = self.get_mapping(parameter) val_p = self.get(parameter, 'val') return val_p, weight, bpress, sg, 0 def get_eval_shape(self, weight, bpress, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): return (1, 1, 1, 1), parameter.dtype class NSOFSurfMinDPressDiffTerm(NSOFSurfMinDPressTerm): r""" Gateaux differential of :math:`\Psi(p)` w.r.t. :math:`p` in the direction :math:`q`. :Definition: .. math:: w \delta_{p} \Psi(p) \circ q :Arguments: - material : :math:`w` (weight) - virtual : :math:`q` """ name = 'dw_of_ns_surf_min_d_press_diff' arg_types = ('material', 'virtual') arg_shapes = {'material' : 1, 'virtual' : (1, None)} def get_fargs(self, weight, virtual, mode=None, term_mode=None, diff_var=None, **kwargs): sg, _ = self.get_mapping(virtual) aux = nm.array([0], ndmin=4, dtype=nm.float64) return aux, weight, 0.0, sg, 1 class SDGradDivStabilizationTerm(Term): r""" Sensitivity (shape derivative) of stabilization term `dw_st_grad_div`. :Definition: .. math:: \gamma \int_{\Omega} [ (\nabla \cdot \ul{u}) (\nabla \cdot \ul{w}) (\nabla \cdot \ul{\Vcal}) - \pdiff{u_i}{x_k} \pdiff{\Vcal_k}{x_i} (\nabla \cdot \ul{w}) - (\nabla \cdot \ul{u}) \pdiff{w_i}{x_k} \pdiff{\Vcal_k}{x_i} ] :Arguments: - material : :math:`\gamma` - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` - mode : 1 (sensitivity) or 0 (original term value) """ name = 'd_sd_st_grad_div' arg_types = ('material', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'material' : '1, 1', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_st_grad_div) def get_fargs(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) div_u = self.get(par_u, 'div') grad_u = grad_as_vector(self.get(par_u, 'grad')) div_w = self.get(par_w, 'div') grad_w = grad_as_vector(self.get(par_w, 'grad')) div_mv = self.get(par_mv, 'div') grad_mv = grad_as_vector(self.get(par_mv, 'grad')) return (div_u, grad_u, div_w, grad_w, div_mv, grad_mv, mat, vg, get_default(term_mode, 1)) def get_eval_shape(self, mat, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDSUPGCStabilizationTerm(Term): r""" Sensitivity (shape derivative) of stabilization term `dw_st_supg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ (\ul{b} \cdot \nabla u_k) (\ul{b} \cdot \nabla w_k) (\nabla \cdot \Vcal) - (\ul{b} \cdot \nabla \Vcal_i) \pdiff{u_k}{x_i} (\ul{b} \cdot \nabla w_k) - (\ul{u} \cdot \nabla u_k) (\ul{b} \cdot \nabla \Vcal_i) \pdiff{w_k}{x_i} ] :Arguments: - material : :math:`\delta_K` - parameter_b : :math:`\ul{b}` - parameter_u : :math:`\ul{u}` - parameter_w : :math:`\ul{w}` - parameter_mv : :math:`\ul{\Vcal}` - mode : 1 (sensitivity) or 0 (original term value) """ name = 'd_sd_st_supg_c' arg_types = ('material', 'parameter_b', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = {'material' : '1, 1', 'parameter_b' : 'D', 'parameter_u' : 'D', 'parameter_w' : 'D', 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_st_supg_c) def get_fargs(self, mat, par_b, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) val_b = self.get(par_b, 'val') grad_u = self.get(par_u, 'grad').transpose((0, 1, 3, 2)).copy() grad_w = self.get(par_w, 'grad').transpose((0, 1, 3, 2)).copy() div_mv = self.get(par_mv, 'div') grad_mv = self.get(par_mv, 'grad').transpose((0, 1, 3, 2)).copy() return (val_b, grad_u, grad_w, div_mv, grad_mv, mat, vg, get_default(term_mode, 1)) def get_eval_shape(self, mat, par_b, par_u, par_w, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDPSPGCStabilizationTerm(Term): r""" Sensitivity (shape derivative) of stabilization terms `dw_st_supg_p` or `dw_st_pspg_c`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \delta_K\ [ \pdiff{r}{x_i} (\ul{b} \cdot \nabla u_i) (\nabla \cdot \Vcal) - \pdiff{r}{x_k} \pdiff{\Vcal_k}{x_i} (\ul{b} \cdot \nabla u_i) - \pdiff{r}{x_k} (\ul{b} \cdot \nabla \Vcal_k) \pdiff{u_i}{x_k} ] :Arguments: - material : :math:`\delta_K` - parameter_b : :math:`\ul{b}` - parameter_u : :math:`\ul{u}` - parameter_r : :math:`r` - parameter_mv : :math:`\ul{\Vcal}` - mode : 1 (sensitivity) or 0 (original term value) """ name = 'd_sd_st_pspg_c' arg_types = ('material', 'parameter_b', 'parameter_u', 'parameter_r', 'parameter_mv') arg_shapes = {'material' : '1, 1', 'parameter_b' : 'D', 'parameter_u' : 'D', 'parameter_r' : 1, 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_st_pspg_c) def get_fargs(self, mat, par_b, par_u, par_r, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_u) val_b = self.get(par_b, 'val') grad_u = self.get(par_u, 'grad').transpose((0, 1, 3, 2)).copy() grad_r = self.get(par_r, 'grad') div_mv = self.get(par_mv, 'div') grad_mv = self.get(par_mv, 'grad').transpose((0, 1, 3, 2)).copy() return (val_b, grad_u, grad_r, div_mv, grad_mv, mat, vg, get_default(term_mode, 1)) def get_eval_shape(self, mat, par_b, par_u, par_r, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(par_u) return (n_el, 1, 1, 1), par_u.dtype class SDPSPGPStabilizationTerm(Term): r""" Sensitivity (shape derivative) of stabilization term `dw_st_pspg_p`. :Definition: .. math:: \sum_{K \in \Ical_h}\int_{T_K} \tau_K\ [ (\nabla r \cdot \nabla p) (\nabla \cdot \Vcal) - \pdiff{r}{x_k} (\nabla \Vcal_k \cdot \nabla p) - (\nabla r \cdot \nabla \Vcal_k) \pdiff{p}{x_k} ] :Arguments: - material : :math:`\tau_K` - parameter_r : :math:`r` - parameter_p : :math:`p` - parameter_mv : :math:`\ul{\Vcal}` - mode : 1 (sensitivity) or 0 (original term value) """ name = 'd_sd_st_pspg_p' arg_types = ('material', 'parameter_r', 'parameter_p', 'parameter_mv') arg_shapes = {'material' : '1, 1', 'parameter_r' : 1, 'parameter_p' : 1, 'parameter_mv' : 'D'} function = staticmethod(terms.d_sd_st_pspg_p) def get_fargs(self, mat, par_r, par_p, par_mv, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(par_p) grad_r = self.get(par_r, 'grad') grad_p = self.get(par_p, 'grad') div_mv = self.get(par_mv, 'div') grad_mv = self.get(par_mv, 'grad').transpose((0, 1, 3, 2)).copy() return (grad_r, grad_p, div_mv, grad_mv, mat, vg,
get_default(term_mode, 1)
sfepy.base.base.get_default
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh =
Mesh.from_file(pb.conf.filename_mesh)
sfepy.discrete.fem.Mesh.from_file
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh = Mesh.from_file(pb.conf.filename_mesh) domain =
FEDomain('domain', mesh)
sfepy.discrete.fem.FEDomain
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh = Mesh.from_file(pb.conf.filename_mesh) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scf', nm.float64, 'scalar', omega, approx_order=1) g =
FieldVariable('g', 'unknown', field)
sfepy.discrete.FieldVariable
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh = Mesh.from_file(pb.conf.filename_mesh) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scf', nm.float64, 'scalar', omega, approx_order=1) g = FieldVariable('g', 'unknown', field) f =
FieldVariable('f', 'test', field, primary_var_name='g')
sfepy.discrete.FieldVariable
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh = Mesh.from_file(pb.conf.filename_mesh) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scf', nm.float64, 'scalar', omega, approx_order=1) g = FieldVariable('g', 'unknown', field) f = FieldVariable('f', 'test', field, primary_var_name='g') integral =
Integral('i', order=2)
sfepy.discrete.Integral
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh = Mesh.from_file(pb.conf.filename_mesh) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scf', nm.float64, 'scalar', omega, approx_order=1) g = FieldVariable('g', 'unknown', field) f = FieldVariable('f', 'test', field, primary_var_name='g') integral = Integral('i', order=2) m =
Material('m', function=set_grad)
sfepy.discrete.Material
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh = Mesh.from_file(pb.conf.filename_mesh) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scf', nm.float64, 'scalar', omega, approx_order=1) g = FieldVariable('g', 'unknown', field) f = FieldVariable('f', 'test', field, primary_var_name='g') integral = Integral('i', order=2) m = Material('m', function=set_grad) t1 =
Term.new('dw_volume_dot(f, g)', integral, omega, f=f, g=g)
sfepy.terms.Term.new
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh = Mesh.from_file(pb.conf.filename_mesh) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scf', nm.float64, 'scalar', omega, approx_order=1) g = FieldVariable('g', 'unknown', field) f = FieldVariable('f', 'test', field, primary_var_name='g') integral = Integral('i', order=2) m = Material('m', function=set_grad) t1 = Term.new('dw_volume_dot(f, g)', integral, omega, f=f, g=g) t2 = Term.new('dw_volume_lvf(m.cs, f)', integral, omega, m=m, f=f) eq =
Equation('balance', t1 - t2)
sfepy.discrete.Equation
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh = Mesh.from_file(pb.conf.filename_mesh) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scf', nm.float64, 'scalar', omega, approx_order=1) g = FieldVariable('g', 'unknown', field) f = FieldVariable('f', 'test', field, primary_var_name='g') integral = Integral('i', order=2) m = Material('m', function=set_grad) t1 = Term.new('dw_volume_dot(f, g)', integral, omega, f=f, g=g) t2 = Term.new('dw_volume_lvf(m.cs, f)', integral, omega, m=m, f=f) eq = Equation('balance', t1 - t2) eqs =
Equations([eq])
sfepy.discrete.Equations
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh = Mesh.from_file(pb.conf.filename_mesh) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scf', nm.float64, 'scalar', omega, approx_order=1) g = FieldVariable('g', 'unknown', field) f = FieldVariable('f', 'test', field, primary_var_name='g') integral = Integral('i', order=2) m = Material('m', function=set_grad) t1 = Term.new('dw_volume_dot(f, g)', integral, omega, f=f, g=g) t2 = Term.new('dw_volume_lvf(m.cs, f)', integral, omega, m=m, f=f) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) ls =
ScipyDirect({})
sfepy.solvers.ls.ScipyDirect
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh = Mesh.from_file(pb.conf.filename_mesh) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scf', nm.float64, 'scalar', omega, approx_order=1) g = FieldVariable('g', 'unknown', field) f = FieldVariable('f', 'test', field, primary_var_name='g') integral = Integral('i', order=2) m = Material('m', function=set_grad) t1 = Term.new('dw_volume_dot(f, g)', integral, omega, f=f, g=g) t2 = Term.new('dw_volume_lvf(m.cs, f)', integral, omega, m=m, f=f) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) ls = ScipyDirect({}) nls_status =
IndexedStruct()
sfepy.base.base.IndexedStruct
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh = Mesh.from_file(pb.conf.filename_mesh) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scf', nm.float64, 'scalar', omega, approx_order=1) g = FieldVariable('g', 'unknown', field) f = FieldVariable('f', 'test', field, primary_var_name='g') integral = Integral('i', order=2) m = Material('m', function=set_grad) t1 = Term.new('dw_volume_dot(f, g)', integral, omega, f=f, g=g) t2 = Term.new('dw_volume_lvf(m.cs, f)', integral, omega, m=m, f=f) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) ls = ScipyDirect({}) nls_status = IndexedStruct() nls =
Newton({'eps_a': 1e-15}, lin_solver=ls, status=nls_status)
sfepy.solvers.nls.Newton
# 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 simulation: # # ./simple.py example_poropiezo-1/poropiezo_macro_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 import data_dir from sfepy.base.base import Struct from sfepy.homogenization.micmac import get_homog_coefs_linear from sfepy.homogenization.recovery import recover_micro_hook_eps data_dir = 'example_poropiezo-1' def set_grad(ts, coors, mode=None, problem=None, **kwargs): if mode == 'qp': out = problem.data.reshape((coors.shape[0], 1, 1)) return {'cs': out} # projection of values from integration points into mesh vertices def linear_projection(pb, cval): from sfepy.discrete import (FieldVariable, Material, Integral, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.base.base import IndexedStruct mesh = Mesh.from_file(pb.conf.filename_mesh) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scf', nm.float64, 'scalar', omega, approx_order=1) g = FieldVariable('g', 'unknown', field) f = FieldVariable('f', 'test', field, primary_var_name='g') integral = Integral('i', order=2) m = Material('m', function=set_grad) t1 = Term.new('dw_volume_dot(f, g)', integral, omega, f=f, g=g) t2 = Term.new('dw_volume_lvf(m.cs, f)', integral, omega, m=m, f=f) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({'eps_a': 1e-15}, lin_solver=ls, status=nls_status) pb =
Problem('elasticity', equations=eqs)
sfepy.discrete.Problem
import os import numpy as nm from sfepy.base.testing import TestCommon from sfepy import data_dir # n_cell, n_face, n_edge, n_vertex # d1 -> d2 : num, n_incident expected = { '2_3_2.mesh' : ([4, 5, 2, 0], { (0, 0) : (4, 10), (0, 1) : (4, 10), (0, 2) : (4, 6), (1, 0) : (5, 10), (1, 1) : (5, 16), (1, 2) : (5, 6), (2, 0) : (2, 6), (2, 1) : (2, 6), (2, 2) : (2, 2), }), '2_4_2.mesh' : ([6, 7, 2, 0], { (0, 0) : (6, 22), (0, 1) : (6, 14), (0, 2) : (6, 8), (1, 0) : (7, 14), (1, 1) : (7, 20), (1, 2) : (7, 8), (2, 0) : (2, 8), (2, 1) : (2, 8), (2, 2) : (2, 2), }), '3_4_2.mesh' : ([5, 9, 7, 2], { (0, 0) : (5, 18), (0, 1) : (5, 18), (0, 2) : (5, 21), (0, 3) : (5, 8), (1, 0) : (9, 18), (1, 1) : (9, 48), (1, 2) : (9, 21), (1, 3) : (9, 12), (2, 0) : (7, 21), (2, 1) : (7, 21), (2, 2) : (7, 42), (2, 3) : (7, 8), (3, 0) : (2, 8), (3, 1) : (2, 12), (3, 2) : (2, 8), (3, 3) : (2, 2), }), '3_8_2.mesh' : ([12, 20, 11, 2], { (0, 0) : (12, 100), (0, 1) : (12, 40), (0, 2) : (12, 44), (0, 3) : (12, 16), (1, 0) : (20, 40), (1, 1) : (20, 96), (1, 2) : (20, 44), (1, 3) : (20, 24), (2, 0) : (11, 44), (2, 1) : (11, 44), (2, 2) : (11, 72), (2, 3) : (11, 12), (3, 0) : (2, 16), (3, 1) : (2, 24), (3, 2) : (2, 12), (3, 3) : (2, 2), }), 'square_triquad.mesh' : ([470, 1127, 658, 0], { (0, 0) : (470, 3054), (0, 1) : (470, 2254), (0, 2) : (470, 2174), (1, 0) : (1127, 2254), (1, 1) : (1127, 9174), (1, 2) : (1127, 2174), (2, 0) : (658, 2174), (2, 1) : (658, 2174), (2, 2) : (658, 6686), }), } class Test(TestCommon): @staticmethod def from_conf(conf, options): filename_meshes = [data_dir + '/meshes/elements/%s_2.mesh' % geom for geom in ['2_3', '2_4', '3_4', '3_8']] filename_meshes.append(data_dir + '/meshes/2d/special/square_triquad.mesh') test = Test(filename_meshes=filename_meshes, conf=conf, options=options) return test def test_cmesh_counts(self): from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem.extmods.cmesh import CMesh, get_cmem_usage gels =
create_geometry_elements()
sfepy.discrete.fem.geometry_element.create_geometry_elements
import os import numpy as nm from sfepy.base.testing import TestCommon from sfepy import data_dir # n_cell, n_face, n_edge, n_vertex # d1 -> d2 : num, n_incident expected = { '2_3_2.mesh' : ([4, 5, 2, 0], { (0, 0) : (4, 10), (0, 1) : (4, 10), (0, 2) : (4, 6), (1, 0) : (5, 10), (1, 1) : (5, 16), (1, 2) : (5, 6), (2, 0) : (2, 6), (2, 1) : (2, 6), (2, 2) : (2, 2), }), '2_4_2.mesh' : ([6, 7, 2, 0], { (0, 0) : (6, 22), (0, 1) : (6, 14), (0, 2) : (6, 8), (1, 0) : (7, 14), (1, 1) : (7, 20), (1, 2) : (7, 8), (2, 0) : (2, 8), (2, 1) : (2, 8), (2, 2) : (2, 2), }), '3_4_2.mesh' : ([5, 9, 7, 2], { (0, 0) : (5, 18), (0, 1) : (5, 18), (0, 2) : (5, 21), (0, 3) : (5, 8), (1, 0) : (9, 18), (1, 1) : (9, 48), (1, 2) : (9, 21), (1, 3) : (9, 12), (2, 0) : (7, 21), (2, 1) : (7, 21), (2, 2) : (7, 42), (2, 3) : (7, 8), (3, 0) : (2, 8), (3, 1) : (2, 12), (3, 2) : (2, 8), (3, 3) : (2, 2), }), '3_8_2.mesh' : ([12, 20, 11, 2], { (0, 0) : (12, 100), (0, 1) : (12, 40), (0, 2) : (12, 44), (0, 3) : (12, 16), (1, 0) : (20, 40), (1, 1) : (20, 96), (1, 2) : (20, 44), (1, 3) : (20, 24), (2, 0) : (11, 44), (2, 1) : (11, 44), (2, 2) : (11, 72), (2, 3) : (11, 12), (3, 0) : (2, 16), (3, 1) : (2, 24), (3, 2) : (2, 12), (3, 3) : (2, 2), }), 'square_triquad.mesh' : ([470, 1127, 658, 0], { (0, 0) : (470, 3054), (0, 1) : (470, 2254), (0, 2) : (470, 2174), (1, 0) : (1127, 2254), (1, 1) : (1127, 9174), (1, 2) : (1127, 2174), (2, 0) : (658, 2174), (2, 1) : (658, 2174), (2, 2) : (658, 6686), }), } class Test(TestCommon): @staticmethod def from_conf(conf, options): filename_meshes = [data_dir + '/meshes/elements/%s_2.mesh' % geom for geom in ['2_3', '2_4', '3_4', '3_8']] filename_meshes.append(data_dir + '/meshes/2d/special/square_triquad.mesh') test = Test(filename_meshes=filename_meshes, conf=conf, options=options) return test def test_cmesh_counts(self): from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem.extmods.cmesh import CMesh, get_cmem_usage gels = create_geometry_elements() ok = True for filename in self.filename_meshes: basename = os.path.basename(filename) enum, esizes = expected[basename] self.report('mesh: %s' % basename) mesh =
Mesh.from_file(filename)
sfepy.discrete.fem.Mesh.from_file
import os import numpy as nm from sfepy.base.testing import TestCommon from sfepy import data_dir # n_cell, n_face, n_edge, n_vertex # d1 -> d2 : num, n_incident expected = { '2_3_2.mesh' : ([4, 5, 2, 0], { (0, 0) : (4, 10), (0, 1) : (4, 10), (0, 2) : (4, 6), (1, 0) : (5, 10), (1, 1) : (5, 16), (1, 2) : (5, 6), (2, 0) : (2, 6), (2, 1) : (2, 6), (2, 2) : (2, 2), }), '2_4_2.mesh' : ([6, 7, 2, 0], { (0, 0) : (6, 22), (0, 1) : (6, 14), (0, 2) : (6, 8), (1, 0) : (7, 14), (1, 1) : (7, 20), (1, 2) : (7, 8), (2, 0) : (2, 8), (2, 1) : (2, 8), (2, 2) : (2, 2), }), '3_4_2.mesh' : ([5, 9, 7, 2], { (0, 0) : (5, 18), (0, 1) : (5, 18), (0, 2) : (5, 21), (0, 3) : (5, 8), (1, 0) : (9, 18), (1, 1) : (9, 48), (1, 2) : (9, 21), (1, 3) : (9, 12), (2, 0) : (7, 21), (2, 1) : (7, 21), (2, 2) : (7, 42), (2, 3) : (7, 8), (3, 0) : (2, 8), (3, 1) : (2, 12), (3, 2) : (2, 8), (3, 3) : (2, 2), }), '3_8_2.mesh' : ([12, 20, 11, 2], { (0, 0) : (12, 100), (0, 1) : (12, 40), (0, 2) : (12, 44), (0, 3) : (12, 16), (1, 0) : (20, 40), (1, 1) : (20, 96), (1, 2) : (20, 44), (1, 3) : (20, 24), (2, 0) : (11, 44), (2, 1) : (11, 44), (2, 2) : (11, 72), (2, 3) : (11, 12), (3, 0) : (2, 16), (3, 1) : (2, 24), (3, 2) : (2, 12), (3, 3) : (2, 2), }), 'square_triquad.mesh' : ([470, 1127, 658, 0], { (0, 0) : (470, 3054), (0, 1) : (470, 2254), (0, 2) : (470, 2174), (1, 0) : (1127, 2254), (1, 1) : (1127, 9174), (1, 2) : (1127, 2174), (2, 0) : (658, 2174), (2, 1) : (658, 2174), (2, 2) : (658, 6686), }), } class Test(TestCommon): @staticmethod def from_conf(conf, options): filename_meshes = [data_dir + '/meshes/elements/%s_2.mesh' % geom for geom in ['2_3', '2_4', '3_4', '3_8']] filename_meshes.append(data_dir + '/meshes/2d/special/square_triquad.mesh') test = Test(filename_meshes=filename_meshes, conf=conf, options=options) return test def test_cmesh_counts(self): from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem.extmods.cmesh import CMesh, get_cmem_usage gels = create_geometry_elements() ok = True for filename in self.filename_meshes: basename = os.path.basename(filename) enum, esizes = expected[basename] self.report('mesh: %s' % basename) mesh = Mesh.from_file(filename) cmesh =
CMesh.from_mesh(mesh)
sfepy.discrete.fem.extmods.cmesh.CMesh.from_mesh
import os import numpy as nm from sfepy.base.testing import TestCommon from sfepy import data_dir # n_cell, n_face, n_edge, n_vertex # d1 -> d2 : num, n_incident expected = { '2_3_2.mesh' : ([4, 5, 2, 0], { (0, 0) : (4, 10), (0, 1) : (4, 10), (0, 2) : (4, 6), (1, 0) : (5, 10), (1, 1) : (5, 16), (1, 2) : (5, 6), (2, 0) : (2, 6), (2, 1) : (2, 6), (2, 2) : (2, 2), }), '2_4_2.mesh' : ([6, 7, 2, 0], { (0, 0) : (6, 22), (0, 1) : (6, 14), (0, 2) : (6, 8), (1, 0) : (7, 14), (1, 1) : (7, 20), (1, 2) : (7, 8), (2, 0) : (2, 8), (2, 1) : (2, 8), (2, 2) : (2, 2), }), '3_4_2.mesh' : ([5, 9, 7, 2], { (0, 0) : (5, 18), (0, 1) : (5, 18), (0, 2) : (5, 21), (0, 3) : (5, 8), (1, 0) : (9, 18), (1, 1) : (9, 48), (1, 2) : (9, 21), (1, 3) : (9, 12), (2, 0) : (7, 21), (2, 1) : (7, 21), (2, 2) : (7, 42), (2, 3) : (7, 8), (3, 0) : (2, 8), (3, 1) : (2, 12), (3, 2) : (2, 8), (3, 3) : (2, 2), }), '3_8_2.mesh' : ([12, 20, 11, 2], { (0, 0) : (12, 100), (0, 1) : (12, 40), (0, 2) : (12, 44), (0, 3) : (12, 16), (1, 0) : (20, 40), (1, 1) : (20, 96), (1, 2) : (20, 44), (1, 3) : (20, 24), (2, 0) : (11, 44), (2, 1) : (11, 44), (2, 2) : (11, 72), (2, 3) : (11, 12), (3, 0) : (2, 16), (3, 1) : (2, 24), (3, 2) : (2, 12), (3, 3) : (2, 2), }), 'square_triquad.mesh' : ([470, 1127, 658, 0], { (0, 0) : (470, 3054), (0, 1) : (470, 2254), (0, 2) : (470, 2174), (1, 0) : (1127, 2254), (1, 1) : (1127, 9174), (1, 2) : (1127, 2174), (2, 0) : (658, 2174), (2, 1) : (658, 2174), (2, 2) : (658, 6686), }), } class Test(TestCommon): @staticmethod def from_conf(conf, options): filename_meshes = [data_dir + '/meshes/elements/%s_2.mesh' % geom for geom in ['2_3', '2_4', '3_4', '3_8']] filename_meshes.append(data_dir + '/meshes/2d/special/square_triquad.mesh') test = Test(filename_meshes=filename_meshes, conf=conf, options=options) return test def test_cmesh_counts(self): from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem.extmods.cmesh import CMesh, get_cmem_usage gels = create_geometry_elements() ok = True for filename in self.filename_meshes: basename = os.path.basename(filename) enum, esizes = expected[basename] self.report('mesh: %s' % basename) mesh = Mesh.from_file(filename) cmesh = CMesh.from_mesh(mesh) cmesh.set_local_entities(gels) cmesh.setup_entities() self.report('dim:', cmesh.dim) self.report('n_cell: %d, n_face: %d, n_edge: %d, n_vertex: %d' % tuple(cmesh.num)) _ok = (enum == cmesh.num).all() if not _ok: self.report('%s == %s failed!' % (enum, cmesh.num)) ok = ok and _ok dim = cmesh.dim for ir in range(dim + 1): for ic in range(dim + 1): cmesh.setup_connectivity(ir, ic) mem_usage1 =
get_cmem_usage()
sfepy.discrete.fem.extmods.cmesh.get_cmem_usage
import os import numpy as nm from sfepy.base.testing import TestCommon from sfepy import data_dir # n_cell, n_face, n_edge, n_vertex # d1 -> d2 : num, n_incident expected = { '2_3_2.mesh' : ([4, 5, 2, 0], { (0, 0) : (4, 10), (0, 1) : (4, 10), (0, 2) : (4, 6), (1, 0) : (5, 10), (1, 1) : (5, 16), (1, 2) : (5, 6), (2, 0) : (2, 6), (2, 1) : (2, 6), (2, 2) : (2, 2), }), '2_4_2.mesh' : ([6, 7, 2, 0], { (0, 0) : (6, 22), (0, 1) : (6, 14), (0, 2) : (6, 8), (1, 0) : (7, 14), (1, 1) : (7, 20), (1, 2) : (7, 8), (2, 0) : (2, 8), (2, 1) : (2, 8), (2, 2) : (2, 2), }), '3_4_2.mesh' : ([5, 9, 7, 2], { (0, 0) : (5, 18), (0, 1) : (5, 18), (0, 2) : (5, 21), (0, 3) : (5, 8), (1, 0) : (9, 18), (1, 1) : (9, 48), (1, 2) : (9, 21), (1, 3) : (9, 12), (2, 0) : (7, 21), (2, 1) : (7, 21), (2, 2) : (7, 42), (2, 3) : (7, 8), (3, 0) : (2, 8), (3, 1) : (2, 12), (3, 2) : (2, 8), (3, 3) : (2, 2), }), '3_8_2.mesh' : ([12, 20, 11, 2], { (0, 0) : (12, 100), (0, 1) : (12, 40), (0, 2) : (12, 44), (0, 3) : (12, 16), (1, 0) : (20, 40), (1, 1) : (20, 96), (1, 2) : (20, 44), (1, 3) : (20, 24), (2, 0) : (11, 44), (2, 1) : (11, 44), (2, 2) : (11, 72), (2, 3) : (11, 12), (3, 0) : (2, 16), (3, 1) : (2, 24), (3, 2) : (2, 12), (3, 3) : (2, 2), }), 'square_triquad.mesh' : ([470, 1127, 658, 0], { (0, 0) : (470, 3054), (0, 1) : (470, 2254), (0, 2) : (470, 2174), (1, 0) : (1127, 2254), (1, 1) : (1127, 9174), (1, 2) : (1127, 2174), (2, 0) : (658, 2174), (2, 1) : (658, 2174), (2, 2) : (658, 6686), }), } class Test(TestCommon): @staticmethod def from_conf(conf, options): filename_meshes = [data_dir + '/meshes/elements/%s_2.mesh' % geom for geom in ['2_3', '2_4', '3_4', '3_8']] filename_meshes.append(data_dir + '/meshes/2d/special/square_triquad.mesh') test = Test(filename_meshes=filename_meshes, conf=conf, options=options) return test def test_cmesh_counts(self): from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem.extmods.cmesh import CMesh, get_cmem_usage gels = create_geometry_elements() ok = True for filename in self.filename_meshes: basename = os.path.basename(filename) enum, esizes = expected[basename] self.report('mesh: %s' % basename) mesh = Mesh.from_file(filename) cmesh = CMesh.from_mesh(mesh) cmesh.set_local_entities(gels) cmesh.setup_entities() self.report('dim:', cmesh.dim) self.report('n_cell: %d, n_face: %d, n_edge: %d, n_vertex: %d' % tuple(cmesh.num)) _ok = (enum == cmesh.num).all() if not _ok: self.report('%s == %s failed!' % (enum, cmesh.num)) ok = ok and _ok dim = cmesh.dim for ir in range(dim + 1): for ic in range(dim + 1): cmesh.setup_connectivity(ir, ic) mem_usage1 = get_cmem_usage()[0] if (ir == dim) and (ic == 0): continue cmesh.free_connectivity(ir, ic) mem_usage2 =
get_cmem_usage()
sfepy.discrete.fem.extmods.cmesh.get_cmem_usage
import os import numpy as nm from sfepy.base.testing import TestCommon from sfepy import data_dir # n_cell, n_face, n_edge, n_vertex # d1 -> d2 : num, n_incident expected = { '2_3_2.mesh' : ([4, 5, 2, 0], { (0, 0) : (4, 10), (0, 1) : (4, 10), (0, 2) : (4, 6), (1, 0) : (5, 10), (1, 1) : (5, 16), (1, 2) : (5, 6), (2, 0) : (2, 6), (2, 1) : (2, 6), (2, 2) : (2, 2), }), '2_4_2.mesh' : ([6, 7, 2, 0], { (0, 0) : (6, 22), (0, 1) : (6, 14), (0, 2) : (6, 8), (1, 0) : (7, 14), (1, 1) : (7, 20), (1, 2) : (7, 8), (2, 0) : (2, 8), (2, 1) : (2, 8), (2, 2) : (2, 2), }), '3_4_2.mesh' : ([5, 9, 7, 2], { (0, 0) : (5, 18), (0, 1) : (5, 18), (0, 2) : (5, 21), (0, 3) : (5, 8), (1, 0) : (9, 18), (1, 1) : (9, 48), (1, 2) : (9, 21), (1, 3) : (9, 12), (2, 0) : (7, 21), (2, 1) : (7, 21), (2, 2) : (7, 42), (2, 3) : (7, 8), (3, 0) : (2, 8), (3, 1) : (2, 12), (3, 2) : (2, 8), (3, 3) : (2, 2), }), '3_8_2.mesh' : ([12, 20, 11, 2], { (0, 0) : (12, 100), (0, 1) : (12, 40), (0, 2) : (12, 44), (0, 3) : (12, 16), (1, 0) : (20, 40), (1, 1) : (20, 96), (1, 2) : (20, 44), (1, 3) : (20, 24), (2, 0) : (11, 44), (2, 1) : (11, 44), (2, 2) : (11, 72), (2, 3) : (11, 12), (3, 0) : (2, 16), (3, 1) : (2, 24), (3, 2) : (2, 12), (3, 3) : (2, 2), }), 'square_triquad.mesh' : ([470, 1127, 658, 0], { (0, 0) : (470, 3054), (0, 1) : (470, 2254), (0, 2) : (470, 2174), (1, 0) : (1127, 2254), (1, 1) : (1127, 9174), (1, 2) : (1127, 2174), (2, 0) : (658, 2174), (2, 1) : (658, 2174), (2, 2) : (658, 6686), }), } class Test(TestCommon): @staticmethod def from_conf(conf, options): filename_meshes = [data_dir + '/meshes/elements/%s_2.mesh' % geom for geom in ['2_3', '2_4', '3_4', '3_8']] filename_meshes.append(data_dir + '/meshes/2d/special/square_triquad.mesh') test = Test(filename_meshes=filename_meshes, conf=conf, options=options) return test def test_cmesh_counts(self): from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem.extmods.cmesh import CMesh, get_cmem_usage gels = create_geometry_elements() ok = True for filename in self.filename_meshes: basename = os.path.basename(filename) enum, esizes = expected[basename] self.report('mesh: %s' % basename) mesh = Mesh.from_file(filename) cmesh = CMesh.from_mesh(mesh) cmesh.set_local_entities(gels) cmesh.setup_entities() self.report('dim:', cmesh.dim) self.report('n_cell: %d, n_face: %d, n_edge: %d, n_vertex: %d' % tuple(cmesh.num)) _ok = (enum == cmesh.num).all() if not _ok: self.report('%s == %s failed!' % (enum, cmesh.num)) ok = ok and _ok dim = cmesh.dim for ir in range(dim + 1): for ic in range(dim + 1): cmesh.setup_connectivity(ir, ic) mem_usage1 = get_cmem_usage()[0] if (ir == dim) and (ic == 0): continue cmesh.free_connectivity(ir, ic) mem_usage2 = get_cmem_usage()[0] cmesh.setup_connectivity(ir, ic) mem_usage3 =
get_cmem_usage()
sfepy.discrete.fem.extmods.cmesh.get_cmem_usage
import numpy as nm from sfepy.base.base import assert_ from sfepy.linalg import dot_sequences from sfepy.terms.terms import Term, terms class ZeroTerm(Term): r""" A do-nothing term useful for introducing additional variables into the equations. :Definition: .. math:: 0 :Arguments: - virtual : :math:`q` or :math:`\ul{v}` - state : :math:`p` or :math:`\ul{u}` """ name = 'dw_zero' arg_types = ('virtual', 'state') arg_shapes = {'virtual' : ('N', None), 'state' : 'N'} @staticmethod def function(out): out.fill(0.0) return 0 def get_fargs(self, vvar, svar, mode=None, term_mode=None, diff_var=None, **kwargs): return () class IntegrateVolumeTerm(Term): r""" Evaluate (weighted) variable in a volume region. Depending on evaluation mode, integrate a variable over a volume region ('eval'), average it in elements ('el_avg') or interpolate it into volume quadrature points ('qp'). Supports 'eval', 'el_avg' and 'qp' evaluation modes. :Definition: .. math:: \int_\Omega y \mbox{ , } \int_\Omega \ul{y} \\ \int_\Omega c y \mbox{ , } \int_\Omega c \ul{y} .. math:: \mbox{vector for } K \from \Ical_h: \int_{T_K} y / \int_{T_K} 1 \mbox{ , } \int_{T_K} \ul{y} / \int_{T_K} 1 \\ \mbox{vector for } K \from \Ical_h: \int_{T_K} c y / \int_{T_K} 1 \mbox{ , } \int_{T_K} c \ul{y} / \int_{T_K} 1 .. math:: y|_{qp} \mbox{ , } \ul{y}|_{qp} \\ c y|_{qp} \mbox{ , } c \ul{y}|_{qp} :Arguments: - material : :math:`c` (optional) - parameter : :math:`y` or :math:`\ul{y}` """ name = 'ev_volume_integrate' arg_types = ('opt_material', 'parameter') arg_shapes = [{'opt_material' : '1, 1', 'parameter' : 'N'}, {'opt_material' : None}] @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, material, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(parameter) val_qp = self.get(parameter, 'val') if material is not None: val_qp *= material fmode = {'eval' : 0, 'el_avg' : 1, 'qp' : 2}.get(mode, 1) return val_qp, vg, fmode def get_eval_shape(self, material, 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, n_c, 1), parameter.dtype class IntegrateSurfaceTerm(Term): r""" Evaluate (weighted) variable in a surface region. Depending on evaluation mode, integrate a variable over a surface region ('eval'), average it in element faces ('el_avg') or interpolate it into surface quadrature points ('qp'). For vector variables, setting `term_mode` to `'flux'` leads to computing corresponding fluxes for the three modes instead. Supports 'eval', 'el_avg' and 'qp' evaluation modes. :Definition: .. math:: \int_\Gamma y \mbox{ , } \int_\Gamma \ul{y} \mbox{ , } \int_\Gamma \ul{y} \cdot \ul{n} \\ \int_\Gamma c y \mbox{ , } \int_\Gamma c \ul{y} \mbox{ , } \int_\Gamma c \ul{y} \cdot \ul{n} \mbox{ flux } .. math:: \mbox{vector for } K \from \Ical_h: \int_{T_K} y / \int_{T_K} 1 \mbox{ , } \int_{T_K} \ul{y} / \int_{T_K} 1 \mbox{ , } \int_{T_K} (\ul{y} \cdot \ul{n}) / \int_{T_K} 1 \\ \mbox{vector for } K \from \Ical_h: \int_{T_K} c y / \int_{T_K} 1 \mbox{ , } \int_{T_K} c \ul{y} / \int_{T_K} 1 \mbox{ , } \int_{T_K} (c \ul{y} \cdot \ul{n}) / \int_{T_K} 1 .. math:: y|_{qp} \mbox{ , } \ul{y}|_{qp} \mbox{ , } (\ul{y} \cdot \ul{n})|_{qp} \mbox{ flux } \\ c y|_{qp} \mbox{ , } c \ul{y}|_{qp} \mbox{ , } (c \ul{y} \cdot \ul{n})|_{qp} \mbox{ flux } :Arguments: - material : :math:`c` (optional) - parameter : :math:`y` or :math:`\ul{y}` """ name = 'ev_surface_integrate' arg_types = ('opt_material', 'parameter') arg_shapes = [{'opt_material' : '1, 1', 'parameter' : 'N'}, {'opt_material' : None}] integration = 'surface' @staticmethod def function(out, val_qp, sg, fmode): if fmode == 2: out[:] = val_qp status = 0 elif fmode == 5: normal = sg.normal out[:] = dot_sequences(val_qp, normal) status = 0 else: status = sg.integrate(out, val_qp, fmode) return status def get_fargs(self, material, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): sg, _ = self.get_mapping(parameter) val_qp = self.get(parameter, 'val') if material is not None: val_qp *= material fmode = {'eval' : 0, 'el_avg' : 1, 'qp' : 2}.get(mode, 1) if term_mode == 'flux': n_fa, n_qp, dim, n_fn, n_c = self.get_data_shape(parameter) if n_c == dim: fmode += 3 return val_qp, sg, fmode def get_eval_shape(self, material, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): n_fa, n_qp, dim, n_fn, n_c = self.get_data_shape(parameter) if mode != 'qp': n_qp = 1 if term_mode == 'flux': n_c = 1 return (n_fa, n_qp, n_c, 1), parameter.dtype class IntegrateVolumeOperatorTerm(Term): r""" Volume integral of a test function weighted by a scalar function :math:`c`. :Definition: .. math:: \int_\Omega q \mbox{ or } \int_\Omega c q :Arguments: - material : :math:`c` (optional) - virtual : :math:`q` """ name = 'dw_volume_integrate' arg_types = ('opt_material', 'virtual') arg_shapes = [{'opt_material' : '1, 1', 'virtual' : (1, None)}, {'opt_material' : None}] @staticmethod def function(out, material, bf, geo): bf_t = nm.tile(bf.transpose((0, 1, 3, 2)), (out.shape[0], 1, 1, 1)) bf_t = nm.ascontiguousarray(bf_t) if material is not None: status = geo.integrate(out, material * bf_t) else: status = geo.integrate(out, bf_t) return status def get_fargs(self, material, virtual, mode=None, term_mode=None, diff_var=None, **kwargs):
assert_(virtual.n_components == 1)
sfepy.base.base.assert_
import numpy as nm from sfepy.base.base import assert_ from sfepy.linalg import dot_sequences from sfepy.terms.terms import Term, terms class ZeroTerm(Term): r""" A do-nothing term useful for introducing additional variables into the equations. :Definition: .. math:: 0 :Arguments: - virtual : :math:`q` or :math:`\ul{v}` - state : :math:`p` or :math:`\ul{u}` """ name = 'dw_zero' arg_types = ('virtual', 'state') arg_shapes = {'virtual' : ('N', None), 'state' : 'N'} @staticmethod def function(out): out.fill(0.0) return 0 def get_fargs(self, vvar, svar, mode=None, term_mode=None, diff_var=None, **kwargs): return () class IntegrateVolumeTerm(Term): r""" Evaluate (weighted) variable in a volume region. Depending on evaluation mode, integrate a variable over a volume region ('eval'), average it in elements ('el_avg') or interpolate it into volume quadrature points ('qp'). Supports 'eval', 'el_avg' and 'qp' evaluation modes. :Definition: .. math:: \int_\Omega y \mbox{ , } \int_\Omega \ul{y} \\ \int_\Omega c y \mbox{ , } \int_\Omega c \ul{y} .. math:: \mbox{vector for } K \from \Ical_h: \int_{T_K} y / \int_{T_K} 1 \mbox{ , } \int_{T_K} \ul{y} / \int_{T_K} 1 \\ \mbox{vector for } K \from \Ical_h: \int_{T_K} c y / \int_{T_K} 1 \mbox{ , } \int_{T_K} c \ul{y} / \int_{T_K} 1 .. math:: y|_{qp} \mbox{ , } \ul{y}|_{qp} \\ c y|_{qp} \mbox{ , } c \ul{y}|_{qp} :Arguments: - material : :math:`c` (optional) - parameter : :math:`y` or :math:`\ul{y}` """ name = 'ev_volume_integrate' arg_types = ('opt_material', 'parameter') arg_shapes = [{'opt_material' : '1, 1', 'parameter' : 'N'}, {'opt_material' : None}] @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, material, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(parameter) val_qp = self.get(parameter, 'val') if material is not None: val_qp *= material fmode = {'eval' : 0, 'el_avg' : 1, 'qp' : 2}.get(mode, 1) return val_qp, vg, fmode def get_eval_shape(self, material, 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, n_c, 1), parameter.dtype class IntegrateSurfaceTerm(Term): r""" Evaluate (weighted) variable in a surface region. Depending on evaluation mode, integrate a variable over a surface region ('eval'), average it in element faces ('el_avg') or interpolate it into surface quadrature points ('qp'). For vector variables, setting `term_mode` to `'flux'` leads to computing corresponding fluxes for the three modes instead. Supports 'eval', 'el_avg' and 'qp' evaluation modes. :Definition: .. math:: \int_\Gamma y \mbox{ , } \int_\Gamma \ul{y} \mbox{ , } \int_\Gamma \ul{y} \cdot \ul{n} \\ \int_\Gamma c y \mbox{ , } \int_\Gamma c \ul{y} \mbox{ , } \int_\Gamma c \ul{y} \cdot \ul{n} \mbox{ flux } .. math:: \mbox{vector for } K \from \Ical_h: \int_{T_K} y / \int_{T_K} 1 \mbox{ , } \int_{T_K} \ul{y} / \int_{T_K} 1 \mbox{ , } \int_{T_K} (\ul{y} \cdot \ul{n}) / \int_{T_K} 1 \\ \mbox{vector for } K \from \Ical_h: \int_{T_K} c y / \int_{T_K} 1 \mbox{ , } \int_{T_K} c \ul{y} / \int_{T_K} 1 \mbox{ , } \int_{T_K} (c \ul{y} \cdot \ul{n}) / \int_{T_K} 1 .. math:: y|_{qp} \mbox{ , } \ul{y}|_{qp} \mbox{ , } (\ul{y} \cdot \ul{n})|_{qp} \mbox{ flux } \\ c y|_{qp} \mbox{ , } c \ul{y}|_{qp} \mbox{ , } (c \ul{y} \cdot \ul{n})|_{qp} \mbox{ flux } :Arguments: - material : :math:`c` (optional) - parameter : :math:`y` or :math:`\ul{y}` """ name = 'ev_surface_integrate' arg_types = ('opt_material', 'parameter') arg_shapes = [{'opt_material' : '1, 1', 'parameter' : 'N'}, {'opt_material' : None}] integration = 'surface' @staticmethod def function(out, val_qp, sg, fmode): if fmode == 2: out[:] = val_qp status = 0 elif fmode == 5: normal = sg.normal out[:] =
dot_sequences(val_qp, normal)
sfepy.linalg.dot_sequences
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh =
Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh')
sfepy.discrete.fem.Mesh.from_file
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain =
FEDomain('domain', mesh)
sfepy.discrete.fem.FEDomain
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu =
Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2)
sfepy.discrete.fem.Field.from_args
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u =
FieldVariable('u', 'unknown', fu)
sfepy.discrete.FieldVariable
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp =
Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2)
sfepy.discrete.fem.Field.from_args
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p =
FieldVariable('p', 'unknown', fp)
sfepy.discrete.FieldVariable
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line =
Function('match_y_line', match_y_line)
sfepy.discrete.Function
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions =
Functions([match_y_line])
sfepy.discrete.Functions
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions = Functions([match_y_line]) epbcs =
Conditions([pbc])
sfepy.discrete.conditions.Conditions
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions = Functions([match_y_line]) epbcs = Conditions([pbc]) variables.equation_mapping(ebcs=None, epbcs=epbcs, ts=None, functions=functions) vec = init_vec(variables) variables.apply_ebc(vec) var = variables['u'] var_bcs = epbcs.group_by_variables()['u'] bc = var_bcs['pbc'] bc.canonize_dof_names(var.dofs) nods0 = var.field.get_dofs_in_region(bc.regions[0]) nods1 = var.field.get_dofs_in_region(bc.regions[1]) coors0 = var.field.get_coor(nods0) coors1 = var.field.get_coor(nods1) i0, i1 =
match_y_line(coors0, coors1)
sfepy.discrete.fem.periodic.match_y_line
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions = Functions([match_y_line]) epbcs = Conditions([pbc]) variables.equation_mapping(ebcs=None, epbcs=epbcs, ts=None, functions=functions) vec = init_vec(variables) variables.apply_ebc(vec) var = variables['u'] var_bcs = epbcs.group_by_variables()['u'] bc = var_bcs['pbc'] bc.canonize_dof_names(var.dofs) nods0 = var.field.get_dofs_in_region(bc.regions[0]) nods1 = var.field.get_dofs_in_region(bc.regions[1]) coors0 = var.field.get_coor(nods0) coors1 = var.field.get_coor(nods1) i0, i1 = match_y_line(coors0, coors1) eq0 =
expand_nodes_to_equations(nods0[i0], bc.dofs[0], var.dofs)
sfepy.discrete.common.dof_info.expand_nodes_to_equations
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions = Functions([match_y_line]) epbcs = Conditions([pbc]) variables.equation_mapping(ebcs=None, epbcs=epbcs, ts=None, functions=functions) vec = init_vec(variables) variables.apply_ebc(vec) var = variables['u'] var_bcs = epbcs.group_by_variables()['u'] bc = var_bcs['pbc'] bc.canonize_dof_names(var.dofs) nods0 = var.field.get_dofs_in_region(bc.regions[0]) nods1 = var.field.get_dofs_in_region(bc.regions[1]) coors0 = var.field.get_coor(nods0) coors1 = var.field.get_coor(nods1) i0, i1 = match_y_line(coors0, coors1) eq0 = expand_nodes_to_equations(nods0[i0], bc.dofs[0], var.dofs) eq1 =
expand_nodes_to_equations(nods1[i1], bc.dofs[1], var.dofs)
sfepy.discrete.common.dof_info.expand_nodes_to_equations
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions = Functions([match_y_line]) epbcs = Conditions([pbc]) variables.equation_mapping(ebcs=None, epbcs=epbcs, ts=None, functions=functions) vec = init_vec(variables) variables.apply_ebc(vec) var = variables['u'] var_bcs = epbcs.group_by_variables()['u'] bc = var_bcs['pbc'] bc.canonize_dof_names(var.dofs) nods0 = var.field.get_dofs_in_region(bc.regions[0]) nods1 = var.field.get_dofs_in_region(bc.regions[1]) coors0 = var.field.get_coor(nods0) coors1 = var.field.get_coor(nods1) i0, i1 = match_y_line(coors0, coors1) eq0 = expand_nodes_to_equations(nods0[i0], bc.dofs[0], var.dofs) eq1 = expand_nodes_to_equations(nods1[i1], bc.dofs[1], var.dofs) ok = True _ok = len(nm.setdiff1d(eq0, var.eq_map.master)) == 0 if not _ok: self.report('master equations mismatch! (set(%s) == set(%s))' % (eq0, var.eq_map.master)) ok = ok and _ok _ok = len(nm.setdiff1d(eq1, var.eq_map.slave)) == 0 if not _ok: self.report('slave equations mismatch! (set(%s) == set(%s))' % (eq1, var.eq_map.slave)) ok = ok and _ok off = variables.di.indx['u'].start _ok = nm.allclose(vec[off + eq0], vec[off + eq1], atol=1e-14, rtol=0.0) if not _ok: self.report('periodicity test failed! (%s == %s)' % (vec[off + eq0], vec[off + eq0])) ok = ok and _ok return ok def test_save_ebc(self): from sfepy.discrete import (FieldVariable, Integral, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.terms import Term name = op.join(self.options.out_dir, op.splitext(op.basename(__file__))[0]) integral =
Integral('i', order=1)
sfepy.discrete.Integral
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions = Functions([match_y_line]) epbcs = Conditions([pbc]) variables.equation_mapping(ebcs=None, epbcs=epbcs, ts=None, functions=functions) vec = init_vec(variables) variables.apply_ebc(vec) var = variables['u'] var_bcs = epbcs.group_by_variables()['u'] bc = var_bcs['pbc'] bc.canonize_dof_names(var.dofs) nods0 = var.field.get_dofs_in_region(bc.regions[0]) nods1 = var.field.get_dofs_in_region(bc.regions[1]) coors0 = var.field.get_coor(nods0) coors1 = var.field.get_coor(nods1) i0, i1 = match_y_line(coors0, coors1) eq0 = expand_nodes_to_equations(nods0[i0], bc.dofs[0], var.dofs) eq1 = expand_nodes_to_equations(nods1[i1], bc.dofs[1], var.dofs) ok = True _ok = len(nm.setdiff1d(eq0, var.eq_map.master)) == 0 if not _ok: self.report('master equations mismatch! (set(%s) == set(%s))' % (eq0, var.eq_map.master)) ok = ok and _ok _ok = len(nm.setdiff1d(eq1, var.eq_map.slave)) == 0 if not _ok: self.report('slave equations mismatch! (set(%s) == set(%s))' % (eq1, var.eq_map.slave)) ok = ok and _ok off = variables.di.indx['u'].start _ok = nm.allclose(vec[off + eq0], vec[off + eq1], atol=1e-14, rtol=0.0) if not _ok: self.report('periodicity test failed! (%s == %s)' % (vec[off + eq0], vec[off + eq0])) ok = ok and _ok return ok def test_save_ebc(self): from sfepy.discrete import (FieldVariable, Integral, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.terms import Term name = op.join(self.options.out_dir, op.splitext(op.basename(__file__))[0]) integral = Integral('i', order=1) u = self.variables['u'] v =
FieldVariable('v', 'test', u.field, primary_var_name='u')
sfepy.discrete.FieldVariable
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions = Functions([match_y_line]) epbcs = Conditions([pbc]) variables.equation_mapping(ebcs=None, epbcs=epbcs, ts=None, functions=functions) vec = init_vec(variables) variables.apply_ebc(vec) var = variables['u'] var_bcs = epbcs.group_by_variables()['u'] bc = var_bcs['pbc'] bc.canonize_dof_names(var.dofs) nods0 = var.field.get_dofs_in_region(bc.regions[0]) nods1 = var.field.get_dofs_in_region(bc.regions[1]) coors0 = var.field.get_coor(nods0) coors1 = var.field.get_coor(nods1) i0, i1 = match_y_line(coors0, coors1) eq0 = expand_nodes_to_equations(nods0[i0], bc.dofs[0], var.dofs) eq1 = expand_nodes_to_equations(nods1[i1], bc.dofs[1], var.dofs) ok = True _ok = len(nm.setdiff1d(eq0, var.eq_map.master)) == 0 if not _ok: self.report('master equations mismatch! (set(%s) == set(%s))' % (eq0, var.eq_map.master)) ok = ok and _ok _ok = len(nm.setdiff1d(eq1, var.eq_map.slave)) == 0 if not _ok: self.report('slave equations mismatch! (set(%s) == set(%s))' % (eq1, var.eq_map.slave)) ok = ok and _ok off = variables.di.indx['u'].start _ok = nm.allclose(vec[off + eq0], vec[off + eq1], atol=1e-14, rtol=0.0) if not _ok: self.report('periodicity test failed! (%s == %s)' % (vec[off + eq0], vec[off + eq0])) ok = ok and _ok return ok def test_save_ebc(self): from sfepy.discrete import (FieldVariable, Integral, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.terms import Term name = op.join(self.options.out_dir, op.splitext(op.basename(__file__))[0]) integral = Integral('i', order=1) u = self.variables['u'] v = FieldVariable('v', 'test', u.field, primary_var_name='u') p = self.variables['p'] q =
FieldVariable('q', 'test', p.field, primary_var_name='p')
sfepy.discrete.FieldVariable
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions = Functions([match_y_line]) epbcs = Conditions([pbc]) variables.equation_mapping(ebcs=None, epbcs=epbcs, ts=None, functions=functions) vec = init_vec(variables) variables.apply_ebc(vec) var = variables['u'] var_bcs = epbcs.group_by_variables()['u'] bc = var_bcs['pbc'] bc.canonize_dof_names(var.dofs) nods0 = var.field.get_dofs_in_region(bc.regions[0]) nods1 = var.field.get_dofs_in_region(bc.regions[1]) coors0 = var.field.get_coor(nods0) coors1 = var.field.get_coor(nods1) i0, i1 = match_y_line(coors0, coors1) eq0 = expand_nodes_to_equations(nods0[i0], bc.dofs[0], var.dofs) eq1 = expand_nodes_to_equations(nods1[i1], bc.dofs[1], var.dofs) ok = True _ok = len(nm.setdiff1d(eq0, var.eq_map.master)) == 0 if not _ok: self.report('master equations mismatch! (set(%s) == set(%s))' % (eq0, var.eq_map.master)) ok = ok and _ok _ok = len(nm.setdiff1d(eq1, var.eq_map.slave)) == 0 if not _ok: self.report('slave equations mismatch! (set(%s) == set(%s))' % (eq1, var.eq_map.slave)) ok = ok and _ok off = variables.di.indx['u'].start _ok = nm.allclose(vec[off + eq0], vec[off + eq1], atol=1e-14, rtol=0.0) if not _ok: self.report('periodicity test failed! (%s == %s)' % (vec[off + eq0], vec[off + eq0])) ok = ok and _ok return ok def test_save_ebc(self): from sfepy.discrete import (FieldVariable, Integral, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.terms import Term name = op.join(self.options.out_dir, op.splitext(op.basename(__file__))[0]) integral = Integral('i', order=1) u = self.variables['u'] v = FieldVariable('v', 'test', u.field, primary_var_name='u') p = self.variables['p'] q = FieldVariable('q', 'test', p.field, primary_var_name='p') regions = self.problem.domain.regions omega = regions['Omega'] # Problem.save_ebc() requires to have equations defined. t1 = Term.new('dw_lin_elastic(v, u)', integral, omega, v=v, u=u) t2 =
Term.new('dw_laplace(q, p)', integral, omega, q=q, p=p)
sfepy.terms.Term.new
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions = Functions([match_y_line]) epbcs = Conditions([pbc]) variables.equation_mapping(ebcs=None, epbcs=epbcs, ts=None, functions=functions) vec = init_vec(variables) variables.apply_ebc(vec) var = variables['u'] var_bcs = epbcs.group_by_variables()['u'] bc = var_bcs['pbc'] bc.canonize_dof_names(var.dofs) nods0 = var.field.get_dofs_in_region(bc.regions[0]) nods1 = var.field.get_dofs_in_region(bc.regions[1]) coors0 = var.field.get_coor(nods0) coors1 = var.field.get_coor(nods1) i0, i1 = match_y_line(coors0, coors1) eq0 = expand_nodes_to_equations(nods0[i0], bc.dofs[0], var.dofs) eq1 = expand_nodes_to_equations(nods1[i1], bc.dofs[1], var.dofs) ok = True _ok = len(nm.setdiff1d(eq0, var.eq_map.master)) == 0 if not _ok: self.report('master equations mismatch! (set(%s) == set(%s))' % (eq0, var.eq_map.master)) ok = ok and _ok _ok = len(nm.setdiff1d(eq1, var.eq_map.slave)) == 0 if not _ok: self.report('slave equations mismatch! (set(%s) == set(%s))' % (eq1, var.eq_map.slave)) ok = ok and _ok off = variables.di.indx['u'].start _ok = nm.allclose(vec[off + eq0], vec[off + eq1], atol=1e-14, rtol=0.0) if not _ok: self.report('periodicity test failed! (%s == %s)' % (vec[off + eq0], vec[off + eq0])) ok = ok and _ok return ok def test_save_ebc(self): from sfepy.discrete import (FieldVariable, Integral, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.terms import Term name = op.join(self.options.out_dir, op.splitext(op.basename(__file__))[0]) integral = Integral('i', order=1) u = self.variables['u'] v = FieldVariable('v', 'test', u.field, primary_var_name='u') p = self.variables['p'] q = FieldVariable('q', 'test', p.field, primary_var_name='p') regions = self.problem.domain.regions omega = regions['Omega'] # Problem.save_ebc() requires to have equations defined. t1 = Term.new('dw_lin_elastic(v, u)', integral, omega, v=v, u=u) t2 = Term.new('dw_laplace(q, p)', integral, omega, q=q, p=p) eq =
Equation('aux', t1 + t2)
sfepy.discrete.Equation
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions = Functions([match_y_line]) epbcs = Conditions([pbc]) variables.equation_mapping(ebcs=None, epbcs=epbcs, ts=None, functions=functions) vec = init_vec(variables) variables.apply_ebc(vec) var = variables['u'] var_bcs = epbcs.group_by_variables()['u'] bc = var_bcs['pbc'] bc.canonize_dof_names(var.dofs) nods0 = var.field.get_dofs_in_region(bc.regions[0]) nods1 = var.field.get_dofs_in_region(bc.regions[1]) coors0 = var.field.get_coor(nods0) coors1 = var.field.get_coor(nods1) i0, i1 = match_y_line(coors0, coors1) eq0 = expand_nodes_to_equations(nods0[i0], bc.dofs[0], var.dofs) eq1 = expand_nodes_to_equations(nods1[i1], bc.dofs[1], var.dofs) ok = True _ok = len(nm.setdiff1d(eq0, var.eq_map.master)) == 0 if not _ok: self.report('master equations mismatch! (set(%s) == set(%s))' % (eq0, var.eq_map.master)) ok = ok and _ok _ok = len(nm.setdiff1d(eq1, var.eq_map.slave)) == 0 if not _ok: self.report('slave equations mismatch! (set(%s) == set(%s))' % (eq1, var.eq_map.slave)) ok = ok and _ok off = variables.di.indx['u'].start _ok = nm.allclose(vec[off + eq0], vec[off + eq1], atol=1e-14, rtol=0.0) if not _ok: self.report('periodicity test failed! (%s == %s)' % (vec[off + eq0], vec[off + eq0])) ok = ok and _ok return ok def test_save_ebc(self): from sfepy.discrete import (FieldVariable, Integral, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.terms import Term name = op.join(self.options.out_dir, op.splitext(op.basename(__file__))[0]) integral = Integral('i', order=1) u = self.variables['u'] v = FieldVariable('v', 'test', u.field, primary_var_name='u') p = self.variables['p'] q = FieldVariable('q', 'test', p.field, primary_var_name='p') regions = self.problem.domain.regions omega = regions['Omega'] # Problem.save_ebc() requires to have equations defined. t1 = Term.new('dw_lin_elastic(v, u)', integral, omega, v=v, u=u) t2 = Term.new('dw_laplace(q, p)', integral, omega, q=q, p=p) eq = Equation('aux', t1 + t2) eqs =
Equations([eq])
sfepy.discrete.Equations
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions = Functions([match_y_line]) epbcs = Conditions([pbc]) variables.equation_mapping(ebcs=None, epbcs=epbcs, ts=None, functions=functions) vec = init_vec(variables) variables.apply_ebc(vec) var = variables['u'] var_bcs = epbcs.group_by_variables()['u'] bc = var_bcs['pbc'] bc.canonize_dof_names(var.dofs) nods0 = var.field.get_dofs_in_region(bc.regions[0]) nods1 = var.field.get_dofs_in_region(bc.regions[1]) coors0 = var.field.get_coor(nods0) coors1 = var.field.get_coor(nods1) i0, i1 = match_y_line(coors0, coors1) eq0 = expand_nodes_to_equations(nods0[i0], bc.dofs[0], var.dofs) eq1 = expand_nodes_to_equations(nods1[i1], bc.dofs[1], var.dofs) ok = True _ok = len(nm.setdiff1d(eq0, var.eq_map.master)) == 0 if not _ok: self.report('master equations mismatch! (set(%s) == set(%s))' % (eq0, var.eq_map.master)) ok = ok and _ok _ok = len(nm.setdiff1d(eq1, var.eq_map.slave)) == 0 if not _ok: self.report('slave equations mismatch! (set(%s) == set(%s))' % (eq1, var.eq_map.slave)) ok = ok and _ok off = variables.di.indx['u'].start _ok = nm.allclose(vec[off + eq0], vec[off + eq1], atol=1e-14, rtol=0.0) if not _ok: self.report('periodicity test failed! (%s == %s)' % (vec[off + eq0], vec[off + eq0])) ok = ok and _ok return ok def test_save_ebc(self): from sfepy.discrete import (FieldVariable, Integral, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.terms import Term name = op.join(self.options.out_dir, op.splitext(op.basename(__file__))[0]) integral = Integral('i', order=1) u = self.variables['u'] v = FieldVariable('v', 'test', u.field, primary_var_name='u') p = self.variables['p'] q = FieldVariable('q', 'test', p.field, primary_var_name='p') regions = self.problem.domain.regions omega = regions['Omega'] # Problem.save_ebc() requires to have equations defined. t1 = Term.new('dw_lin_elastic(v, u)', integral, omega, v=v, u=u) t2 = Term.new('dw_laplace(q, p)', integral, omega, q=q, p=p) eq = Equation('aux', t1 + t2) eqs = Equations([eq]) pb =
Problem('test', equations=eqs, auto_solvers=False)
sfepy.discrete.Problem
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs) off = variables.di.indx[var_name].start n_nod = len(nods) for cdof, dof_name in enumerate(cond.dofs[0]): idof = var.dofs.index(dof_name) eqs = eq[n_nod * cdof : n_nod * (cdof + 1)] _ok = nm.allclose(vec[off + eqs], idof, atol=1e-14, rtol=0.0) if not _ok: self.report(' %s: failed! (all of %s == %f)' % (dof_name, vec[off + eqs], idof)) ok = ok and _ok return ok class Test(TestCommon): @staticmethod def from_conf(conf, options): from sfepy.discrete import FieldVariable, Variables, Problem from sfepy.discrete.fem import Mesh, FEDomain, Field mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') domain.create_region('Left', 'vertices in (x < -0.499)', 'facet') domain.create_region('LeftStrip', 'vertices in (x < -0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet') domain.create_region('Right', 'vertices in (x > 0.499)', 'facet') domain.create_region('RightStrip', 'vertices in (x > 0.499)' ' & (y > -0.199) & (y < 0.199)', 'facet') domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet') fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', fu) fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2) p = FieldVariable('p', 'unknown', fp) pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False, auto_solvers=False) test = Test(problem=pb, variables=Variables([u, p]), conf=conf, options=options) return test def test_ics(self): from sfepy.discrete.conditions import Conditions, InitialCondition variables = self.variables omega = self.problem.domain.regions['Omega'] all_ics = [] all_ics.append(InitialCondition('ic0', omega, {'p.all' : 0.0})) all_ics.append(InitialCondition('ic1', omega, {'u.1' : 1.0})) all_ics.append(InitialCondition('ic2', omega, {'u.all' : nm.array([0.0, 1.0])})) all_ics.append(InitialCondition('ic3', omega, {'p.0' : 0.0, 'u.0' : 0.0, 'u.1' : 1.0})) ok = True for ii, ics in enumerate(all_ics): if not isinstance(ics, list): ics = [ics] ics = Conditions(ics) variables.setup_initial_conditions(ics, functions=None) vec = init_vec(variables) variables.apply_ic(vec) ok = check_vec(self, vec, ii, ok, ics, variables) return ok def test_ebcs(self): from sfepy.discrete.conditions import Conditions, EssentialBC variables = self.variables regions = self.problem.domain.regions all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) all_ebcs.append([EssentialBC('fix_p3', regions['Right'], {'p.0' : 0.0}), EssentialBC('fix_u3', regions['Left'], {'u.0' : 0.0, 'u.1' : 1.0})]) ok = True for ii, bcs in enumerate(all_ebcs): if not isinstance(bcs, list): bcs = [bcs] ebcs = Conditions(bcs) variables.equation_mapping(ebcs=ebcs, epbcs=None, ts=None, functions=None) vec = init_vec(variables) variables.apply_ebc(vec) ok = check_vec(self, vec, ii, ok, ebcs, variables) return ok def test_epbcs(self): from sfepy.discrete import Function, Functions from sfepy.discrete.conditions import Conditions, PeriodicBC from sfepy.discrete.common.dof_info import expand_nodes_to_equations from sfepy.discrete.fem.periodic import match_y_line variables = self.variables regions = self.problem.domain.regions match_y_line = Function('match_y_line', match_y_line) pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']], {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line') functions = Functions([match_y_line]) epbcs = Conditions([pbc]) variables.equation_mapping(ebcs=None, epbcs=epbcs, ts=None, functions=functions) vec = init_vec(variables) variables.apply_ebc(vec) var = variables['u'] var_bcs = epbcs.group_by_variables()['u'] bc = var_bcs['pbc'] bc.canonize_dof_names(var.dofs) nods0 = var.field.get_dofs_in_region(bc.regions[0]) nods1 = var.field.get_dofs_in_region(bc.regions[1]) coors0 = var.field.get_coor(nods0) coors1 = var.field.get_coor(nods1) i0, i1 = match_y_line(coors0, coors1) eq0 = expand_nodes_to_equations(nods0[i0], bc.dofs[0], var.dofs) eq1 = expand_nodes_to_equations(nods1[i1], bc.dofs[1], var.dofs) ok = True _ok = len(nm.setdiff1d(eq0, var.eq_map.master)) == 0 if not _ok: self.report('master equations mismatch! (set(%s) == set(%s))' % (eq0, var.eq_map.master)) ok = ok and _ok _ok = len(nm.setdiff1d(eq1, var.eq_map.slave)) == 0 if not _ok: self.report('slave equations mismatch! (set(%s) == set(%s))' % (eq1, var.eq_map.slave)) ok = ok and _ok off = variables.di.indx['u'].start _ok = nm.allclose(vec[off + eq0], vec[off + eq1], atol=1e-14, rtol=0.0) if not _ok: self.report('periodicity test failed! (%s == %s)' % (vec[off + eq0], vec[off + eq0])) ok = ok and _ok return ok def test_save_ebc(self): from sfepy.discrete import (FieldVariable, Integral, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.terms import Term name = op.join(self.options.out_dir, op.splitext(op.basename(__file__))[0]) integral = Integral('i', order=1) u = self.variables['u'] v = FieldVariable('v', 'test', u.field, primary_var_name='u') p = self.variables['p'] q = FieldVariable('q', 'test', p.field, primary_var_name='p') regions = self.problem.domain.regions omega = regions['Omega'] # Problem.save_ebc() requires to have equations defined. t1 = Term.new('dw_lin_elastic(v, u)', integral, omega, v=v, u=u) t2 = Term.new('dw_laplace(q, p)', integral, omega, q=q, p=p) eq = Equation('aux', t1 + t2) eqs = Equations([eq]) pb = Problem('test', equations=eqs, auto_solvers=False) all_ebcs = [] all_ebcs.append(EssentialBC('fix_u1', regions['RightFix'], {'u.all' : nm.array([0.0, 1.0])})) all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'], {'u.0' : 0.0, 'u.1' : 1.0})) all_ebcs.append(EssentialBC('fix_p1', regions['LeftFix'], {'p.all' : 0.0})) all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'], {'p.0' : 0.0})) ebcs =
Conditions(all_ebcs)
sfepy.discrete.conditions.Conditions
from __future__ import absolute_import import os.path as op import numpy as nm from sfepy import data_dir from sfepy.base.testing import TestCommon import six def init_vec(variables): return nm.random.rand(variables.di.ptr[-1]) def check_vec(self, vec, ii, ok, conds, variables): from sfepy.discrete.common.dof_info import expand_nodes_to_equations for var_name, var_conds in six.iteritems(conds.group_by_variables()): var = variables[var_name] for cond in var_conds: cond.canonize_dof_names(var.dofs) self.report('%d: %s %s: %s %s' % (ii, var.name, cond.name, cond.region.name, cond.dofs[0])) nods = var.field.get_dofs_in_region(cond.region) eq =
expand_nodes_to_equations(nods, cond.dofs[0], var.dofs)
sfepy.discrete.common.dof_info.expand_nodes_to_equations