prompt
stringlengths
174
59.5k
completion
stringlengths
7
228
api
stringlengths
12
64
#!/usr/bin/env python r""" This example shows the use of the `dw_tl_he_genyeoh` hyperelastic term, whose contribution to the deformation energy density per unit reference volume is given by .. math:: W = K \, \left( \overline I_1 - 3 \right)^{p} where :math:`\overline I_1` is the first main invariant of the deviatoric part of the right Cauchy-Green deformation tensor :math:`\ull{C}` and `K` and `p` are its parameters. This term may be used to implement the generalized Yeoh hyperelastic material model [1] by adding three such terms: .. math:: W = K_1 \, \left( \overline I_1 - 3 \right)^{m} +K_2 \, \left( \overline I_1 - 3 \right)^{p} +K_3 \, \left( \overline I_1 - 3 \right)^{q} where the coefficients :math:`K_1, K_2, K_3` and exponents :math:`m, p, q` are material parameters. Only a single term is used in this example for the sake of simplicity. Components of the second Piola-Kirchhoff stress are in the case of an incompressible material .. math:: S_{ij} = 2 \, \pdiff{W}{C_{ij}} - p \, F^{-1}_{ik} \, F^{-T}_{kj} \;, where :math:`p` is the hydrostatic pressure. The large deformation is described using the total Lagrangian formulation in this example. The incompressibility is treated by mixed displacement-pressure formulation. The weak formulation is: Find the displacement field :math:`\ul{u}` and pressure field :math:`p` such that: .. math:: \intl{\Omega\suz}{} \ull{S}\eff(\ul{u}, p) : \ull{E}(\ul{v}) \difd{V} = 0 \;, \quad \forall \ul{v} \;, \intl{\Omega\suz}{} q\, (J(\ul{u})-1) \difd{V} = 0 \;, \quad \forall q \;. The following formula holds for the axial true (Cauchy) stress in the case of uniaxial stress: .. math:: \sigma(\lambda) = \frac{2}{3} \, m \, K_1 \, \left( \lambda^2 + \frac{2}{\lambda} - 3 \right)^{m-1} \, \left( \lambda - \frac{1}{\lambda^2} \right) \;, where :math:`\lambda = l/l_0` is the prescribed stretch (:math:`l_0` and :math:`l` being the original and deformed specimen length respectively). The boundary conditions are set so that a state of uniaxial stress is achieved, i.e. appropriate components of displacement are fixed on the "Left", "Bottom", and "Near" faces and a monotonously increasing displacement is prescribed on the "Right" face. This prescribed displacement is then used to calculate :math:`\lambda` and to convert the second Piola-Kirchhoff stress to the true (Cauchy) stress. Note on material parameters --------------------------- The three-term generalized Yeoh model is meant to be used for modelling of filled rubbers. The following choice of parameters is suggested [1] based on experimental data and stability considerations: :math:`K_1 > 0`, :math:`K_2 < 0`, :math:`K_3 > 0`, :math:`0.7 < m < 1`, :math:`m < p < q`. Usage Examples -------------- Default options:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py To show a comparison of stress against the analytic formula:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -p Using different mesh fineness:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --shape "5, 5, 5" Different dimensions of the computational domain:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --dims "2, 1, 3" Different length of time interval and/or number of time steps:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ -t 0,15,21 Use higher approximation order (the ``-t`` option to decrease the time step is required for convergence here):: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py \ --order 2 -t 0,2,21 Change material parameters:: $ python examples/large_deformation/gen_yeoh_tl_up_interactive.py -m 2,1 View the results using ``resview.py`` ------------------------------------- Show pressure on deformed mesh (use PgDn/PgUp to jump forward/back):: $ python resview.py --fields=p:f1:wu:p1 domain.??.vtk Show the axial component of stress (second Piola-Kirchhoff):: $ python resview.py --fields=stress:c0 domain.??.vtk [1] <NAME>, <NAME>, <NAME>, <NAME>. Busfield. Aconstitutive Model For Both Lowand High Strain Nonlinearities In Highly Filled Elastomers And Implementation With User-Defined Material Subroutines In Abaqus. Rubber Chemistry And Technology, Vol. 92, No. 4, Pp. 653-686 (2019) """ from __future__ import print_function, absolute_import import argparse import sys SFEPY_DIR = '.' sys.path.append(SFEPY_DIR) import matplotlib.pyplot as plt import numpy as np from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.discrete.fem import FEDomain, Field from sfepy.homogenization.utils import define_box_regions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.solvers.ts_solvers import SimpleTimeSteppingSolver from sfepy.terms import Term DIMENSION = 3 def get_displacement(ts, coors, bc=None, problem=None): """ Define the time-dependent displacement. """ out = 1. * ts.time * coors[:, 0] return out def _get_analytic_stress(stretches, coef, exp): out = np.array([ 2 * coef * exp * (stretch**2 + 2 / stretch - 3)**(exp - 1) * (stretch - stretch**-2) if (stretch**2 + 2 / stretch > 3) else 0. for stretch in stretches]) return out def plot_graphs( material_parameters, global_stress, global_displacement, undeformed_length): """ Plot a comparison of the nominal stress computed by the FEM and using the analytic formula. Parameters ---------- material_parameters : list or tuple of float The K_1 coefficient and exponent m. global_displacement The total displacement for each time step, from the FEM. global_stress The true (Cauchy) stress for each time step, from the FEM. undeformed_length : float The length of the undeformed specimen. """ coef, exp = material_parameters stretch = 1 + np.array(global_displacement) / undeformed_length # axial stress values stress_fem_2pk = np.array([sig for sig in global_stress]) stress_fem = stress_fem_2pk * stretch stress_analytic = _get_analytic_stress(stretch, coef, exp) fig, (ax_stress, ax_difference) = plt.subplots(nrows=2, sharex=True) ax_stress.plot(stretch, stress_fem, '.-', label='FEM') ax_stress.plot(stretch, stress_analytic, '--', label='analytic') ax_difference.plot(stretch, stress_fem - stress_analytic, '.-') ax_stress.legend(loc='best').set_draggable(True) ax_stress.set_ylabel(r'nominal stress $\mathrm{[Pa]}$') ax_stress.grid() ax_difference.set_ylabel(r'difference in nominal stress $\mathrm{[Pa]}$') ax_difference.set_xlabel(r'stretch $\mathrm{[-]}$') ax_difference.grid() plt.tight_layout() plt.show() def stress_strain( out, problem, _state, order=1, global_stress=None, global_displacement=None, **_): """ Compute the stress and the strain and add them to the output. Parameters ---------- out : dict Holds the results of the finite element computation. problem : sfepy.discrete.Problem order : int The approximation order of the displacement field. global_displacement Total displacement for each time step, current value will be appended. global_stress The true (Cauchy) stress for each time step, current value will be appended. Returns ------- out : dict """ strain = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='strain', copy_materials=False) out['green_strain'] = Struct( name='output_data', mode='cell', data=strain, dofs=None) stress_1 = problem.evaluate( 'dw_tl_he_genyeoh.%d.Omega(m1.par, v, u)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress_p = problem.evaluate( 'dw_tl_bulk_pressure.%d.Omega(v, u, p)' % (2*order), mode='el_avg', term_mode='stress', copy_materials=False) stress = stress_1 + stress_p out['stress'] = Struct( name='output_data', mode='cell', data=stress, dofs=None) global_stress.append(stress[0, 0, 0, 0]) global_displacement.append(get_displacement( problem.ts, np.array([[1., 0, 0]]))[0]) return out def main(cli_args): dims = parse_argument_list(cli_args.dims, float) shape = parse_argument_list(cli_args.shape, int) centre = parse_argument_list(cli_args.centre, float) material_parameters = parse_argument_list(cli_args.material_parameters, float) order = cli_args.order ts_vals = cli_args.ts.split(',') ts = { 't0' : float(ts_vals[0]), 't1' : float(ts_vals[1]), 'n_step' : int(ts_vals[2])} do_plot = cli_args.plot ### Mesh and regions ### mesh = gen_block_mesh( dims, shape, centre, name='block', verbose=False) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') lbn, rtf = domain.get_mesh_bounding_box() box_regions = define_box_regions(3, lbn, rtf) regions = dict([ [r, domain.create_region(r, box_regions[r][0], box_regions[r][1])] for r in box_regions]) ### Fields ### scalar_field = Field.from_args( 'fu', np.float64, 'scalar', omega, approx_order=order-1) vector_field = Field.from_args( 'fv', np.float64, 'vector', omega, approx_order=order) u = FieldVariable('u', 'unknown', vector_field, history=1) v = FieldVariable('v', 'test', vector_field, primary_var_name='u') p = FieldVariable('p', 'unknown', scalar_field, history=1) q = FieldVariable('q', 'test', scalar_field, primary_var_name='p') ### Material ### coefficient, exponent = material_parameters m_1 = Material( 'm1', par=[coefficient, exponent], ) ### Boundary conditions ### x_sym = EssentialBC('x_sym', regions['Left'], {'u.0' : 0.0}) y_sym = EssentialBC('y_sym', regions['Near'], {'u.1' : 0.0}) z_sym = EssentialBC('z_sym', regions['Bottom'], {'u.2' : 0.0}) disp_fun = Function('disp_fun', get_displacement) displacement = EssentialBC( 'displacement', regions['Right'], {'u.0' : disp_fun}) ebcs = Conditions([x_sym, y_sym, z_sym, displacement]) ### Terms and equations ### integral = Integral('i', order=2*order+1) term_1 = Term.new( 'dw_tl_he_genyeoh(m1.par, v, u)', integral, omega, m1=m_1, v=v, u=u) term_pressure = Term.new( 'dw_tl_bulk_pressure(v, u, p)', integral, omega, v=v, u=u, p=p) term_volume_change = Term.new( 'dw_tl_volume(q, u)', integral, omega, q=q, u=u, term_mode='volume') term_volume = Term.new( 'dw_volume_integrate(q)', integral, omega, q=q) eq_balance = Equation('balance', term_1 + term_pressure) eq_volume = Equation('volume', term_volume_change - term_volume) equations = Equations([eq_balance, eq_volume]) ### Solvers ### ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton( {'i_max' : 20}, lin_solver=ls, status=nls_status ) ### Problem ### pb = Problem('hyper', equations=equations) pb.set_bcs(ebcs=ebcs) pb.set_ics(ics=
Conditions([])
sfepy.discrete.conditions.Conditions
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r') output('') output('Supported writable mesh formats:') output('--------------------------------') output_mesh_formats('w') sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = _parse_val_or_vec(options.scale, 'scale', parser) center = _parse_val_or_vec(options.center, 'center', parser) filename_in, filename_out = args mesh =
Mesh.from_file(filename_in)
sfepy.discrete.fem.Mesh.from_file
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r') output('') output('Supported writable mesh formats:') output('--------------------------------') output_mesh_formats('w') sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = _parse_val_or_vec(options.scale, 'scale', parser) center = _parse_val_or_vec(options.center, 'center', parser) filename_in, filename_out = args mesh = Mesh.from_file(filename_in) if scale is not None: if len(scale) == 1: tr = nm.eye(mesh.dim, dtype=nm.float64) * scale elif len(scale) == mesh.dim: tr = nm.diag(scale) else: raise ValueError('bad scale! (%s)' % scale) mesh.transform_coors(tr) if center is not None: cc = 0.5 * mesh.get_bounding_box().sum(0) shift = center - cc tr = nm.c_[nm.eye(mesh.dim, dtype=nm.float64), shift[:, None]] mesh.transform_coors(tr) if options.refine > 0: domain = FEDomain(mesh.name, mesh) output('initial mesh: %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) mesh = domain.mesh io = MeshIO.for_format(filename_out, format=options.format, writable=True) cell_types = ', '.join(supported_cell_types[io.format])
output('writing [%s] %s...' % (cell_types, filename_out))
sfepy.base.base.output
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r') output('') output('Supported writable mesh formats:') output('--------------------------------') output_mesh_formats('w') sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = _parse_val_or_vec(options.scale, 'scale', parser) center = _parse_val_or_vec(options.center, 'center', parser) filename_in, filename_out = args mesh = Mesh.from_file(filename_in) if scale is not None: if len(scale) == 1: tr = nm.eye(mesh.dim, dtype=nm.float64) * scale elif len(scale) == mesh.dim: tr = nm.diag(scale) else: raise ValueError('bad scale! (%s)' % scale) mesh.transform_coors(tr) if center is not None: cc = 0.5 * mesh.get_bounding_box().sum(0) shift = center - cc tr = nm.c_[nm.eye(mesh.dim, dtype=nm.float64), shift[:, None]] mesh.transform_coors(tr) if options.refine > 0: domain = FEDomain(mesh.name, mesh) output('initial mesh: %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) mesh = domain.mesh io = MeshIO.for_format(filename_out, format=options.format, writable=True) cell_types = ', '.join(supported_cell_types[io.format]) output('writing [%s] %s...' % (cell_types, filename_out)) mesh.write(filename_out, io=io)
output('...done')
sfepy.base.base.output
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list:
output('Supported readable mesh formats:')
sfepy.base.base.output
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:')
output('--------------------------------')
sfepy.base.base.output
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------')
output_mesh_formats('r')
sfepy.discrete.fem.meshio.output_mesh_formats
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r')
output('')
sfepy.base.base.output
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r') output('')
output('Supported writable mesh formats:')
sfepy.base.base.output
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r') output('') output('Supported writable mesh formats:')
output('--------------------------------')
sfepy.base.base.output
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r') output('') output('Supported writable mesh formats:') output('--------------------------------')
output_mesh_formats('w')
sfepy.discrete.fem.meshio.output_mesh_formats
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r') output('') output('Supported writable mesh formats:') output('--------------------------------') output_mesh_formats('w') sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = _parse_val_or_vec(options.scale, 'scale', parser) center = _parse_val_or_vec(options.center, 'center', parser) filename_in, filename_out = args mesh = Mesh.from_file(filename_in) if scale is not None: if len(scale) == 1: tr = nm.eye(mesh.dim, dtype=nm.float64) * scale elif len(scale) == mesh.dim: tr = nm.diag(scale) else: raise ValueError('bad scale! (%s)' % scale) mesh.transform_coors(tr) if center is not None: cc = 0.5 * mesh.get_bounding_box().sum(0) shift = center - cc tr = nm.c_[nm.eye(mesh.dim, dtype=nm.float64), shift[:, None]] mesh.transform_coors(tr) if options.refine > 0: domain =
FEDomain(mesh.name, mesh)
sfepy.discrete.fem.FEDomain
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option =
nm.array(option, dtype=nm.float64, ndmin=1)
sfepy.base.base.nm.array
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r') output('') output('Supported writable mesh formats:') output('--------------------------------') output_mesh_formats('w') sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = _parse_val_or_vec(options.scale, 'scale', parser) center = _parse_val_or_vec(options.center, 'center', parser) filename_in, filename_out = args mesh = Mesh.from_file(filename_in) if scale is not None: if len(scale) == 1: tr = nm.eye(mesh.dim, dtype=nm.float64) * scale elif len(scale) == mesh.dim: tr = nm.diag(scale) else: raise ValueError('bad scale! (%s)' % scale) mesh.transform_coors(tr) if center is not None: cc = 0.5 * mesh.get_bounding_box().sum(0) shift = center - cc tr = nm.c_[nm.eye(mesh.dim, dtype=nm.float64), shift[:, None]] mesh.transform_coors(tr) if options.refine > 0: domain = FEDomain(mesh.name, mesh) output('initial mesh: %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) for ii in range(options.refine):
output('refine %d...' % ii)
sfepy.base.base.output
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except:
output('bad %s! (%s)' % (name, option))
sfepy.base.base.output
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r') output('') output('Supported writable mesh formats:') output('--------------------------------') output_mesh_formats('w') sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = _parse_val_or_vec(options.scale, 'scale', parser) center = _parse_val_or_vec(options.center, 'center', parser) filename_in, filename_out = args mesh = Mesh.from_file(filename_in) if scale is not None: if len(scale) == 1: tr =
nm.eye(mesh.dim, dtype=nm.float64)
sfepy.base.base.nm.eye
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r') output('') output('Supported writable mesh formats:') output('--------------------------------') output_mesh_formats('w') sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = _parse_val_or_vec(options.scale, 'scale', parser) center = _parse_val_or_vec(options.center, 'center', parser) filename_in, filename_out = args mesh = Mesh.from_file(filename_in) if scale is not None: if len(scale) == 1: tr = nm.eye(mesh.dim, dtype=nm.float64) * scale elif len(scale) == mesh.dim: tr =
nm.diag(scale)
sfepy.base.base.nm.diag
#!/usr/bin/env python """ Convert a mesh file from one SfePy-supported format to another. Examples:: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 -c 0 """ import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.discrete.fem import Mesh, FEDomain from sfepy.discrete.fem.meshio import (output_mesh_formats, MeshIO, supported_cell_types) usage = '%prog [options] filename_in filename_out\n' + __doc__.rstrip() help = { 'scale' : 'scale factor (float or comma-separated list for each axis)' ' [default: %default]', 'center' : 'center of the output mesh (0 for origin or' ' comma-separated list for each axis) applied after scaling' ' [default: %default]', 'refine' : 'uniform refinement level [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported readable/writable output mesh formats', } def _parse_val_or_vec(option, name, parser): if option is not None: try: try: option = float(option) except ValueError: option = [float(ii) for ii in option.split(',')] option = nm.array(option, dtype=nm.float64, ndmin=1) except: output('bad %s! (%s)' % (name, option)) parser.print_help() sys.exit(1) return option def main(): parser = OptionParser(usage=usage) parser.add_option('-s', '--scale', metavar='scale', action='store', dest='scale', default=None, help=help['scale']) parser.add_option('-c', '--center', metavar='center', action='store', dest='center', default=None, help=help['center']) parser.add_option('-r', '--refine', metavar='level', action='store', type=int, dest='refine', default=0, help=help['refine']) parser.add_option('-f', '--format', metavar='format', action='store', type='string', dest='format', default=None, help=help['format']) parser.add_option('-l', '--list', action='store_true', dest='list', help=help['list']) (options, args) = parser.parse_args() if options.list: output('Supported readable mesh formats:') output('--------------------------------') output_mesh_formats('r') output('') output('Supported writable mesh formats:') output('--------------------------------') output_mesh_formats('w') sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = _parse_val_or_vec(options.scale, 'scale', parser) center = _parse_val_or_vec(options.center, 'center', parser) filename_in, filename_out = args mesh = Mesh.from_file(filename_in) if scale is not None: if len(scale) == 1: tr = nm.eye(mesh.dim, dtype=nm.float64) * scale elif len(scale) == mesh.dim: tr = nm.diag(scale) else: raise ValueError('bad scale! (%s)' % scale) mesh.transform_coors(tr) if center is not None: cc = 0.5 * mesh.get_bounding_box().sum(0) shift = center - cc tr = nm.c_[
nm.eye(mesh.dim, dtype=nm.float64)
sfepy.base.base.nm.eye
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf =
Struct(name=name)
sfepy.base.base.Struct
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 = Struct(name=key, order=conf) elif len(conf) == 3: c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights']) d2['integral_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['integral_'+c2.name] = c2 return d2 def transform_fields(adict): dtypes = {'real' : nm.float64, 'complex' : nm.complex128} d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['dtype', 'shape', 'region', 'approx_order', 'space', 'poly_space_base']) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dtype', nm.float64) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_'+c2.name] = c2 return d2 def transform_materials(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, function=conf) d2['material_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['values', 'function', 'kind']) if len(conf) == 4: c2.flags = conf[3] d2['material_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['material_'+conf['name']] = c2 return d2 def transform_solvers(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind','params']) for param, val in six.iteritems(c2.params): setattr(c2, param, val) delattr(c2, 'params') d2['solvers_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['solvers_'+c2.name] = c2 return d2 def transform_functions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['function']) d2['function_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['function_'+c2.name] = c2 return d2 def transform_to_struct_1(adict): return
dict_to_struct(adict, flag=(1,))
sfepy.base.base.dict_to_struct
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 = Struct(name=key, order=conf) elif len(conf) == 3: c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights']) d2['integral_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['integral_'+c2.name] = c2 return d2 def transform_fields(adict): dtypes = {'real' : nm.float64, 'complex' : nm.complex128} d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['dtype', 'shape', 'region', 'approx_order', 'space', 'poly_space_base']) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dtype', nm.float64) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_'+c2.name] = c2 return d2 def transform_materials(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, function=conf) d2['material_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['values', 'function', 'kind']) if len(conf) == 4: c2.flags = conf[3] d2['material_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['material_'+conf['name']] = c2 return d2 def transform_solvers(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind','params']) for param, val in six.iteritems(c2.params): setattr(c2, param, val) delattr(c2, 'params') d2['solvers_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['solvers_'+c2.name] = c2 return d2 def transform_functions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['function']) d2['function_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['function_'+c2.name] = c2 return d2 def transform_to_struct_1(adict): return dict_to_struct(adict, flag=(1,)) def transform_to_i_struct_1(adict): return
dict_to_struct(adict, flag=(1,), constructor=IndexedStruct)
sfepy.base.base.dict_to_struct
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 = Struct(name=key, order=conf) elif len(conf) == 3: c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights']) d2['integral_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['integral_'+c2.name] = c2 return d2 def transform_fields(adict): dtypes = {'real' : nm.float64, 'complex' : nm.complex128} d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['dtype', 'shape', 'region', 'approx_order', 'space', 'poly_space_base']) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dtype', nm.float64) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_'+c2.name] = c2 return d2 def transform_materials(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, function=conf) d2['material_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['values', 'function', 'kind']) if len(conf) == 4: c2.flags = conf[3] d2['material_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['material_'+conf['name']] = c2 return d2 def transform_solvers(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind','params']) for param, val in six.iteritems(c2.params): setattr(c2, param, val) delattr(c2, 'params') d2['solvers_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['solvers_'+c2.name] = c2 return d2 def transform_functions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['function']) d2['function_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['function_'+c2.name] = c2 return d2 def transform_to_struct_1(adict): return dict_to_struct(adict, flag=(1,)) def transform_to_i_struct_1(adict): return dict_to_struct(adict, flag=(1,), constructor=IndexedStruct) def transform_to_struct_01(adict): return
dict_to_struct(adict, flag=(0,1))
sfepy.base.base.dict_to_struct
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 = Struct(name=key, order=conf) elif len(conf) == 3: c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights']) d2['integral_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['integral_'+c2.name] = c2 return d2 def transform_fields(adict): dtypes = {'real' : nm.float64, 'complex' : nm.complex128} d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['dtype', 'shape', 'region', 'approx_order', 'space', 'poly_space_base']) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dtype', nm.float64) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_'+c2.name] = c2 return d2 def transform_materials(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, function=conf) d2['material_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['values', 'function', 'kind']) if len(conf) == 4: c2.flags = conf[3] d2['material_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['material_'+conf['name']] = c2 return d2 def transform_solvers(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind','params']) for param, val in six.iteritems(c2.params): setattr(c2, param, val) delattr(c2, 'params') d2['solvers_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['solvers_'+c2.name] = c2 return d2 def transform_functions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['function']) d2['function_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['function_'+c2.name] = c2 return d2 def transform_to_struct_1(adict): return dict_to_struct(adict, flag=(1,)) def transform_to_i_struct_1(adict): return dict_to_struct(adict, flag=(1,), constructor=IndexedStruct) def transform_to_struct_01(adict): return dict_to_struct(adict, flag=(0,1)) def transform_to_struct_10(adict): return
dict_to_struct(adict, flag=(1,0))
sfepy.base.base.dict_to_struct
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 = Struct(name=key, order=conf) elif len(conf) == 3: c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights']) d2['integral_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['integral_'+c2.name] = c2 return d2 def transform_fields(adict): dtypes = {'real' : nm.float64, 'complex' : nm.complex128} d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['dtype', 'shape', 'region', 'approx_order', 'space', 'poly_space_base']) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dtype', nm.float64) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_'+c2.name] = c2 return d2 def transform_materials(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, function=conf) d2['material_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['values', 'function', 'kind']) if len(conf) == 4: c2.flags = conf[3] d2['material_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['material_'+conf['name']] = c2 return d2 def transform_solvers(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind','params']) for param, val in six.iteritems(c2.params): setattr(c2, param, val) delattr(c2, 'params') d2['solvers_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['solvers_'+c2.name] = c2 return d2 def transform_functions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['function']) d2['function_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['function_'+c2.name] = c2 return d2 def transform_to_struct_1(adict): return dict_to_struct(adict, flag=(1,)) def transform_to_i_struct_1(adict): return dict_to_struct(adict, flag=(1,), constructor=IndexedStruct) def transform_to_struct_01(adict): return dict_to_struct(adict, flag=(0,1)) def transform_to_struct_10(adict): return dict_to_struct(adict, flag=(1,0)) transforms = { 'options' : transform_to_i_struct_1, 'solvers' : transform_solvers, 'integrals' : transform_integrals, 'regions' : transform_regions, 'fields' : transform_fields, 'variables' : transform_variables, 'ebcs' : transform_ebcs, 'epbcs' : transform_epbcs, 'dgebcs' : transform_dgebcs, 'dgepbcs' : transform_dgepbcs, 'nbcs' : transform_to_struct_01, 'lcbcs' : transform_lcbcs, 'ics' : transform_ics, 'materials' : transform_materials, 'functions' : transform_functions, } def dict_from_string(string, allow_tuple=False, free_word=False): """ Parse `string` and return a dictionary that can be used to construct/override a ProblemConf instance. """ if string is None: return {} if isinstance(string, dict): return string parser =
create_bnf(allow_tuple=allow_tuple, free_word=free_word)
sfepy.base.parse_conf.create_bnf
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return
copy(_required)
sfepy.base.base.copy
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required),
copy(_other)
sfepy.base.base.copy
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 = Struct(name=key, order=conf) elif len(conf) == 3: c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights']) d2['integral_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['integral_'+c2.name] = c2 return d2 def transform_fields(adict): dtypes = {'real' : nm.float64, 'complex' : nm.complex128} d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['dtype', 'shape', 'region', 'approx_order', 'space', 'poly_space_base']) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dtype', nm.float64) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_'+c2.name] = c2 return d2 def transform_materials(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, function=conf) d2['material_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['values', 'function', 'kind']) if len(conf) == 4: c2.flags = conf[3] d2['material_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['material_'+conf['name']] = c2 return d2 def transform_solvers(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind','params']) for param, val in six.iteritems(c2.params): setattr(c2, param, val) delattr(c2, 'params') d2['solvers_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['solvers_'+c2.name] = c2 return d2 def transform_functions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['function']) d2['function_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['function_'+c2.name] = c2 return d2 def transform_to_struct_1(adict): return dict_to_struct(adict, flag=(1,)) def transform_to_i_struct_1(adict): return dict_to_struct(adict, flag=(1,), constructor=IndexedStruct) def transform_to_struct_01(adict): return dict_to_struct(adict, flag=(0,1)) def transform_to_struct_10(adict): return dict_to_struct(adict, flag=(1,0)) transforms = { 'options' : transform_to_i_struct_1, 'solvers' : transform_solvers, 'integrals' : transform_integrals, 'regions' : transform_regions, 'fields' : transform_fields, 'variables' : transform_variables, 'ebcs' : transform_ebcs, 'epbcs' : transform_epbcs, 'dgebcs' : transform_dgebcs, 'dgepbcs' : transform_dgepbcs, 'nbcs' : transform_to_struct_01, 'lcbcs' : transform_lcbcs, 'ics' : transform_ics, 'materials' : transform_materials, 'functions' : transform_functions, } def dict_from_string(string, allow_tuple=False, free_word=False): """ Parse `string` and return a dictionary that can be used to construct/override a ProblemConf instance. """ if string is None: return {} if isinstance(string, dict): return string parser = create_bnf(allow_tuple=allow_tuple, free_word=free_word) out = {} for r in parser.parseString(string, parseAll=True): out.update(r) return out def dict_from_options(options): """ Return a dictionary that can be used to construct/override a ProblemConf instance based on `options`. See ``--conf`` and ``--options`` options of the ``simple.py`` script. """ override = dict_from_string(options.conf) if options.app_options: if not 'options' in override: override['options'] = {} override_options = dict_from_string(options.app_options) override['options'].update(override_options) return override ## # 27.10.2005, c class ProblemConf(Struct): """ Problem configuration, corresponding to an input (problem description file). It validates the input using lists of required and other keywords that have to/can appear in the input. Default keyword lists can be obtained by sfepy.base.conf.get_standard_keywords(). ProblemConf instance is used to construct a Problem instance via Problem.from_conf(conf). """ @staticmethod def from_file(filename, required=None, other=None, verbose=True, define_args=None, override=None, setup=True): """ Loads the problem definition from a file. The filename can either contain plain definitions, or it can contain the define() function, in which case it will be called to return the input definitions. The job of the define() function is to return a dictionary of parameters. How the dictionary is constructed is not our business, but the usual way is to simply have a function define() along these lines in the input file:: def define(): options = { 'save_eig_vectors' : None, 'eigen_solver' : 'eigen1', } region_2 = { 'name' : 'Surface', 'select' : 'nodes of surface', } return locals() Optionally, the define() function can accept additional arguments that should be defined using the `define_args` tuple or dictionary. """ funmod =
import_file(filename, package_name=False)
sfepy.base.base.import_file
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 = Struct(name=key, order=conf) elif len(conf) == 3: c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights']) d2['integral_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['integral_'+c2.name] = c2 return d2 def transform_fields(adict): dtypes = {'real' : nm.float64, 'complex' : nm.complex128} d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['dtype', 'shape', 'region', 'approx_order', 'space', 'poly_space_base']) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dtype', nm.float64) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_'+c2.name] = c2 return d2 def transform_materials(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, function=conf) d2['material_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['values', 'function', 'kind']) if len(conf) == 4: c2.flags = conf[3] d2['material_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['material_'+conf['name']] = c2 return d2 def transform_solvers(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind','params']) for param, val in six.iteritems(c2.params): setattr(c2, param, val) delattr(c2, 'params') d2['solvers_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['solvers_'+c2.name] = c2 return d2 def transform_functions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['function']) d2['function_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['function_'+c2.name] = c2 return d2 def transform_to_struct_1(adict): return dict_to_struct(adict, flag=(1,)) def transform_to_i_struct_1(adict): return dict_to_struct(adict, flag=(1,), constructor=IndexedStruct) def transform_to_struct_01(adict): return dict_to_struct(adict, flag=(0,1)) def transform_to_struct_10(adict): return dict_to_struct(adict, flag=(1,0)) transforms = { 'options' : transform_to_i_struct_1, 'solvers' : transform_solvers, 'integrals' : transform_integrals, 'regions' : transform_regions, 'fields' : transform_fields, 'variables' : transform_variables, 'ebcs' : transform_ebcs, 'epbcs' : transform_epbcs, 'dgebcs' : transform_dgebcs, 'dgepbcs' : transform_dgepbcs, 'nbcs' : transform_to_struct_01, 'lcbcs' : transform_lcbcs, 'ics' : transform_ics, 'materials' : transform_materials, 'functions' : transform_functions, } def dict_from_string(string, allow_tuple=False, free_word=False): """ Parse `string` and return a dictionary that can be used to construct/override a ProblemConf instance. """ if string is None: return {} if isinstance(string, dict): return string parser = create_bnf(allow_tuple=allow_tuple, free_word=free_word) out = {} for r in parser.parseString(string, parseAll=True): out.update(r) return out def dict_from_options(options): """ Return a dictionary that can be used to construct/override a ProblemConf instance based on `options`. See ``--conf`` and ``--options`` options of the ``simple.py`` script. """ override = dict_from_string(options.conf) if options.app_options: if not 'options' in override: override['options'] = {} override_options = dict_from_string(options.app_options) override['options'].update(override_options) return override ## # 27.10.2005, c class ProblemConf(Struct): """ Problem configuration, corresponding to an input (problem description file). It validates the input using lists of required and other keywords that have to/can appear in the input. Default keyword lists can be obtained by sfepy.base.conf.get_standard_keywords(). ProblemConf instance is used to construct a Problem instance via Problem.from_conf(conf). """ @staticmethod def from_file(filename, required=None, other=None, verbose=True, define_args=None, override=None, setup=True): """ Loads the problem definition from a file. The filename can either contain plain definitions, or it can contain the define() function, in which case it will be called to return the input definitions. The job of the define() function is to return a dictionary of parameters. How the dictionary is constructed is not our business, but the usual way is to simply have a function define() along these lines in the input file:: def define(): options = { 'save_eig_vectors' : None, 'eigen_solver' : 'eigen1', } region_2 = { 'name' : 'Surface', 'select' : 'nodes of surface', } return locals() Optionally, the define() function can accept additional arguments that should be defined using the `define_args` tuple or dictionary. """ funmod = import_file(filename, package_name=False) if "define" in funmod.__dict__: if define_args is None: define_dict = funmod.__dict__["define"]() else: if isinstance(define_args, str): define_args = dict_from_string(define_args) if isinstance(define_args, dict): define_dict = funmod.__dict__["define"](**define_args) else: define_dict = funmod.__dict__["define"](*define_args) else: define_dict = funmod.__dict__ obj = ProblemConf(define_dict, funmod=funmod, filename=filename, required=required, other=other, verbose=verbose, override=override, setup=setup) return obj @staticmethod def from_file_and_options(filename, options, required=None, other=None, verbose=True, define_args=None, setup=True): """ Utility function, a wrapper around ProblemConf.from_file() with possible override taken from `options`. """ override = dict_from_options(options) obj = ProblemConf.from_file(filename, required=required, other=other, verbose=verbose, define_args=define_args, override=override, setup=setup) return obj @staticmethod def from_module(module, required=None, other=None, verbose=True, override=None, setup=True): obj = ProblemConf(module.__dict__, module, module.__name__, required, other, verbose, override, setup=setup) return obj @staticmethod def from_dict(dict_, funmod, required=None, other=None, verbose=True, override=None, setup=True): obj = ProblemConf(dict_, funmod, None, required, other, verbose, override, setup=setup) return obj def __init__(self, define_dict, funmod=None, filename=None, required=None, other=None, verbose=True, override=None, setup=True): if override: if isinstance(override, Struct): override = override.__dict__ define_dict = update_dict_recursively(define_dict, override, True) self.__dict__.update(define_dict) self.verbose = verbose if setup: self.setup(funmod=funmod, filename=filename, required=required, other=other) def setup(self, define_dict=None, funmod=None, filename=None, required=None, other=None): define_dict =
get_default(define_dict, self.__dict__)
sfepy.base.base.get_default
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 = Struct(name=key, order=conf) elif len(conf) == 3: c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights']) d2['integral_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['integral_'+c2.name] = c2 return d2 def transform_fields(adict): dtypes = {'real' : nm.float64, 'complex' : nm.complex128} d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['dtype', 'shape', 'region', 'approx_order', 'space', 'poly_space_base']) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dtype', nm.float64) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_'+c2.name] = c2 return d2 def transform_materials(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, function=conf) d2['material_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['values', 'function', 'kind']) if len(conf) == 4: c2.flags = conf[3] d2['material_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['material_'+conf['name']] = c2 return d2 def transform_solvers(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind','params']) for param, val in six.iteritems(c2.params): setattr(c2, param, val) delattr(c2, 'params') d2['solvers_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['solvers_'+c2.name] = c2 return d2 def transform_functions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['function']) d2['function_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['function_'+c2.name] = c2 return d2 def transform_to_struct_1(adict): return dict_to_struct(adict, flag=(1,)) def transform_to_i_struct_1(adict): return dict_to_struct(adict, flag=(1,), constructor=IndexedStruct) def transform_to_struct_01(adict): return dict_to_struct(adict, flag=(0,1)) def transform_to_struct_10(adict): return dict_to_struct(adict, flag=(1,0)) transforms = { 'options' : transform_to_i_struct_1, 'solvers' : transform_solvers, 'integrals' : transform_integrals, 'regions' : transform_regions, 'fields' : transform_fields, 'variables' : transform_variables, 'ebcs' : transform_ebcs, 'epbcs' : transform_epbcs, 'dgebcs' : transform_dgebcs, 'dgepbcs' : transform_dgepbcs, 'nbcs' : transform_to_struct_01, 'lcbcs' : transform_lcbcs, 'ics' : transform_ics, 'materials' : transform_materials, 'functions' : transform_functions, } def dict_from_string(string, allow_tuple=False, free_word=False): """ Parse `string` and return a dictionary that can be used to construct/override a ProblemConf instance. """ if string is None: return {} if isinstance(string, dict): return string parser = create_bnf(allow_tuple=allow_tuple, free_word=free_word) out = {} for r in parser.parseString(string, parseAll=True): out.update(r) return out def dict_from_options(options): """ Return a dictionary that can be used to construct/override a ProblemConf instance based on `options`. See ``--conf`` and ``--options`` options of the ``simple.py`` script. """ override = dict_from_string(options.conf) if options.app_options: if not 'options' in override: override['options'] = {} override_options = dict_from_string(options.app_options) override['options'].update(override_options) return override ## # 27.10.2005, c class ProblemConf(Struct): """ Problem configuration, corresponding to an input (problem description file). It validates the input using lists of required and other keywords that have to/can appear in the input. Default keyword lists can be obtained by sfepy.base.conf.get_standard_keywords(). ProblemConf instance is used to construct a Problem instance via Problem.from_conf(conf). """ @staticmethod def from_file(filename, required=None, other=None, verbose=True, define_args=None, override=None, setup=True): """ Loads the problem definition from a file. The filename can either contain plain definitions, or it can contain the define() function, in which case it will be called to return the input definitions. The job of the define() function is to return a dictionary of parameters. How the dictionary is constructed is not our business, but the usual way is to simply have a function define() along these lines in the input file:: def define(): options = { 'save_eig_vectors' : None, 'eigen_solver' : 'eigen1', } region_2 = { 'name' : 'Surface', 'select' : 'nodes of surface', } return locals() Optionally, the define() function can accept additional arguments that should be defined using the `define_args` tuple or dictionary. """ funmod = import_file(filename, package_name=False) if "define" in funmod.__dict__: if define_args is None: define_dict = funmod.__dict__["define"]() else: if isinstance(define_args, str): define_args = dict_from_string(define_args) if isinstance(define_args, dict): define_dict = funmod.__dict__["define"](**define_args) else: define_dict = funmod.__dict__["define"](*define_args) else: define_dict = funmod.__dict__ obj = ProblemConf(define_dict, funmod=funmod, filename=filename, required=required, other=other, verbose=verbose, override=override, setup=setup) return obj @staticmethod def from_file_and_options(filename, options, required=None, other=None, verbose=True, define_args=None, setup=True): """ Utility function, a wrapper around ProblemConf.from_file() with possible override taken from `options`. """ override = dict_from_options(options) obj = ProblemConf.from_file(filename, required=required, other=other, verbose=verbose, define_args=define_args, override=override, setup=setup) return obj @staticmethod def from_module(module, required=None, other=None, verbose=True, override=None, setup=True): obj = ProblemConf(module.__dict__, module, module.__name__, required, other, verbose, override, setup=setup) return obj @staticmethod def from_dict(dict_, funmod, required=None, other=None, verbose=True, override=None, setup=True): obj = ProblemConf(dict_, funmod, None, required, other, verbose, override, setup=setup) return obj def __init__(self, define_dict, funmod=None, filename=None, required=None, other=None, verbose=True, override=None, setup=True): if override: if isinstance(override, Struct): override = override.__dict__ define_dict = update_dict_recursively(define_dict, override, True) self.__dict__.update(define_dict) self.verbose = verbose if setup: self.setup(funmod=funmod, filename=filename, required=required, other=other) def setup(self, define_dict=None, funmod=None, filename=None, required=None, other=None): define_dict = get_default(define_dict, self.__dict__) self._filename = filename self.validate(required=required, other=other) self.transform_input_trivial() self._raw = {} for key, val in six.iteritems(define_dict): if isinstance(val, dict): self._raw[key] = copy(val) self.transform_input() self.funmod = funmod def _validate_helper(self, items, but_nots): keys = list(self.__dict__.keys()) left_over = keys[:] if but_nots is not None: for item in but_nots: match = re.compile('^' + item + '$').match for key in keys: if match(key): left_over.remove(key) missing = [] if items is not None: for item in items: found = False match = re.compile('^' + item + '$').match for key in keys: if match(key): found = True left_over.remove(key) if not found: missing.append(item) return left_over, missing def validate(self, required=None, other=None): required_left_over, required_missing \ = self._validate_helper(required, other) other_left_over, other_missing \ = self._validate_helper(other, required)
assert_(required_left_over == other_left_over)
sfepy.base.base.assert_
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 =
Struct(name=key, select=conf)
sfepy.base.base.Struct
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 =
Struct(name=key, order=conf)
sfepy.base.base.Struct
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 = Struct(name=key, order=conf) elif len(conf) == 3: c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights']) d2['integral_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['integral_'+c2.name] = c2 return d2 def transform_fields(adict): dtypes = {'real' : nm.float64, 'complex' : nm.complex128} d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['dtype', 'shape', 'region', 'approx_order', 'space', 'poly_space_base']) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dtype', nm.float64) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_'+c2.name] = c2 return d2 def transform_materials(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 =
Struct(name=key, function=conf)
sfepy.base.base.Struct
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 = Struct(name=key, order=conf) elif len(conf) == 3: c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights']) d2['integral_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['integral_'+c2.name] = c2 return d2 def transform_fields(adict): dtypes = {'real' : nm.float64, 'complex' : nm.complex128} d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['dtype', 'shape', 'region', 'approx_order', 'space', 'poly_space_base']) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dtype', nm.float64) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_'+c2.name] = c2 return d2 def transform_materials(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, function=conf) d2['material_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['values', 'function', 'kind']) if len(conf) == 4: c2.flags = conf[3] d2['material_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['material_'+conf['name']] = c2 return d2 def transform_solvers(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind','params']) for param, val in six.iteritems(c2.params): setattr(c2, param, val) delattr(c2, 'params') d2['solvers_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['solvers_'+c2.name] = c2 return d2 def transform_functions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['function']) d2['function_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['function_'+c2.name] = c2 return d2 def transform_to_struct_1(adict): return dict_to_struct(adict, flag=(1,)) def transform_to_i_struct_1(adict): return dict_to_struct(adict, flag=(1,), constructor=IndexedStruct) def transform_to_struct_01(adict): return dict_to_struct(adict, flag=(0,1)) def transform_to_struct_10(adict): return dict_to_struct(adict, flag=(1,0)) transforms = { 'options' : transform_to_i_struct_1, 'solvers' : transform_solvers, 'integrals' : transform_integrals, 'regions' : transform_regions, 'fields' : transform_fields, 'variables' : transform_variables, 'ebcs' : transform_ebcs, 'epbcs' : transform_epbcs, 'dgebcs' : transform_dgebcs, 'dgepbcs' : transform_dgepbcs, 'nbcs' : transform_to_struct_01, 'lcbcs' : transform_lcbcs, 'ics' : transform_ics, 'materials' : transform_materials, 'functions' : transform_functions, } def dict_from_string(string, allow_tuple=False, free_word=False): """ Parse `string` and return a dictionary that can be used to construct/override a ProblemConf instance. """ if string is None: return {} if isinstance(string, dict): return string parser = create_bnf(allow_tuple=allow_tuple, free_word=free_word) out = {} for r in parser.parseString(string, parseAll=True): out.update(r) return out def dict_from_options(options): """ Return a dictionary that can be used to construct/override a ProblemConf instance based on `options`. See ``--conf`` and ``--options`` options of the ``simple.py`` script. """ override = dict_from_string(options.conf) if options.app_options: if not 'options' in override: override['options'] = {} override_options = dict_from_string(options.app_options) override['options'].update(override_options) return override ## # 27.10.2005, c class ProblemConf(Struct): """ Problem configuration, corresponding to an input (problem description file). It validates the input using lists of required and other keywords that have to/can appear in the input. Default keyword lists can be obtained by sfepy.base.conf.get_standard_keywords(). ProblemConf instance is used to construct a Problem instance via Problem.from_conf(conf). """ @staticmethod def from_file(filename, required=None, other=None, verbose=True, define_args=None, override=None, setup=True): """ Loads the problem definition from a file. The filename can either contain plain definitions, or it can contain the define() function, in which case it will be called to return the input definitions. The job of the define() function is to return a dictionary of parameters. How the dictionary is constructed is not our business, but the usual way is to simply have a function define() along these lines in the input file:: def define(): options = { 'save_eig_vectors' : None, 'eigen_solver' : 'eigen1', } region_2 = { 'name' : 'Surface', 'select' : 'nodes of surface', } return locals() Optionally, the define() function can accept additional arguments that should be defined using the `define_args` tuple or dictionary. """ funmod = import_file(filename, package_name=False) if "define" in funmod.__dict__: if define_args is None: define_dict = funmod.__dict__["define"]() else: if isinstance(define_args, str): define_args = dict_from_string(define_args) if isinstance(define_args, dict): define_dict = funmod.__dict__["define"](**define_args) else: define_dict = funmod.__dict__["define"](*define_args) else: define_dict = funmod.__dict__ obj = ProblemConf(define_dict, funmod=funmod, filename=filename, required=required, other=other, verbose=verbose, override=override, setup=setup) return obj @staticmethod def from_file_and_options(filename, options, required=None, other=None, verbose=True, define_args=None, setup=True): """ Utility function, a wrapper around ProblemConf.from_file() with possible override taken from `options`. """ override = dict_from_options(options) obj = ProblemConf.from_file(filename, required=required, other=other, verbose=verbose, define_args=define_args, override=override, setup=setup) return obj @staticmethod def from_module(module, required=None, other=None, verbose=True, override=None, setup=True): obj = ProblemConf(module.__dict__, module, module.__name__, required, other, verbose, override, setup=setup) return obj @staticmethod def from_dict(dict_, funmod, required=None, other=None, verbose=True, override=None, setup=True): obj = ProblemConf(dict_, funmod, None, required, other, verbose, override, setup=setup) return obj def __init__(self, define_dict, funmod=None, filename=None, required=None, other=None, verbose=True, override=None, setup=True): if override: if isinstance(override, Struct): override = override.__dict__ define_dict =
update_dict_recursively(define_dict, override, True)
sfepy.base.base.update_dict_recursively
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 = Struct(name=key, order=conf) elif len(conf) == 3: c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights']) d2['integral_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['integral_'+c2.name] = c2 return d2 def transform_fields(adict): dtypes = {'real' : nm.float64, 'complex' : nm.complex128} d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['dtype', 'shape', 'region', 'approx_order', 'space', 'poly_space_base']) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dtype', nm.float64) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_'+c2.name] = c2 return d2 def transform_materials(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, function=conf) d2['material_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['values', 'function', 'kind']) if len(conf) == 4: c2.flags = conf[3] d2['material_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['material_'+conf['name']] = c2 return d2 def transform_solvers(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind','params']) for param, val in six.iteritems(c2.params): setattr(c2, param, val) delattr(c2, 'params') d2['solvers_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['solvers_'+c2.name] = c2 return d2 def transform_functions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['function']) d2['function_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['function_'+c2.name] = c2 return d2 def transform_to_struct_1(adict): return dict_to_struct(adict, flag=(1,)) def transform_to_i_struct_1(adict): return dict_to_struct(adict, flag=(1,), constructor=IndexedStruct) def transform_to_struct_01(adict): return dict_to_struct(adict, flag=(0,1)) def transform_to_struct_10(adict): return dict_to_struct(adict, flag=(1,0)) transforms = { 'options' : transform_to_i_struct_1, 'solvers' : transform_solvers, 'integrals' : transform_integrals, 'regions' : transform_regions, 'fields' : transform_fields, 'variables' : transform_variables, 'ebcs' : transform_ebcs, 'epbcs' : transform_epbcs, 'dgebcs' : transform_dgebcs, 'dgepbcs' : transform_dgepbcs, 'nbcs' : transform_to_struct_01, 'lcbcs' : transform_lcbcs, 'ics' : transform_ics, 'materials' : transform_materials, 'functions' : transform_functions, } def dict_from_string(string, allow_tuple=False, free_word=False): """ Parse `string` and return a dictionary that can be used to construct/override a ProblemConf instance. """ if string is None: return {} if isinstance(string, dict): return string parser = create_bnf(allow_tuple=allow_tuple, free_word=free_word) out = {} for r in parser.parseString(string, parseAll=True): out.update(r) return out def dict_from_options(options): """ Return a dictionary that can be used to construct/override a ProblemConf instance based on `options`. See ``--conf`` and ``--options`` options of the ``simple.py`` script. """ override = dict_from_string(options.conf) if options.app_options: if not 'options' in override: override['options'] = {} override_options = dict_from_string(options.app_options) override['options'].update(override_options) return override ## # 27.10.2005, c class ProblemConf(Struct): """ Problem configuration, corresponding to an input (problem description file). It validates the input using lists of required and other keywords that have to/can appear in the input. Default keyword lists can be obtained by sfepy.base.conf.get_standard_keywords(). ProblemConf instance is used to construct a Problem instance via Problem.from_conf(conf). """ @staticmethod def from_file(filename, required=None, other=None, verbose=True, define_args=None, override=None, setup=True): """ Loads the problem definition from a file. The filename can either contain plain definitions, or it can contain the define() function, in which case it will be called to return the input definitions. The job of the define() function is to return a dictionary of parameters. How the dictionary is constructed is not our business, but the usual way is to simply have a function define() along these lines in the input file:: def define(): options = { 'save_eig_vectors' : None, 'eigen_solver' : 'eigen1', } region_2 = { 'name' : 'Surface', 'select' : 'nodes of surface', } return locals() Optionally, the define() function can accept additional arguments that should be defined using the `define_args` tuple or dictionary. """ funmod = import_file(filename, package_name=False) if "define" in funmod.__dict__: if define_args is None: define_dict = funmod.__dict__["define"]() else: if isinstance(define_args, str): define_args = dict_from_string(define_args) if isinstance(define_args, dict): define_dict = funmod.__dict__["define"](**define_args) else: define_dict = funmod.__dict__["define"](*define_args) else: define_dict = funmod.__dict__ obj = ProblemConf(define_dict, funmod=funmod, filename=filename, required=required, other=other, verbose=verbose, override=override, setup=setup) return obj @staticmethod def from_file_and_options(filename, options, required=None, other=None, verbose=True, define_args=None, setup=True): """ Utility function, a wrapper around ProblemConf.from_file() with possible override taken from `options`. """ override = dict_from_options(options) obj = ProblemConf.from_file(filename, required=required, other=other, verbose=verbose, define_args=define_args, override=override, setup=setup) return obj @staticmethod def from_module(module, required=None, other=None, verbose=True, override=None, setup=True): obj = ProblemConf(module.__dict__, module, module.__name__, required, other, verbose, override, setup=setup) return obj @staticmethod def from_dict(dict_, funmod, required=None, other=None, verbose=True, override=None, setup=True): obj = ProblemConf(dict_, funmod, None, required, other, verbose, override, setup=setup) return obj def __init__(self, define_dict, funmod=None, filename=None, required=None, other=None, verbose=True, override=None, setup=True): if override: if isinstance(override, Struct): override = override.__dict__ define_dict = update_dict_recursively(define_dict, override, True) self.__dict__.update(define_dict) self.verbose = verbose if setup: self.setup(funmod=funmod, filename=filename, required=required, other=other) def setup(self, define_dict=None, funmod=None, filename=None, required=None, other=None): define_dict = get_default(define_dict, self.__dict__) self._filename = filename self.validate(required=required, other=other) self.transform_input_trivial() self._raw = {} for key, val in six.iteritems(define_dict): if isinstance(val, dict): self._raw[key] = copy(val) self.transform_input() self.funmod = funmod def _validate_helper(self, items, but_nots): keys = list(self.__dict__.keys()) left_over = keys[:] if but_nots is not None: for item in but_nots: match = re.compile('^' + item + '$').match for key in keys: if match(key): left_over.remove(key) missing = [] if items is not None: for item in items: found = False match = re.compile('^' + item + '$').match for key in keys: if match(key): found = True left_over.remove(key) if not found: missing.append(item) return left_over, missing def validate(self, required=None, other=None): required_left_over, required_missing \ = self._validate_helper(required, other) other_left_over, other_missing \ = self._validate_helper(other, required) assert_(required_left_over == other_left_over) if other_left_over and self.verbose:
output('left over:', other_left_over)
sfepy.base.base.output
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 = Struct(name=key, order=conf) elif len(conf) == 3: c2 = tuple_to_conf(key, conf, ['order', 'vals', 'weights']) d2['integral_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['integral_'+c2.name] = c2 return d2 def transform_fields(adict): dtypes = {'real' : nm.float64, 'complex' : nm.complex128} d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['dtype', 'shape', 'region', 'approx_order', 'space', 'poly_space_base']) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dtype', nm.float64) if c2.dtype in dtypes: c2.dtype = dtypes[c2.dtype] d2['field_'+c2.name] = c2 return d2 def transform_materials(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, function=conf) d2['material_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['values', 'function', 'kind']) if len(conf) == 4: c2.flags = conf[3] d2['material_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['material_'+conf['name']] = c2 return d2 def transform_solvers(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind','params']) for param, val in six.iteritems(c2.params): setattr(c2, param, val) delattr(c2, 'params') d2['solvers_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['solvers_'+c2.name] = c2 return d2 def transform_functions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['function']) d2['function_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['function_'+c2.name] = c2 return d2 def transform_to_struct_1(adict): return dict_to_struct(adict, flag=(1,)) def transform_to_i_struct_1(adict): return dict_to_struct(adict, flag=(1,), constructor=IndexedStruct) def transform_to_struct_01(adict): return dict_to_struct(adict, flag=(0,1)) def transform_to_struct_10(adict): return dict_to_struct(adict, flag=(1,0)) transforms = { 'options' : transform_to_i_struct_1, 'solvers' : transform_solvers, 'integrals' : transform_integrals, 'regions' : transform_regions, 'fields' : transform_fields, 'variables' : transform_variables, 'ebcs' : transform_ebcs, 'epbcs' : transform_epbcs, 'dgebcs' : transform_dgebcs, 'dgepbcs' : transform_dgepbcs, 'nbcs' : transform_to_struct_01, 'lcbcs' : transform_lcbcs, 'ics' : transform_ics, 'materials' : transform_materials, 'functions' : transform_functions, } def dict_from_string(string, allow_tuple=False, free_word=False): """ Parse `string` and return a dictionary that can be used to construct/override a ProblemConf instance. """ if string is None: return {} if isinstance(string, dict): return string parser = create_bnf(allow_tuple=allow_tuple, free_word=free_word) out = {} for r in parser.parseString(string, parseAll=True): out.update(r) return out def dict_from_options(options): """ Return a dictionary that can be used to construct/override a ProblemConf instance based on `options`. See ``--conf`` and ``--options`` options of the ``simple.py`` script. """ override = dict_from_string(options.conf) if options.app_options: if not 'options' in override: override['options'] = {} override_options = dict_from_string(options.app_options) override['options'].update(override_options) return override ## # 27.10.2005, c class ProblemConf(Struct): """ Problem configuration, corresponding to an input (problem description file). It validates the input using lists of required and other keywords that have to/can appear in the input. Default keyword lists can be obtained by sfepy.base.conf.get_standard_keywords(). ProblemConf instance is used to construct a Problem instance via Problem.from_conf(conf). """ @staticmethod def from_file(filename, required=None, other=None, verbose=True, define_args=None, override=None, setup=True): """ Loads the problem definition from a file. The filename can either contain plain definitions, or it can contain the define() function, in which case it will be called to return the input definitions. The job of the define() function is to return a dictionary of parameters. How the dictionary is constructed is not our business, but the usual way is to simply have a function define() along these lines in the input file:: def define(): options = { 'save_eig_vectors' : None, 'eigen_solver' : 'eigen1', } region_2 = { 'name' : 'Surface', 'select' : 'nodes of surface', } return locals() Optionally, the define() function can accept additional arguments that should be defined using the `define_args` tuple or dictionary. """ funmod = import_file(filename, package_name=False) if "define" in funmod.__dict__: if define_args is None: define_dict = funmod.__dict__["define"]() else: if isinstance(define_args, str): define_args = dict_from_string(define_args) if isinstance(define_args, dict): define_dict = funmod.__dict__["define"](**define_args) else: define_dict = funmod.__dict__["define"](*define_args) else: define_dict = funmod.__dict__ obj = ProblemConf(define_dict, funmod=funmod, filename=filename, required=required, other=other, verbose=verbose, override=override, setup=setup) return obj @staticmethod def from_file_and_options(filename, options, required=None, other=None, verbose=True, define_args=None, setup=True): """ Utility function, a wrapper around ProblemConf.from_file() with possible override taken from `options`. """ override = dict_from_options(options) obj = ProblemConf.from_file(filename, required=required, other=other, verbose=verbose, define_args=define_args, override=override, setup=setup) return obj @staticmethod def from_module(module, required=None, other=None, verbose=True, override=None, setup=True): obj = ProblemConf(module.__dict__, module, module.__name__, required, other, verbose, override, setup=setup) return obj @staticmethod def from_dict(dict_, funmod, required=None, other=None, verbose=True, override=None, setup=True): obj = ProblemConf(dict_, funmod, None, required, other, verbose, override, setup=setup) return obj def __init__(self, define_dict, funmod=None, filename=None, required=None, other=None, verbose=True, override=None, setup=True): if override: if isinstance(override, Struct): override = override.__dict__ define_dict = update_dict_recursively(define_dict, override, True) self.__dict__.update(define_dict) self.verbose = verbose if setup: self.setup(funmod=funmod, filename=filename, required=required, other=other) def setup(self, define_dict=None, funmod=None, filename=None, required=None, other=None): define_dict = get_default(define_dict, self.__dict__) self._filename = filename self.validate(required=required, other=other) self.transform_input_trivial() self._raw = {} for key, val in six.iteritems(define_dict): if isinstance(val, dict): self._raw[key] =
copy(val)
sfepy.base.base.copy
""" Problem description file handling. Notes ----- Short syntax: key is suffixed with '__<number>' to prevent collisions with long syntax keys -> both cases can be used in a single input. """ from __future__ import absolute_import import re import numpy as nm from sfepy.base.base import (Struct, IndexedStruct, dict_to_struct, output, copy, update_dict_recursively, import_file, assert_, get_default, basestr) from sfepy.base.parse_conf import create_bnf import six _required = ['filename_mesh|filename_domain', 'field_[0-9]+|fields', # TODO originaly EBC were required to be specified but in some examples # (especially 1D) only EPBCs specified is valid 'ebc_[0-9]+|ebcs|dgebc_[0-9]+|dgebcs|dgepbc_[0-9]+|dgepbcs', 'equations', 'region_[0-9]+|regions', 'variable_[0-9]+|variables', 'material_[0-9]+|materials', 'solver_[0-9]+|solvers'] _other = ['epbc_[0-9]+|epbcs', 'lcbc_[0-9]+|lcbcs', 'nbc_[0-9]+|nbcs', 'ic_[0-9]+|ics', 'function_[0-9]+|functions', 'options', 'integral_[0-9]+|integrals'] def get_standard_keywords(): return copy(_required), copy(_other) def tuple_to_conf(name, vals, order): """ Convert a configuration tuple `vals` into a Struct named `name`, with attribute names given in and ordered by `order`. Items in `order` at indices outside the length of `vals` are ignored. """ conf = Struct(name=name) for ii, key in enumerate(order[:len(vals)]): setattr(conf, key, vals[ii]) return conf def transform_variables(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['kind', 'field']) if len(conf) >= 3: kind = c2.kind.split()[0] if kind == 'unknown': c2.order = conf[2] elif kind == 'test': c2.dual = conf[2] elif kind == 'parameter': if isinstance(conf[2], basestr) or (conf[2] is None): c2.like = conf[2] else: c2.like = None c2.special = conf[2] if len(conf) == 4: c2.history = conf[3] d2['variable_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['variable_'+c2.name] = c2 return d2 def transform_conditions(adict, prefix): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 2: c2 = tuple_to_conf(key, conf, ['region', 'dofs']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgebcs(adict): return transform_conditions(adict, "dgebc") def transform_ebcs(adict): return transform_conditions(adict, 'ebc') def transform_ics(adict): return transform_conditions(adict, 'ic') def transform_lcbcs(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) >= 4: if isinstance(conf[1], dict): c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[4:] else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'dof_map_fun', 'kind']) c2.arguments = conf[5:] else: msg = 'LCBC syntax has to be: region[, times], dofs,' \ ' dof_map_fun, kind[, other arguments]' raise SyntaxError(msg) d2['lcbc_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) c2.set_default('dof_map_fun', None) c2.set_default('arguments', ()) d2['lcbc_%s' % (c2.name)] = c2 return d2 def transform_epbcs(adict, prefix="epbc"): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, tuple): if len(conf) == 3: c2 = tuple_to_conf(key, conf, ['region', 'dofs', 'match']) else: c2 = tuple_to_conf(key, conf, ['region', 'times', 'dofs', 'match']) d2['%s_%s__%d' % (prefix, c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['%s_%s' % (prefix, c2.name)] = c2 return d2 def transform_dgepbcs(adict): return transform_epbcs(adict, "dgepbc") def transform_regions(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, basestr): c2 = Struct(name=key, select=conf) d2['region_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): c2 = tuple_to_conf(key, conf, ['select', 'kind']) if len(conf) == 3: c2.parent = conf[2] if len(conf) == 4: c2.parent = conf[2] c2.extra_options = conf[3] d2['region_%s__%d' % (c2.name, ii)] = c2 else: c2 = transform_to_struct_1(conf) d2['region_'+c2.name] = c2 return d2 def transform_integrals(adict): d2 = {} for ii, (key, conf) in enumerate(six.iteritems(adict)): if isinstance(conf, int): c2 = Struct(name=key, order=conf) d2['integral_%s__%d' % (c2.name, ii)] = c2 elif isinstance(conf, tuple): if len(conf) == 2: # Old tuple version with now-ignored 'kind'. conf = conf[1] c2 =
Struct(name=key, order=conf)
sfepy.base.base.Struct
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock()
output(mtx_a, '.. analytical')
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical')
output(mtx_d, '.. difference')
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0
output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r))
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs):
NonlinearSolver.__init__(self, conf, **kwargs)
sfepy.solvers.solvers.NonlinearSolver.__init__
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log =
get_logging_conf(conf)
sfepy.base.log.get_logging_conf
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log =
Struct(name='log_conf', **log)
sfepy.base.base.Struct
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf =
get_default(conf, self.conf)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun =
get_default(fun, self.fun)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad =
get_default(fun_grad, self.fun_grad)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver =
get_default(lin_solver, self.lin_solver)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook =
get_default(iter_hook, self.iter_hook)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status =
get_default(status, self.status)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a =
get_default(ls_eps_a, 1.0)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r =
get_default(ls_eps_r, 1.0)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs):
NonlinearSolver.__init__(self, conf, **kwargs)
sfepy.solvers.solvers.NonlinearSolver.__init__
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) self.set_method(self.conf) def set_method(self, conf): import scipy.optimize as so try: solver = getattr(so, conf.method) except AttributeError: output('scipy solver %s does not exist!' % conf.method) output('using broyden3 instead') solver = so.broyden3 self.solver = solver def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): if conf is not None: self.set_method(conf) else: conf = self.conf fun =
get_default(fun, self.fun)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) self.set_method(self.conf) def set_method(self, conf): import scipy.optimize as so try: solver = getattr(so, conf.method) except AttributeError: output('scipy solver %s does not exist!' % conf.method) output('using broyden3 instead') solver = so.broyden3 self.solver = solver def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): if conf is not None: self.set_method(conf) else: conf = self.conf fun = get_default(fun, self.fun) status =
get_default(status, self.status)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) self.set_method(self.conf) def set_method(self, conf): import scipy.optimize as so try: solver = getattr(so, conf.method) except AttributeError: output('scipy solver %s does not exist!' % conf.method) output('using broyden3 instead') solver = so.broyden3 self.solver = solver def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): if conf is not None: self.set_method(conf) else: conf = self.conf fun = get_default(fun, self.fun) status = get_default(status, self.status) tt = time.clock() kwargs = {'iter' : conf.i_max, 'alpha' : conf.alpha, 'verbose' : conf.verbose} if conf.method == 'broyden_generalized': kwargs.update({'M' : conf.M}) elif conf.method in ['anderson', 'anderson2']: kwargs.update({'M' : conf.M, 'w0' : conf.w0}) if conf.method in ['anderson', 'anderson2', 'broyden', 'broyden2' , 'newton_krylov']: kwargs.update({'f_tol' : conf.f_tol }) vec_x = self.solver(fun, vec_x0, **kwargs) vec_x = nm.asarray(vec_x) if status is not None: status['time_stats'] = time.clock() - tt return vec_x class PETScNonlinearSolver(NonlinearSolver): """ Interface to PETSc SNES (Scalable Nonlinear Equations Solvers). The solver supports parallel use with a given MPI communicator (see `comm` argument of :func:`PETScNonlinearSolver.__init__()`). Returns a (global) PETSc solution vector instead of a (local) numpy array, when given a PETSc initial guess vector. For parallel use, the `fun` and `fun_grad` callbacks should be provided by :class:`PETScParallelEvaluator <sfepy.parallel.evaluate.PETScParallelEvaluator>`. """ name = 'nls.petsc' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'newtonls', False, 'The SNES type.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('if_max', 'int', 100, False, 'The maximum number of function evaluations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_s', 'float', 0.0, False, """The convergence tolerance in terms of the norm of the change in the solution between steps, i.e. $||delta x|| < \epsilon_s ||x||$"""), ] def __init__(self, conf, pmtx=None, prhs=None, comm=None, **kwargs): if comm is None: try: import petsc4py petsc4py.init([]) except ImportError: msg = 'cannot import petsc4py!' raise ImportError(msg) from petsc4py import PETSc as petsc NonlinearSolver.__init__(self, conf, petsc=petsc, pmtx=pmtx, prhs=prhs, comm=comm, **kwargs) def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None, pmtx=None, prhs=None, comm=None): conf = self.conf fun =
get_default(fun, self.fun)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) self.set_method(self.conf) def set_method(self, conf): import scipy.optimize as so try: solver = getattr(so, conf.method) except AttributeError: output('scipy solver %s does not exist!' % conf.method) output('using broyden3 instead') solver = so.broyden3 self.solver = solver def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): if conf is not None: self.set_method(conf) else: conf = self.conf fun = get_default(fun, self.fun) status = get_default(status, self.status) tt = time.clock() kwargs = {'iter' : conf.i_max, 'alpha' : conf.alpha, 'verbose' : conf.verbose} if conf.method == 'broyden_generalized': kwargs.update({'M' : conf.M}) elif conf.method in ['anderson', 'anderson2']: kwargs.update({'M' : conf.M, 'w0' : conf.w0}) if conf.method in ['anderson', 'anderson2', 'broyden', 'broyden2' , 'newton_krylov']: kwargs.update({'f_tol' : conf.f_tol }) vec_x = self.solver(fun, vec_x0, **kwargs) vec_x = nm.asarray(vec_x) if status is not None: status['time_stats'] = time.clock() - tt return vec_x class PETScNonlinearSolver(NonlinearSolver): """ Interface to PETSc SNES (Scalable Nonlinear Equations Solvers). The solver supports parallel use with a given MPI communicator (see `comm` argument of :func:`PETScNonlinearSolver.__init__()`). Returns a (global) PETSc solution vector instead of a (local) numpy array, when given a PETSc initial guess vector. For parallel use, the `fun` and `fun_grad` callbacks should be provided by :class:`PETScParallelEvaluator <sfepy.parallel.evaluate.PETScParallelEvaluator>`. """ name = 'nls.petsc' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'newtonls', False, 'The SNES type.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('if_max', 'int', 100, False, 'The maximum number of function evaluations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_s', 'float', 0.0, False, """The convergence tolerance in terms of the norm of the change in the solution between steps, i.e. $||delta x|| < \epsilon_s ||x||$"""), ] def __init__(self, conf, pmtx=None, prhs=None, comm=None, **kwargs): if comm is None: try: import petsc4py petsc4py.init([]) except ImportError: msg = 'cannot import petsc4py!' raise ImportError(msg) from petsc4py import PETSc as petsc NonlinearSolver.__init__(self, conf, petsc=petsc, pmtx=pmtx, prhs=prhs, comm=comm, **kwargs) def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None, pmtx=None, prhs=None, comm=None): conf = self.conf fun = get_default(fun, self.fun) fun_grad =
get_default(fun_grad, self.fun_grad)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) self.set_method(self.conf) def set_method(self, conf): import scipy.optimize as so try: solver = getattr(so, conf.method) except AttributeError: output('scipy solver %s does not exist!' % conf.method) output('using broyden3 instead') solver = so.broyden3 self.solver = solver def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): if conf is not None: self.set_method(conf) else: conf = self.conf fun = get_default(fun, self.fun) status = get_default(status, self.status) tt = time.clock() kwargs = {'iter' : conf.i_max, 'alpha' : conf.alpha, 'verbose' : conf.verbose} if conf.method == 'broyden_generalized': kwargs.update({'M' : conf.M}) elif conf.method in ['anderson', 'anderson2']: kwargs.update({'M' : conf.M, 'w0' : conf.w0}) if conf.method in ['anderson', 'anderson2', 'broyden', 'broyden2' , 'newton_krylov']: kwargs.update({'f_tol' : conf.f_tol }) vec_x = self.solver(fun, vec_x0, **kwargs) vec_x = nm.asarray(vec_x) if status is not None: status['time_stats'] = time.clock() - tt return vec_x class PETScNonlinearSolver(NonlinearSolver): """ Interface to PETSc SNES (Scalable Nonlinear Equations Solvers). The solver supports parallel use with a given MPI communicator (see `comm` argument of :func:`PETScNonlinearSolver.__init__()`). Returns a (global) PETSc solution vector instead of a (local) numpy array, when given a PETSc initial guess vector. For parallel use, the `fun` and `fun_grad` callbacks should be provided by :class:`PETScParallelEvaluator <sfepy.parallel.evaluate.PETScParallelEvaluator>`. """ name = 'nls.petsc' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'newtonls', False, 'The SNES type.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('if_max', 'int', 100, False, 'The maximum number of function evaluations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_s', 'float', 0.0, False, """The convergence tolerance in terms of the norm of the change in the solution between steps, i.e. $||delta x|| < \epsilon_s ||x||$"""), ] def __init__(self, conf, pmtx=None, prhs=None, comm=None, **kwargs): if comm is None: try: import petsc4py petsc4py.init([]) except ImportError: msg = 'cannot import petsc4py!' raise ImportError(msg) from petsc4py import PETSc as petsc NonlinearSolver.__init__(self, conf, petsc=petsc, pmtx=pmtx, prhs=prhs, comm=comm, **kwargs) def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None, pmtx=None, prhs=None, comm=None): conf = self.conf fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver =
get_default(lin_solver, self.lin_solver)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) self.set_method(self.conf) def set_method(self, conf): import scipy.optimize as so try: solver = getattr(so, conf.method) except AttributeError: output('scipy solver %s does not exist!' % conf.method) output('using broyden3 instead') solver = so.broyden3 self.solver = solver def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): if conf is not None: self.set_method(conf) else: conf = self.conf fun = get_default(fun, self.fun) status = get_default(status, self.status) tt = time.clock() kwargs = {'iter' : conf.i_max, 'alpha' : conf.alpha, 'verbose' : conf.verbose} if conf.method == 'broyden_generalized': kwargs.update({'M' : conf.M}) elif conf.method in ['anderson', 'anderson2']: kwargs.update({'M' : conf.M, 'w0' : conf.w0}) if conf.method in ['anderson', 'anderson2', 'broyden', 'broyden2' , 'newton_krylov']: kwargs.update({'f_tol' : conf.f_tol }) vec_x = self.solver(fun, vec_x0, **kwargs) vec_x = nm.asarray(vec_x) if status is not None: status['time_stats'] = time.clock() - tt return vec_x class PETScNonlinearSolver(NonlinearSolver): """ Interface to PETSc SNES (Scalable Nonlinear Equations Solvers). The solver supports parallel use with a given MPI communicator (see `comm` argument of :func:`PETScNonlinearSolver.__init__()`). Returns a (global) PETSc solution vector instead of a (local) numpy array, when given a PETSc initial guess vector. For parallel use, the `fun` and `fun_grad` callbacks should be provided by :class:`PETScParallelEvaluator <sfepy.parallel.evaluate.PETScParallelEvaluator>`. """ name = 'nls.petsc' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'newtonls', False, 'The SNES type.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('if_max', 'int', 100, False, 'The maximum number of function evaluations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_s', 'float', 0.0, False, """The convergence tolerance in terms of the norm of the change in the solution between steps, i.e. $||delta x|| < \epsilon_s ||x||$"""), ] def __init__(self, conf, pmtx=None, prhs=None, comm=None, **kwargs): if comm is None: try: import petsc4py petsc4py.init([]) except ImportError: msg = 'cannot import petsc4py!' raise ImportError(msg) from petsc4py import PETSc as petsc NonlinearSolver.__init__(self, conf, petsc=petsc, pmtx=pmtx, prhs=prhs, comm=comm, **kwargs) def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None, pmtx=None, prhs=None, comm=None): conf = self.conf fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook =
get_default(iter_hook, self.iter_hook)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) self.set_method(self.conf) def set_method(self, conf): import scipy.optimize as so try: solver = getattr(so, conf.method) except AttributeError: output('scipy solver %s does not exist!' % conf.method) output('using broyden3 instead') solver = so.broyden3 self.solver = solver def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): if conf is not None: self.set_method(conf) else: conf = self.conf fun = get_default(fun, self.fun) status = get_default(status, self.status) tt = time.clock() kwargs = {'iter' : conf.i_max, 'alpha' : conf.alpha, 'verbose' : conf.verbose} if conf.method == 'broyden_generalized': kwargs.update({'M' : conf.M}) elif conf.method in ['anderson', 'anderson2']: kwargs.update({'M' : conf.M, 'w0' : conf.w0}) if conf.method in ['anderson', 'anderson2', 'broyden', 'broyden2' , 'newton_krylov']: kwargs.update({'f_tol' : conf.f_tol }) vec_x = self.solver(fun, vec_x0, **kwargs) vec_x = nm.asarray(vec_x) if status is not None: status['time_stats'] = time.clock() - tt return vec_x class PETScNonlinearSolver(NonlinearSolver): """ Interface to PETSc SNES (Scalable Nonlinear Equations Solvers). The solver supports parallel use with a given MPI communicator (see `comm` argument of :func:`PETScNonlinearSolver.__init__()`). Returns a (global) PETSc solution vector instead of a (local) numpy array, when given a PETSc initial guess vector. For parallel use, the `fun` and `fun_grad` callbacks should be provided by :class:`PETScParallelEvaluator <sfepy.parallel.evaluate.PETScParallelEvaluator>`. """ name = 'nls.petsc' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'newtonls', False, 'The SNES type.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('if_max', 'int', 100, False, 'The maximum number of function evaluations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_s', 'float', 0.0, False, """The convergence tolerance in terms of the norm of the change in the solution between steps, i.e. $||delta x|| < \epsilon_s ||x||$"""), ] def __init__(self, conf, pmtx=None, prhs=None, comm=None, **kwargs): if comm is None: try: import petsc4py petsc4py.init([]) except ImportError: msg = 'cannot import petsc4py!' raise ImportError(msg) from petsc4py import PETSc as petsc NonlinearSolver.__init__(self, conf, petsc=petsc, pmtx=pmtx, prhs=prhs, comm=comm, **kwargs) def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None, pmtx=None, prhs=None, comm=None): conf = self.conf fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status =
get_default(status, self.status)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) self.set_method(self.conf) def set_method(self, conf): import scipy.optimize as so try: solver = getattr(so, conf.method) except AttributeError: output('scipy solver %s does not exist!' % conf.method) output('using broyden3 instead') solver = so.broyden3 self.solver = solver def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): if conf is not None: self.set_method(conf) else: conf = self.conf fun = get_default(fun, self.fun) status = get_default(status, self.status) tt = time.clock() kwargs = {'iter' : conf.i_max, 'alpha' : conf.alpha, 'verbose' : conf.verbose} if conf.method == 'broyden_generalized': kwargs.update({'M' : conf.M}) elif conf.method in ['anderson', 'anderson2']: kwargs.update({'M' : conf.M, 'w0' : conf.w0}) if conf.method in ['anderson', 'anderson2', 'broyden', 'broyden2' , 'newton_krylov']: kwargs.update({'f_tol' : conf.f_tol }) vec_x = self.solver(fun, vec_x0, **kwargs) vec_x = nm.asarray(vec_x) if status is not None: status['time_stats'] = time.clock() - tt return vec_x class PETScNonlinearSolver(NonlinearSolver): """ Interface to PETSc SNES (Scalable Nonlinear Equations Solvers). The solver supports parallel use with a given MPI communicator (see `comm` argument of :func:`PETScNonlinearSolver.__init__()`). Returns a (global) PETSc solution vector instead of a (local) numpy array, when given a PETSc initial guess vector. For parallel use, the `fun` and `fun_grad` callbacks should be provided by :class:`PETScParallelEvaluator <sfepy.parallel.evaluate.PETScParallelEvaluator>`. """ name = 'nls.petsc' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'newtonls', False, 'The SNES type.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('if_max', 'int', 100, False, 'The maximum number of function evaluations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_s', 'float', 0.0, False, """The convergence tolerance in terms of the norm of the change in the solution between steps, i.e. $||delta x|| < \epsilon_s ||x||$"""), ] def __init__(self, conf, pmtx=None, prhs=None, comm=None, **kwargs): if comm is None: try: import petsc4py petsc4py.init([]) except ImportError: msg = 'cannot import petsc4py!' raise ImportError(msg) from petsc4py import PETSc as petsc NonlinearSolver.__init__(self, conf, petsc=petsc, pmtx=pmtx, prhs=prhs, comm=comm, **kwargs) def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None, pmtx=None, prhs=None, comm=None): conf = self.conf fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) pmtx =
get_default(pmtx, self.pmtx)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) self.set_method(self.conf) def set_method(self, conf): import scipy.optimize as so try: solver = getattr(so, conf.method) except AttributeError: output('scipy solver %s does not exist!' % conf.method) output('using broyden3 instead') solver = so.broyden3 self.solver = solver def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): if conf is not None: self.set_method(conf) else: conf = self.conf fun = get_default(fun, self.fun) status = get_default(status, self.status) tt = time.clock() kwargs = {'iter' : conf.i_max, 'alpha' : conf.alpha, 'verbose' : conf.verbose} if conf.method == 'broyden_generalized': kwargs.update({'M' : conf.M}) elif conf.method in ['anderson', 'anderson2']: kwargs.update({'M' : conf.M, 'w0' : conf.w0}) if conf.method in ['anderson', 'anderson2', 'broyden', 'broyden2' , 'newton_krylov']: kwargs.update({'f_tol' : conf.f_tol }) vec_x = self.solver(fun, vec_x0, **kwargs) vec_x = nm.asarray(vec_x) if status is not None: status['time_stats'] = time.clock() - tt return vec_x class PETScNonlinearSolver(NonlinearSolver): """ Interface to PETSc SNES (Scalable Nonlinear Equations Solvers). The solver supports parallel use with a given MPI communicator (see `comm` argument of :func:`PETScNonlinearSolver.__init__()`). Returns a (global) PETSc solution vector instead of a (local) numpy array, when given a PETSc initial guess vector. For parallel use, the `fun` and `fun_grad` callbacks should be provided by :class:`PETScParallelEvaluator <sfepy.parallel.evaluate.PETScParallelEvaluator>`. """ name = 'nls.petsc' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'newtonls', False, 'The SNES type.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('if_max', 'int', 100, False, 'The maximum number of function evaluations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_s', 'float', 0.0, False, """The convergence tolerance in terms of the norm of the change in the solution between steps, i.e. $||delta x|| < \epsilon_s ||x||$"""), ] def __init__(self, conf, pmtx=None, prhs=None, comm=None, **kwargs): if comm is None: try: import petsc4py petsc4py.init([]) except ImportError: msg = 'cannot import petsc4py!' raise ImportError(msg) from petsc4py import PETSc as petsc NonlinearSolver.__init__(self, conf, petsc=petsc, pmtx=pmtx, prhs=prhs, comm=comm, **kwargs) def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None, pmtx=None, prhs=None, comm=None): conf = self.conf fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) pmtx = get_default(pmtx, self.pmtx) prhs =
get_default(prhs, self.prhs)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) self.set_method(self.conf) def set_method(self, conf): import scipy.optimize as so try: solver = getattr(so, conf.method) except AttributeError: output('scipy solver %s does not exist!' % conf.method) output('using broyden3 instead') solver = so.broyden3 self.solver = solver def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): if conf is not None: self.set_method(conf) else: conf = self.conf fun = get_default(fun, self.fun) status = get_default(status, self.status) tt = time.clock() kwargs = {'iter' : conf.i_max, 'alpha' : conf.alpha, 'verbose' : conf.verbose} if conf.method == 'broyden_generalized': kwargs.update({'M' : conf.M}) elif conf.method in ['anderson', 'anderson2']: kwargs.update({'M' : conf.M, 'w0' : conf.w0}) if conf.method in ['anderson', 'anderson2', 'broyden', 'broyden2' , 'newton_krylov']: kwargs.update({'f_tol' : conf.f_tol }) vec_x = self.solver(fun, vec_x0, **kwargs) vec_x = nm.asarray(vec_x) if status is not None: status['time_stats'] = time.clock() - tt return vec_x class PETScNonlinearSolver(NonlinearSolver): """ Interface to PETSc SNES (Scalable Nonlinear Equations Solvers). The solver supports parallel use with a given MPI communicator (see `comm` argument of :func:`PETScNonlinearSolver.__init__()`). Returns a (global) PETSc solution vector instead of a (local) numpy array, when given a PETSc initial guess vector. For parallel use, the `fun` and `fun_grad` callbacks should be provided by :class:`PETScParallelEvaluator <sfepy.parallel.evaluate.PETScParallelEvaluator>`. """ name = 'nls.petsc' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'newtonls', False, 'The SNES type.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('if_max', 'int', 100, False, 'The maximum number of function evaluations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_s', 'float', 0.0, False, """The convergence tolerance in terms of the norm of the change in the solution between steps, i.e. $||delta x|| < \epsilon_s ||x||$"""), ] def __init__(self, conf, pmtx=None, prhs=None, comm=None, **kwargs): if comm is None: try: import petsc4py petsc4py.init([]) except ImportError: msg = 'cannot import petsc4py!' raise ImportError(msg) from petsc4py import PETSc as petsc NonlinearSolver.__init__(self, conf, petsc=petsc, pmtx=pmtx, prhs=prhs, comm=comm, **kwargs) def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None, pmtx=None, prhs=None, comm=None): conf = self.conf fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) pmtx = get_default(pmtx, self.pmtx) prhs = get_default(prhs, self.prhs) comm =
get_default(comm, self.comm)
sfepy.base.base.get_default
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose:
output('solving linear system...')
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose:
output('...done')
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems():
output('%10s: %7.2f [s]' % kv)
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red:
output('warning: linear system solution precision is lower')
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) self.set_method(self.conf) def set_method(self, conf): import scipy.optimize as so try: solver = getattr(so, conf.method) except AttributeError:
output('scipy solver %s does not exist!' % conf.method)
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min: output('linesearch failed, continuing anyway') break ls *= red; vec_dx = ls * vec_dx0; vec_x = vec_x_last.copy() - vec_dx # End residual loop. if self.log is not None: self.log.plot_vlines([1], color='g', linewidth=0.5) err_last = err; vec_x_last = vec_x.copy() condition = conv_test(conf, it, err, err0) if condition >= 0: break if (not ok) and conf.give_up_warp: condition = 2 break tt = time.clock() if not conf.is_linear: mtx_a = fun_grad(vec_x) else: mtx_a = fun_grad('linear') time_stats['matrix'] = time.clock() - tt if conf.check: tt = time.clock() wt = check_tangent_matrix(conf, vec_x, fun, fun_grad) time_stats['check'] = time.clock() - tt - wt if conf.lin_precision is not None: if ls_eps_a is not None: eps_a = max(err * conf.lin_precision, ls_eps_a) elif ls_eps_r is not None: eps_r = max(conf.lin_precision, ls_eps_r) lin_red = max(eps_a, err * eps_r) if conf.verbose: output('solving linear system...') tt = time.clock() vec_dx = lin_solver(vec_r, x0=vec_x, eps_a=eps_a, eps_r=eps_r, mtx=mtx_a) time_stats['solve'] = time.clock() - tt if conf.verbose: output('...done') for kv in time_stats.iteritems(): output('%10s: %7.2f [s]' % kv) vec_e = mtx_a * vec_dx - vec_r lerr = nla.norm(vec_e) if lerr > lin_red: output('warning: linear system solution precision is lower') output('then the value set in solver options! (err = %e < %e)' % (lerr, lin_red)) vec_x -= vec_dx it += 1 if status is not None: status['time_stats'] = time_stats status['err0'] = err0 status['err'] = err status['n_iter'] = it status['condition'] = condition if conf.log.plot is not None: if self.log is not None: self.log(save_figure=conf.log.plot) return vec_x class ScipyBroyden(NonlinearSolver): """ Interface to Broyden and Anderson solvers from ``scipy.optimize``. """ name = 'nls.scipy_broyden_like' __metaclass__ = SolverMeta _parameters = [ ('method', 'str', 'anderson', False, 'The name of the solver in ``scipy.optimize``.'), ('i_max', 'int', 10, False, 'The maximum number of iterations.'), ('alpha', 'float', 0.9, False, 'See ``scipy.optimize``.'), ('M', 'float', 5, False, 'See ``scipy.optimize``.'), ('f_tol', 'float', 1e-6, False, 'See ``scipy.optimize``.'), ('w0', 'float', 0.1, False, 'See ``scipy.optimize``.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) self.set_method(self.conf) def set_method(self, conf): import scipy.optimize as so try: solver = getattr(so, conf.method) except AttributeError: output('scipy solver %s does not exist!' % conf.method)
output('using broyden3 instead')
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp: output('giving up!') break red = conf.ls_red_warp; output('rezidual computation failed for iter %d' ' (new ls: %e)!' % (it, red * ls)) if ls < conf.ls_min:
output('linesearch failed, continuing anyway')
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all()) debug() if self.log is not None: self.log(err, it) if it == 0: err0 = err; break if err < (err_last * conf.ls_on): break red = conf.ls_red; output('linesearch: iter %d, (%.5e < %.5e) (new ls: %e)' % (it, err, err_last * conf.ls_on, red * ls)) else: # Failure. if conf.give_up_warp:
output('giving up!')
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min):
output('giving up!')
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except:
output('infs or nans in the residual:', vec_r)
sfepy.base.base.output
""" Nonlinear solvers. """ import time import numpy as nm import numpy.linalg as nla from sfepy.base.base import output, get_default, debug, Struct from sfepy.base.log import Log, get_logging_conf from sfepy.solvers.solvers import SolverMeta, NonlinearSolver def check_tangent_matrix(conf, vec_x0, fun, fun_grad): """ Verify the correctness of the tangent matrix as computed by `fun_grad()` by comparing it with its finite difference approximation evaluated by repeatedly calling `fun()` with `vec_x0` items perturbed by a small delta. """ vec_x = vec_x0.copy() delta = conf.delta vec_r = fun(vec_x) # Update state. mtx_a0 = fun_grad(vec_x) mtx_a = mtx_a0.tocsc() mtx_d = mtx_a.copy() mtx_d.data[:] = 0.0 vec_dx = nm.zeros_like(vec_r) for ic in range(vec_dx.shape[0]): vec_dx[ic] = delta xx = vec_x.copy() - vec_dx vec_r1 = fun(xx) vec_dx[ic] = -delta xx = vec_x.copy() - vec_dx vec_r2 = fun(xx) vec_dx[ic] = 0.0; vec = 0.5 * (vec_r2 - vec_r1) / delta ir = mtx_a.indices[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] mtx_d.data[mtx_a.indptr[ic]:mtx_a.indptr[ic+1]] = vec[ir] vec_r = fun(vec_x) # Restore. tt = time.clock() output(mtx_a, '.. analytical') output(mtx_d, '.. difference') import sfepy.base.plotutils as plu plu.plot_matrix_diff(mtx_d, mtx_a, delta, ['difference', 'analytical'], conf.check) return time.clock() - tt def conv_test(conf, it, err, err0): """ Nonlinear solver convergence test. Parameters ---------- conf : Struct instance The nonlinear solver configuration. it : int The current iteration. err : float The current iteration error. err0 : float The initial error. Returns ------- status : int The convergence status: -1 = no convergence (yet), 0 = solver converged - tolerances were met, 1 = max. number of iterations reached. """ status = -1 if (abs(err0) < conf.macheps): err_r = 0.0 else: err_r = err / err0 output('nls: iter: %d, residual: %e (rel: %e)' % (it, err, err_r)) conv_a = err < conf.eps_a if it > 0: conv_r = err_r < conf.eps_r if conv_a and conv_r: status = 0 elif (conf.get('eps_mode', '') == 'or') and (conv_a or conv_r): status = 0 else: if conv_a: status = 0 if (status == -1) and (it >= conf.i_max): status = 1 return status class Newton(NonlinearSolver): r""" Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. """ name = 'nls.newton' __metaclass__ = SolverMeta _parameters = [ ('i_max', 'int', 1, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-10, False, 'The absolute tolerance for the residual, i.e. :math:`||f(x^i)||`.'), ('eps_r', 'float', 1.0, False, """The relative tolerance for the residual, i.e. :math:`||f(x^i)|| / ||f(x^0)||`."""), ('eps_mode', "'and' or 'or'", 'and', False, """The logical operator to use for combining the absolute and relative tolerances."""), ('macheps', 'float', nm.finfo(nm.float64).eps, False, 'The float considered to be machine "zero".'), ('lin_red', 'float', 1.0, False, """The linear system solution error should be smaller than (`eps_a` * `lin_red`), otherwise a warning is printed."""), ('lin_precision', 'float or None', None, False, """If not None, the linear system solution tolerances are set in each nonlinear iteration relative to the current residual norm by the `lin_precision` factor. Ignored for direct linear solvers."""), ('ls_on', 'float', 0.99999, False, """Start the backtracking line-search by reducing the step, if :math:`||f(x^i)|| / ||f(x^{i-1})||` is larger than `ls_on`."""), ('ls_red', '0.0 < float < 1.0', 0.1, False, 'The step reduction factor in case of correct residual assembling.'), ('ls_red_warp', '0.0 < float < 1.0', 0.001, False, """The step reduction factor in case of failed residual assembling (e.g. the "warp violation" error caused by a negative volume element resulting from too large deformations)."""), ('ls_min', '0.0 < float < 1.0', 1e-5, False, 'The minimum step reduction factor.'), ('give_up_warp', 'bool', False, False, 'If True, abort on the "warp violation" error.'), ('check', '0, 1 or 2', 0, False, """If >= 1, check the tangent matrix using finite differences. If 2, plot the resulting sparsity patterns."""), ('delta', 'float', 1e-6, False, r"""If `check >= 1`, the finite difference matrix is taken as :math:`A_{ij} = \frac{f_i(x_j + \delta) - f_i(x_j - \delta)}{2 \delta}`."""), ('log', 'dict or None', None, False, """If not None, log the convergence according to the configuration in the following form: ``{'text' : 'log.txt', 'plot' : 'log.pdf'}``. Each of the dict items can be None."""), ('is_linear', 'bool', False, False, 'If True, the problem is considered to be linear.'), ] def __init__(self, conf, **kwargs): NonlinearSolver.__init__(self, conf, **kwargs) conf = self.conf log = get_logging_conf(conf) conf.log = log = Struct(name='log_conf', **log) conf.is_any_log = (log.text is not None) or (log.plot is not None) if conf.is_any_log: self.log = Log([[r'$||r||$'], ['iteration']], xlabels=['', 'all iterations'], ylabels=[r'$||r||$', 'iteration'], yscales=['log', 'linear'], is_plot=conf.log.plot is not None, log_filename=conf.log.text, formats=[['%.8e'], ['%d']]) else: self.log = None def __call__(self, vec_x0, conf=None, fun=None, fun_grad=None, lin_solver=None, iter_hook=None, status=None): """ Nonlinear system solver call. Solves a nonlinear system :math:`f(x) = 0` using the Newton method with backtracking line-search, starting with an initial guess :math:`x^0`. Parameters ---------- vec_x0 : array The initial guess vector :math:`x_0`. conf : Struct instance, optional The solver configuration parameters, fun : function, optional The function :math:`f(x)` whose zero is sought - the residual. fun_grad : function, optional The gradient of :math:`f(x)` - the tangent matrix. lin_solver : LinearSolver instance, optional The linear solver for each nonlinear iteration. iter_hook : function, optional User-supplied function to call before each iteration. status : dict-like, optional The user-supplied object to hold convergence statistics. Notes ----- * The optional parameters except `iter_hook` and `status` need to be given either here or upon `Newton` construction. * Setting `conf.is_linear == True` means a pre-assembled and possibly pre-solved matrix. This is mostly useful for linear time-dependent problems. """ conf = get_default(conf, self.conf) fun = get_default(fun, self.fun) fun_grad = get_default(fun_grad, self.fun_grad) lin_solver = get_default(lin_solver, self.lin_solver) iter_hook = get_default(iter_hook, self.iter_hook) status = get_default(status, self.status) ls_eps_a, ls_eps_r = lin_solver.get_tolerance() eps_a = get_default(ls_eps_a, 1.0) eps_r = get_default(ls_eps_r, 1.0) lin_red = conf.eps_a * conf.lin_red time_stats = {} vec_x = vec_x0.copy() vec_x_last = vec_x0.copy() vec_dx = None if self.log is not None: self.log.plot_vlines(color='r', linewidth=1.0) err = err0 = -1.0 err_last = -1.0 it = 0 while 1: if iter_hook is not None: iter_hook(self, vec_x, it, err, err0) ls = 1.0 vec_dx0 = vec_dx; while 1: tt = time.clock() try: vec_r = fun(vec_x) except ValueError: if (it == 0) or (ls < conf.ls_min): output('giving up!') raise else: ok = False else: ok = True time_stats['rezidual'] = time.clock() - tt if ok: try: err = nla.norm(vec_r) except: output('infs or nans in the residual:', vec_r) output(nm.isfinite(vec_r).all())
debug()
sfepy.base.base.debug
from __future__ import absolute_import from sfepy import data_dir import six filename_mesh = data_dir + '/meshes/3d/special/cube_cylinder.mesh' if 0: from sfepy.discrete.fem.utils import refine_mesh refinement_level = 1 filename_mesh =
refine_mesh(filename_mesh, refinement_level)
sfepy.discrete.fem.utils.refine_mesh
from __future__ import absolute_import from sfepy import data_dir import six filename_mesh = data_dir + '/meshes/3d/special/cube_cylinder.mesh' if 0: from sfepy.discrete.fem.utils import refine_mesh refinement_level = 1 filename_mesh = refine_mesh(filename_mesh, refinement_level) material_2 = { 'name' : 'coef', 'values' : {'val' : 1.0}, } field_1 = { 'name' : 'temperature', 'dtype' : 'real', 'shape' : (1,), 'region' : 'Omega', 'approx_order' : 1, } variables = { 't' : ('unknown field', 'temperature', 0), 's' : ('test field', 'temperature', 't'), } regions = { 'Omega' : 'all', 'Gamma_Left' : ('vertices in (x < 0.0001)', 'facet'), 'Gamma_Right' : ('vertices in (x > 0.999)', 'facet'), } ebcs = { 't1' : ('Gamma_Left', {'t.0' : 2.0}), 't2' : ('Gamma_Right', {'t.0' : -2.0}), } integral_1 = { 'name' : 'i', 'order' : 1, } equations = { 'Temperature' : """dw_laplace.i.Omega(coef.val, s, t) = 0""" } class DiagPC(object): """ Diagonal (Jacobi) preconditioner. Equivalent to setting `'precond' : 'jacobi'`. """ def setUp(self, pc): A = pc.getOperators()[0] self.idiag = 1.0 / A.getDiagonal() def apply(self, pc, x, y): y.pointwiseMult(x, self.idiag) def setup_petsc_precond(mtx, problem): return DiagPC() solvers = { 'd00' : ('ls.scipy_direct', {'method' : 'umfpack', 'warn' : True,} ), 'd01' : ('ls.scipy_direct', {'method' : 'superlu', 'warn' : True,} ), 'd10' : ('ls.mumps', {}), 'i00' : ('ls.pyamg', {'method' : 'ruge_stuben_solver', 'accel' : 'cg', 'eps_r' : 1e-12, 'method:max_levels' : 5, 'solve:cycle' : 'V',} ), 'i01' : ('ls.pyamg', {'method' : 'smoothed_aggregation_solver', 'accel' : 'cg', 'eps_r' : 1e-12,} ), 'i02' : ('ls.pyamg_krylov', {'method' : 'cg', 'eps_r' : 1e-12, 'i_max' : 1000,} ), 'i10' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'none', # pc_type 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i11' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'python', # just for output (unused) 'setup_precond' : setup_petsc_precond, # user-defined pc 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i12' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'jacobi', # pc_type 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i13' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'icc', # pc_type 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i20' : ('ls.scipy_iterative', {'method' : 'cg', 'i_max' : 1000, 'eps_r' : 1e-12,} ), 'i21' : ('ls.scipy_iterative', {'method' : 'bicgstab', 'i_max' : 1000, 'eps_r' : 1e-12,} ), 'i22' : ('ls.scipy_iterative', {'method' : 'qmr', 'i_max' : 1000, 'eps_r' : 1e-12,} ), 'newton' : ('nls.newton', { 'i_max' : 1, 'eps_a' : 1e-10, }), } options = { 'nls' : 'newton', } from sfepy.base.testing import TestCommon output_name = 'test_linear_solvers_%s.vtk' class Test(TestCommon): can_fail = ['ls.pyamg', 'ls.pyamg_krylov', 'ls.petsc', 'ls.mumps',] @staticmethod def from_conf(conf, options): from sfepy.discrete import Problem problem =
Problem.from_conf(conf)
sfepy.discrete.Problem.from_conf
from __future__ import absolute_import from sfepy import data_dir import six filename_mesh = data_dir + '/meshes/3d/special/cube_cylinder.mesh' if 0: from sfepy.discrete.fem.utils import refine_mesh refinement_level = 1 filename_mesh = refine_mesh(filename_mesh, refinement_level) material_2 = { 'name' : 'coef', 'values' : {'val' : 1.0}, } field_1 = { 'name' : 'temperature', 'dtype' : 'real', 'shape' : (1,), 'region' : 'Omega', 'approx_order' : 1, } variables = { 't' : ('unknown field', 'temperature', 0), 's' : ('test field', 'temperature', 't'), } regions = { 'Omega' : 'all', 'Gamma_Left' : ('vertices in (x < 0.0001)', 'facet'), 'Gamma_Right' : ('vertices in (x > 0.999)', 'facet'), } ebcs = { 't1' : ('Gamma_Left', {'t.0' : 2.0}), 't2' : ('Gamma_Right', {'t.0' : -2.0}), } integral_1 = { 'name' : 'i', 'order' : 1, } equations = { 'Temperature' : """dw_laplace.i.Omega(coef.val, s, t) = 0""" } class DiagPC(object): """ Diagonal (Jacobi) preconditioner. Equivalent to setting `'precond' : 'jacobi'`. """ def setUp(self, pc): A = pc.getOperators()[0] self.idiag = 1.0 / A.getDiagonal() def apply(self, pc, x, y): y.pointwiseMult(x, self.idiag) def setup_petsc_precond(mtx, problem): return DiagPC() solvers = { 'd00' : ('ls.scipy_direct', {'method' : 'umfpack', 'warn' : True,} ), 'd01' : ('ls.scipy_direct', {'method' : 'superlu', 'warn' : True,} ), 'd10' : ('ls.mumps', {}), 'i00' : ('ls.pyamg', {'method' : 'ruge_stuben_solver', 'accel' : 'cg', 'eps_r' : 1e-12, 'method:max_levels' : 5, 'solve:cycle' : 'V',} ), 'i01' : ('ls.pyamg', {'method' : 'smoothed_aggregation_solver', 'accel' : 'cg', 'eps_r' : 1e-12,} ), 'i02' : ('ls.pyamg_krylov', {'method' : 'cg', 'eps_r' : 1e-12, 'i_max' : 1000,} ), 'i10' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'none', # pc_type 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i11' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'python', # just for output (unused) 'setup_precond' : setup_petsc_precond, # user-defined pc 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i12' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'jacobi', # pc_type 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i13' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'icc', # pc_type 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i20' : ('ls.scipy_iterative', {'method' : 'cg', 'i_max' : 1000, 'eps_r' : 1e-12,} ), 'i21' : ('ls.scipy_iterative', {'method' : 'bicgstab', 'i_max' : 1000, 'eps_r' : 1e-12,} ), 'i22' : ('ls.scipy_iterative', {'method' : 'qmr', 'i_max' : 1000, 'eps_r' : 1e-12,} ), 'newton' : ('nls.newton', { 'i_max' : 1, 'eps_a' : 1e-10, }), } options = { 'nls' : 'newton', } from sfepy.base.testing import TestCommon output_name = 'test_linear_solvers_%s.vtk' class Test(TestCommon): can_fail = ['ls.pyamg', 'ls.pyamg_krylov', 'ls.petsc', 'ls.mumps',] @staticmethod def from_conf(conf, options): from sfepy.discrete import Problem problem = Problem.from_conf(conf) problem.time_update() test = Test(problem=problem, conf=conf, options=options) return test def _list_linear_solvers(self, confs): d = [] for key, val in six.iteritems(confs): if val.kind.find('ls.') == 0: d.append(val) d.sort(key=lambda a: a.name) return d def test_solvers(self): from sfepy.base.base import IndexedStruct import os.path as op solver_confs = self._list_linear_solvers(self.problem.solver_confs) ok = True tt = [] for solver_conf in solver_confs: method = solver_conf.get('method', '') precond = solver_conf.get('precond', '') name = ' '.join((solver_conf.name, solver_conf.kind, method, precond)).rstrip() self.report(name) self.report('matrix size:', self.problem.mtx_a.shape) self.report(' nnz:', self.problem.mtx_a.nnz) status = IndexedStruct() try: self.problem.init_solvers(status=status, ls_conf=solver_conf, force=True) state = self.problem.solve() failed = status.nls_status.condition != 0 except Exception as aux: failed = True status = None exc = aux ok = ok and ((not failed) or (solver_conf.kind in self.can_fail)) if status is not None: status = status.nls_status for kv in six.iteritems(status.time_stats): self.report('%10s: %7.2f [s]' % kv) self.report('condition: %d, err0: %.3e, err: %.3e' % (status.condition, status.err0, status.err)) tt.append([name, status.time_stats['solve'], status.ls_n_iter, status.err]) aux = name.replace(' ', '_') fname = op.join(self.options.out_dir, op.split(self.conf.output_name)[1]) % aux self.problem.save_state(fname, state) else: self.report('solver failed:') self.report(exc) tt.append([name, -1, 1e10, 1e10]) tt.sort(key=lambda a: a[1]) self.report('solution times / numbers of iterations (residual norms):') for row in tt: self.report('%.2f [s] / % 4d' % (row[1], row[2]), '(%.3e)' % row[3], ':', row[0]) return ok def test_ls_reuse(self): import numpy as nm from sfepy.solvers import Solver from sfepy.discrete.state import State self.problem.init_solvers(ls_conf=self.problem.solver_confs['d00']) nls = self.problem.get_nls() state0 =
State(self.problem.equations.variables)
sfepy.discrete.state.State
from __future__ import absolute_import from sfepy import data_dir import six filename_mesh = data_dir + '/meshes/3d/special/cube_cylinder.mesh' if 0: from sfepy.discrete.fem.utils import refine_mesh refinement_level = 1 filename_mesh = refine_mesh(filename_mesh, refinement_level) material_2 = { 'name' : 'coef', 'values' : {'val' : 1.0}, } field_1 = { 'name' : 'temperature', 'dtype' : 'real', 'shape' : (1,), 'region' : 'Omega', 'approx_order' : 1, } variables = { 't' : ('unknown field', 'temperature', 0), 's' : ('test field', 'temperature', 't'), } regions = { 'Omega' : 'all', 'Gamma_Left' : ('vertices in (x < 0.0001)', 'facet'), 'Gamma_Right' : ('vertices in (x > 0.999)', 'facet'), } ebcs = { 't1' : ('Gamma_Left', {'t.0' : 2.0}), 't2' : ('Gamma_Right', {'t.0' : -2.0}), } integral_1 = { 'name' : 'i', 'order' : 1, } equations = { 'Temperature' : """dw_laplace.i.Omega(coef.val, s, t) = 0""" } class DiagPC(object): """ Diagonal (Jacobi) preconditioner. Equivalent to setting `'precond' : 'jacobi'`. """ def setUp(self, pc): A = pc.getOperators()[0] self.idiag = 1.0 / A.getDiagonal() def apply(self, pc, x, y): y.pointwiseMult(x, self.idiag) def setup_petsc_precond(mtx, problem): return DiagPC() solvers = { 'd00' : ('ls.scipy_direct', {'method' : 'umfpack', 'warn' : True,} ), 'd01' : ('ls.scipy_direct', {'method' : 'superlu', 'warn' : True,} ), 'd10' : ('ls.mumps', {}), 'i00' : ('ls.pyamg', {'method' : 'ruge_stuben_solver', 'accel' : 'cg', 'eps_r' : 1e-12, 'method:max_levels' : 5, 'solve:cycle' : 'V',} ), 'i01' : ('ls.pyamg', {'method' : 'smoothed_aggregation_solver', 'accel' : 'cg', 'eps_r' : 1e-12,} ), 'i02' : ('ls.pyamg_krylov', {'method' : 'cg', 'eps_r' : 1e-12, 'i_max' : 1000,} ), 'i10' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'none', # pc_type 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i11' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'python', # just for output (unused) 'setup_precond' : setup_petsc_precond, # user-defined pc 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i12' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'jacobi', # pc_type 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i13' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'icc', # pc_type 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i20' : ('ls.scipy_iterative', {'method' : 'cg', 'i_max' : 1000, 'eps_r' : 1e-12,} ), 'i21' : ('ls.scipy_iterative', {'method' : 'bicgstab', 'i_max' : 1000, 'eps_r' : 1e-12,} ), 'i22' : ('ls.scipy_iterative', {'method' : 'qmr', 'i_max' : 1000, 'eps_r' : 1e-12,} ), 'newton' : ('nls.newton', { 'i_max' : 1, 'eps_a' : 1e-10, }), } options = { 'nls' : 'newton', } from sfepy.base.testing import TestCommon output_name = 'test_linear_solvers_%s.vtk' class Test(TestCommon): can_fail = ['ls.pyamg', 'ls.pyamg_krylov', 'ls.petsc', 'ls.mumps',] @staticmethod def from_conf(conf, options): from sfepy.discrete import Problem problem = Problem.from_conf(conf) problem.time_update() test = Test(problem=problem, conf=conf, options=options) return test def _list_linear_solvers(self, confs): d = [] for key, val in six.iteritems(confs): if val.kind.find('ls.') == 0: d.append(val) d.sort(key=lambda a: a.name) return d def test_solvers(self): from sfepy.base.base import IndexedStruct import os.path as op solver_confs = self._list_linear_solvers(self.problem.solver_confs) ok = True tt = [] for solver_conf in solver_confs: method = solver_conf.get('method', '') precond = solver_conf.get('precond', '') name = ' '.join((solver_conf.name, solver_conf.kind, method, precond)).rstrip() self.report(name) self.report('matrix size:', self.problem.mtx_a.shape) self.report(' nnz:', self.problem.mtx_a.nnz) status =
IndexedStruct()
sfepy.base.base.IndexedStruct
from __future__ import absolute_import from sfepy import data_dir import six filename_mesh = data_dir + '/meshes/3d/special/cube_cylinder.mesh' if 0: from sfepy.discrete.fem.utils import refine_mesh refinement_level = 1 filename_mesh = refine_mesh(filename_mesh, refinement_level) material_2 = { 'name' : 'coef', 'values' : {'val' : 1.0}, } field_1 = { 'name' : 'temperature', 'dtype' : 'real', 'shape' : (1,), 'region' : 'Omega', 'approx_order' : 1, } variables = { 't' : ('unknown field', 'temperature', 0), 's' : ('test field', 'temperature', 't'), } regions = { 'Omega' : 'all', 'Gamma_Left' : ('vertices in (x < 0.0001)', 'facet'), 'Gamma_Right' : ('vertices in (x > 0.999)', 'facet'), } ebcs = { 't1' : ('Gamma_Left', {'t.0' : 2.0}), 't2' : ('Gamma_Right', {'t.0' : -2.0}), } integral_1 = { 'name' : 'i', 'order' : 1, } equations = { 'Temperature' : """dw_laplace.i.Omega(coef.val, s, t) = 0""" } class DiagPC(object): """ Diagonal (Jacobi) preconditioner. Equivalent to setting `'precond' : 'jacobi'`. """ def setUp(self, pc): A = pc.getOperators()[0] self.idiag = 1.0 / A.getDiagonal() def apply(self, pc, x, y): y.pointwiseMult(x, self.idiag) def setup_petsc_precond(mtx, problem): return DiagPC() solvers = { 'd00' : ('ls.scipy_direct', {'method' : 'umfpack', 'warn' : True,} ), 'd01' : ('ls.scipy_direct', {'method' : 'superlu', 'warn' : True,} ), 'd10' : ('ls.mumps', {}), 'i00' : ('ls.pyamg', {'method' : 'ruge_stuben_solver', 'accel' : 'cg', 'eps_r' : 1e-12, 'method:max_levels' : 5, 'solve:cycle' : 'V',} ), 'i01' : ('ls.pyamg', {'method' : 'smoothed_aggregation_solver', 'accel' : 'cg', 'eps_r' : 1e-12,} ), 'i02' : ('ls.pyamg_krylov', {'method' : 'cg', 'eps_r' : 1e-12, 'i_max' : 1000,} ), 'i10' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'none', # pc_type 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i11' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'python', # just for output (unused) 'setup_precond' : setup_petsc_precond, # user-defined pc 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i12' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'jacobi', # pc_type 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i13' : ('ls.petsc', {'method' : 'cg', # ksp_type 'precond' : 'icc', # pc_type 'eps_a' : 1e-12, # abstol 'eps_r' : 1e-12, # rtol 'i_max' : 1000,} # maxits ), 'i20' : ('ls.scipy_iterative', {'method' : 'cg', 'i_max' : 1000, 'eps_r' : 1e-12,} ), 'i21' : ('ls.scipy_iterative', {'method' : 'bicgstab', 'i_max' : 1000, 'eps_r' : 1e-12,} ), 'i22' : ('ls.scipy_iterative', {'method' : 'qmr', 'i_max' : 1000, 'eps_r' : 1e-12,} ), 'newton' : ('nls.newton', { 'i_max' : 1, 'eps_a' : 1e-10, }), } options = { 'nls' : 'newton', } from sfepy.base.testing import TestCommon output_name = 'test_linear_solvers_%s.vtk' class Test(TestCommon): can_fail = ['ls.pyamg', 'ls.pyamg_krylov', 'ls.petsc', 'ls.mumps',] @staticmethod def from_conf(conf, options): from sfepy.discrete import Problem problem = Problem.from_conf(conf) problem.time_update() test = Test(problem=problem, conf=conf, options=options) return test def _list_linear_solvers(self, confs): d = [] for key, val in six.iteritems(confs): if val.kind.find('ls.') == 0: d.append(val) d.sort(key=lambda a: a.name) return d def test_solvers(self): from sfepy.base.base import IndexedStruct import os.path as op solver_confs = self._list_linear_solvers(self.problem.solver_confs) ok = True tt = [] for solver_conf in solver_confs: method = solver_conf.get('method', '') precond = solver_conf.get('precond', '') name = ' '.join((solver_conf.name, solver_conf.kind, method, precond)).rstrip() self.report(name) self.report('matrix size:', self.problem.mtx_a.shape) self.report(' nnz:', self.problem.mtx_a.nnz) status = IndexedStruct() try: self.problem.init_solvers(status=status, ls_conf=solver_conf, force=True) state = self.problem.solve() failed = status.nls_status.condition != 0 except Exception as aux: failed = True status = None exc = aux ok = ok and ((not failed) or (solver_conf.kind in self.can_fail)) if status is not None: status = status.nls_status for kv in six.iteritems(status.time_stats): self.report('%10s: %7.2f [s]' % kv) self.report('condition: %d, err0: %.3e, err: %.3e' % (status.condition, status.err0, status.err)) tt.append([name, status.time_stats['solve'], status.ls_n_iter, status.err]) aux = name.replace(' ', '_') fname = op.join(self.options.out_dir, op.split(self.conf.output_name)[1]) % aux self.problem.save_state(fname, state) else: self.report('solver failed:') self.report(exc) tt.append([name, -1, 1e10, 1e10]) tt.sort(key=lambda a: a[1]) self.report('solution times / numbers of iterations (residual norms):') for row in tt: self.report('%.2f [s] / % 4d' % (row[1], row[2]), '(%.3e)' % row[3], ':', row[0]) return ok def test_ls_reuse(self): import numpy as nm from sfepy.solvers import Solver from sfepy.discrete.state import State self.problem.init_solvers(ls_conf=self.problem.solver_confs['d00']) nls = self.problem.get_nls() state0 = State(self.problem.equations.variables) state0.apply_ebc() vec0 = state0.get_reduced() self.problem.update_materials() rhs = nls.fun(vec0) mtx = nls.fun_grad(vec0) ok = True for name in ['i12', 'i01']: solver_conf = self.problem.solver_confs[name] method = solver_conf.get('method', '') precond = solver_conf.get('precond', '') name = ' '.join((solver_conf.name, solver_conf.kind, method, precond)).rstrip() self.report(name) try: ls =
Solver.any_from_conf(solver_conf)
sfepy.solvers.Solver.any_from_conf
""" Quantum oscillator. See :ref:`quantum-quantum_common`. """ from __future__ import absolute_import from sfepy.linalg import norm_l2_along_axis from examples.quantum.quantum_common import common def get_exact(n_eigs, box_size, dim): if dim == 2: eigs = [1] + [2]*2 + [3]*3 + [4]*4 + [5]*5 + [6]*6 elif dim == 3: eigs = [float(1)/2 + x for x in [1] + [2]*3 + [3]*6 + [4]*10] return eigs def fun_v(ts, coor, mode=None, **kwargs): if not mode == 'qp': return out = {} C = 0.5 val = C *
norm_l2_along_axis(coor, axis=1, squared=True)
sfepy.linalg.norm_l2_along_axis
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ import time import numpy as nm from sfepy.base.base import output, assert_ import fea from sfepy.discrete.fem.utils import prepare_remap from sfepy.discrete.common.dof_info import expand_nodes_to_dofs from sfepy.discrete.fem.global_interp import get_ref_coors from sfepy.discrete.fem.facets import get_facet_dof_permutations from sfepy.discrete.fem.fields_base import (FEField, VolumeField, SurfaceField, H1Mixin) from sfepy.discrete.fem.extmods.bases import evaluate_in_rc class H1NodalMixin(H1Mixin): def _setup_facet_orientations(self): order = self.approx_order self.node_desc = self.interp.describe_nodes() edge_nodes = self.node_desc.edge_nodes if edge_nodes is not None: n_fp = self.gel.edges.shape[1] self.edge_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) face_nodes = self.node_desc.face_nodes if face_nodes is not None: n_fp = self.gel.faces.shape[1] self.face_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) def _setup_edge_dofs(self): """ Setup edge DOF connectivity. """ if self.node_desc.edge is None: return 0, None, None return self._setup_facet_dofs(1, self.node_desc.edge, self.edge_dof_perms, self.n_vertex_dof) def _setup_face_dofs(self): """ Setup face DOF connectivity. """ if self.node_desc.face is None: return 0, None, None return self._setup_facet_dofs(self.domain.shape.tdim - 1, self.node_desc.face, self.face_dof_perms, self.n_vertex_dof + self.n_edge_dof) def _setup_facet_dofs(self, dim, facet_desc, facet_perms, offset): """ Helper function to setup facet DOF connectivity, works for both edges and faces. """ facet_desc = nm.array(facet_desc) n_dof_per_facet = facet_desc.shape[1] cmesh = self.domain.cmesh facets = self.region.entities[dim] ii = nm.arange(facets.shape[0], dtype=nm.int32) all_dofs = offset + expand_nodes_to_dofs(ii, n_dof_per_facet) # Prepare global facet id remapping to field-local numbering. remap =
prepare_remap(facets, cmesh.num[dim])
sfepy.discrete.fem.utils.prepare_remap
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ import time import numpy as nm from sfepy.base.base import output, assert_ import fea from sfepy.discrete.fem.utils import prepare_remap from sfepy.discrete.common.dof_info import expand_nodes_to_dofs from sfepy.discrete.fem.global_interp import get_ref_coors from sfepy.discrete.fem.facets import get_facet_dof_permutations from sfepy.discrete.fem.fields_base import (FEField, VolumeField, SurfaceField, H1Mixin) from sfepy.discrete.fem.extmods.bases import evaluate_in_rc class H1NodalMixin(H1Mixin): def _setup_facet_orientations(self): order = self.approx_order self.node_desc = self.interp.describe_nodes() edge_nodes = self.node_desc.edge_nodes if edge_nodes is not None: n_fp = self.gel.edges.shape[1] self.edge_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) face_nodes = self.node_desc.face_nodes if face_nodes is not None: n_fp = self.gel.faces.shape[1] self.face_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) def _setup_edge_dofs(self): """ Setup edge DOF connectivity. """ if self.node_desc.edge is None: return 0, None, None return self._setup_facet_dofs(1, self.node_desc.edge, self.edge_dof_perms, self.n_vertex_dof) def _setup_face_dofs(self): """ Setup face DOF connectivity. """ if self.node_desc.face is None: return 0, None, None return self._setup_facet_dofs(self.domain.shape.tdim - 1, self.node_desc.face, self.face_dof_perms, self.n_vertex_dof + self.n_edge_dof) def _setup_facet_dofs(self, dim, facet_desc, facet_perms, offset): """ Helper function to setup facet DOF connectivity, works for both edges and faces. """ facet_desc = nm.array(facet_desc) n_dof_per_facet = facet_desc.shape[1] cmesh = self.domain.cmesh facets = self.region.entities[dim] ii = nm.arange(facets.shape[0], dtype=nm.int32) all_dofs = offset + expand_nodes_to_dofs(ii, n_dof_per_facet) # Prepare global facet id remapping to field-local numbering. remap = prepare_remap(facets, cmesh.num[dim]) cconn = self.region.domain.cmesh.get_conn(self.region.tdim, dim) offs = cconn.offsets n_f = self.gel.edges.shape[0] if dim == 1 else self.gel.faces.shape[0] oris = cmesh.get_orientations(dim) for ig, ap in self.aps.iteritems(): gcells = self.region.get_cells(ig, offset=False) n_el = gcells.shape[0] indices = cconn.indices[offs[gcells[0]]:offs[gcells[-1]+1]] facets_of_cells = remap[indices] ori = oris[offs[gcells[0]]:offs[gcells[-1]+1]] perms = facet_perms[ig][ori] # Define global facet dof numbers. gdofs = offset + expand_nodes_to_dofs(facets_of_cells, n_dof_per_facet) # Elements of facets. iel = nm.arange(n_el, dtype=nm.int32).repeat(n_f) ies = nm.tile(nm.arange(n_f, dtype=nm.int32), n_el) # DOF columns in econn for each facet. iep = facet_desc[ies] iaux = nm.arange(gdofs.shape[0], dtype=nm.int32) ap.econn[iel[:, None], iep] = gdofs[iaux[:, None], perms] n_dof = n_dof_per_facet * facets.shape[0] assert_(n_dof == nm.prod(all_dofs.shape)) return n_dof, all_dofs, remap def _setup_bubble_dofs(self): """ Setup bubble DOF connectivity. """ if self.node_desc.bubble is None: return 0, None, None offset = self.n_vertex_dof + self.n_edge_dof + self.n_face_dof n_dof = 0 n_dof_per_cell = self.node_desc.bubble.shape[0] all_dofs = {} remaps = {} for ig, ap in self.aps.iteritems(): ii = self.region.get_cells(ig) n_cell = ii.shape[0] nd = n_dof_per_cell * n_cell group = self.domain.groups[ig] remaps[ig] = prepare_remap(ii, group.shape.n_el) aux = nm.arange(offset + n_dof, offset + n_dof + nd, dtype=nm.int32) aux.shape = (n_cell, n_dof_per_cell) iep = self.node_desc.bubble[0] ap.econn[:,iep:] = aux all_dofs[ig] = aux n_dof += nd return n_dof, all_dofs, remaps def set_dofs(self, fun=0.0, region=None, dpn=None, warn=None): """ Set the values of DOFs in a given region using a function of space coordinates or value `fun`. """ if region is None: region = self.region if dpn is None: dpn = self.n_components aux = self.get_dofs_in_region(region, clean=True, warn=warn) nods = nm.unique(nm.hstack(aux)) if callable(fun): vals = fun(self.get_coor(nods)) elif nm.isscalar(fun): vals = nm.repeat([fun], nods.shape[0] * dpn) elif isinstance(fun, nm.ndarray): assert_(len(fun) == dpn) vals = nm.repeat(fun, nods.shape[0]) else: raise ValueError('unknown function/value type! (%s)' % type(fun)) return nods, vals def evaluate_at(self, coors, source_vals, strategy='kdtree', close_limit=0.1, cache=None, ret_cells=False, ret_status=False, ret_ref_coors=False, verbose=True): """ Evaluate source DOF values corresponding to the field in the given coordinates using the field interpolation. Parameters ---------- coors : array The coordinates the source values should be interpolated into. source_vals : array The source DOF values corresponding to the field. strategy : str, optional The strategy for finding the elements that contain the coordinates. Only 'kdtree' is supported for the moment. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh, the inverse connectivity of the field mesh and the KDTree instance can be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and `cache.kdtree`. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the KDTree related data are ignored. ret_cells : bool, optional If True, return also the cell indices the coordinates are in. ret_status : bool, optional If True, return also the status for each point: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure. ret_ref_coors : bool, optional If True, return also the found reference element coordinates. verbose : bool If False, reduce verbosity. Returns ------- vals : array The interpolated values. cells : array The cell indices, if `ret_cells` or `ret_status` are True. status : array The status, if `ret_status` is True. """
output('evaluating in %d points...' % coors.shape[0], verbose=verbose)
sfepy.base.base.output
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ import time import numpy as nm from sfepy.base.base import output, assert_ import fea from sfepy.discrete.fem.utils import prepare_remap from sfepy.discrete.common.dof_info import expand_nodes_to_dofs from sfepy.discrete.fem.global_interp import get_ref_coors from sfepy.discrete.fem.facets import get_facet_dof_permutations from sfepy.discrete.fem.fields_base import (FEField, VolumeField, SurfaceField, H1Mixin) from sfepy.discrete.fem.extmods.bases import evaluate_in_rc class H1NodalMixin(H1Mixin): def _setup_facet_orientations(self): order = self.approx_order self.node_desc = self.interp.describe_nodes() edge_nodes = self.node_desc.edge_nodes if edge_nodes is not None: n_fp = self.gel.edges.shape[1] self.edge_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) face_nodes = self.node_desc.face_nodes if face_nodes is not None: n_fp = self.gel.faces.shape[1] self.face_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) def _setup_edge_dofs(self): """ Setup edge DOF connectivity. """ if self.node_desc.edge is None: return 0, None, None return self._setup_facet_dofs(1, self.node_desc.edge, self.edge_dof_perms, self.n_vertex_dof) def _setup_face_dofs(self): """ Setup face DOF connectivity. """ if self.node_desc.face is None: return 0, None, None return self._setup_facet_dofs(self.domain.shape.tdim - 1, self.node_desc.face, self.face_dof_perms, self.n_vertex_dof + self.n_edge_dof) def _setup_facet_dofs(self, dim, facet_desc, facet_perms, offset): """ Helper function to setup facet DOF connectivity, works for both edges and faces. """ facet_desc = nm.array(facet_desc) n_dof_per_facet = facet_desc.shape[1] cmesh = self.domain.cmesh facets = self.region.entities[dim] ii = nm.arange(facets.shape[0], dtype=nm.int32) all_dofs = offset + expand_nodes_to_dofs(ii, n_dof_per_facet) # Prepare global facet id remapping to field-local numbering. remap = prepare_remap(facets, cmesh.num[dim]) cconn = self.region.domain.cmesh.get_conn(self.region.tdim, dim) offs = cconn.offsets n_f = self.gel.edges.shape[0] if dim == 1 else self.gel.faces.shape[0] oris = cmesh.get_orientations(dim) for ig, ap in self.aps.iteritems(): gcells = self.region.get_cells(ig, offset=False) n_el = gcells.shape[0] indices = cconn.indices[offs[gcells[0]]:offs[gcells[-1]+1]] facets_of_cells = remap[indices] ori = oris[offs[gcells[0]]:offs[gcells[-1]+1]] perms = facet_perms[ig][ori] # Define global facet dof numbers. gdofs = offset + expand_nodes_to_dofs(facets_of_cells, n_dof_per_facet) # Elements of facets. iel = nm.arange(n_el, dtype=nm.int32).repeat(n_f) ies = nm.tile(nm.arange(n_f, dtype=nm.int32), n_el) # DOF columns in econn for each facet. iep = facet_desc[ies] iaux = nm.arange(gdofs.shape[0], dtype=nm.int32) ap.econn[iel[:, None], iep] = gdofs[iaux[:, None], perms] n_dof = n_dof_per_facet * facets.shape[0] assert_(n_dof == nm.prod(all_dofs.shape)) return n_dof, all_dofs, remap def _setup_bubble_dofs(self): """ Setup bubble DOF connectivity. """ if self.node_desc.bubble is None: return 0, None, None offset = self.n_vertex_dof + self.n_edge_dof + self.n_face_dof n_dof = 0 n_dof_per_cell = self.node_desc.bubble.shape[0] all_dofs = {} remaps = {} for ig, ap in self.aps.iteritems(): ii = self.region.get_cells(ig) n_cell = ii.shape[0] nd = n_dof_per_cell * n_cell group = self.domain.groups[ig] remaps[ig] = prepare_remap(ii, group.shape.n_el) aux = nm.arange(offset + n_dof, offset + n_dof + nd, dtype=nm.int32) aux.shape = (n_cell, n_dof_per_cell) iep = self.node_desc.bubble[0] ap.econn[:,iep:] = aux all_dofs[ig] = aux n_dof += nd return n_dof, all_dofs, remaps def set_dofs(self, fun=0.0, region=None, dpn=None, warn=None): """ Set the values of DOFs in a given region using a function of space coordinates or value `fun`. """ if region is None: region = self.region if dpn is None: dpn = self.n_components aux = self.get_dofs_in_region(region, clean=True, warn=warn) nods = nm.unique(nm.hstack(aux)) if callable(fun): vals = fun(self.get_coor(nods)) elif nm.isscalar(fun): vals = nm.repeat([fun], nods.shape[0] * dpn) elif isinstance(fun, nm.ndarray): assert_(len(fun) == dpn) vals = nm.repeat(fun, nods.shape[0]) else: raise ValueError('unknown function/value type! (%s)' % type(fun)) return nods, vals def evaluate_at(self, coors, source_vals, strategy='kdtree', close_limit=0.1, cache=None, ret_cells=False, ret_status=False, ret_ref_coors=False, verbose=True): """ Evaluate source DOF values corresponding to the field in the given coordinates using the field interpolation. Parameters ---------- coors : array The coordinates the source values should be interpolated into. source_vals : array The source DOF values corresponding to the field. strategy : str, optional The strategy for finding the elements that contain the coordinates. Only 'kdtree' is supported for the moment. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh, the inverse connectivity of the field mesh and the KDTree instance can be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and `cache.kdtree`. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the KDTree related data are ignored. ret_cells : bool, optional If True, return also the cell indices the coordinates are in. ret_status : bool, optional If True, return also the status for each point: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure. ret_ref_coors : bool, optional If True, return also the found reference element coordinates. verbose : bool If False, reduce verbosity. Returns ------- vals : array The interpolated values. cells : array The cell indices, if `ret_cells` or `ret_status` are True. status : array The status, if `ret_status` is True. """ output('evaluating in %d points...' % coors.shape[0], verbose=verbose) ref_coors, cells, status = get_ref_coors(self, coors, strategy=strategy, close_limit=close_limit, cache=cache, verbose=verbose) tt = time.clock() vertex_coorss, nodess, orders, mtx_is = [], [], [], [] conns = [] for ap in self.aps.itervalues(): ps = ap.interp.poly_spaces['v'] vertex_coorss.append(ps.geometry.coors) nodess.append(ps.nodes) mtx_is.append(ps.get_mtx_i()) orders.append(ps.order) conns.append(ap.econn) orders = nm.array(orders, dtype=nm.int32) # Interpolate to the reference coordinates. vals = nm.empty((coors.shape[0], source_vals.shape[1]), dtype=source_vals.dtype) evaluate_in_rc(vals, ref_coors, cells, status, source_vals, conns, vertex_coorss, nodess, orders, mtx_is, 1e-15) output('interpolation: %f s' % (time.clock()-tt),verbose=verbose)
output('...done',verbose=verbose)
sfepy.base.base.output
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ import time import numpy as nm from sfepy.base.base import output, assert_ import fea from sfepy.discrete.fem.utils import prepare_remap from sfepy.discrete.common.dof_info import expand_nodes_to_dofs from sfepy.discrete.fem.global_interp import get_ref_coors from sfepy.discrete.fem.facets import get_facet_dof_permutations from sfepy.discrete.fem.fields_base import (FEField, VolumeField, SurfaceField, H1Mixin) from sfepy.discrete.fem.extmods.bases import evaluate_in_rc class H1NodalMixin(H1Mixin): def _setup_facet_orientations(self): order = self.approx_order self.node_desc = self.interp.describe_nodes() edge_nodes = self.node_desc.edge_nodes if edge_nodes is not None: n_fp = self.gel.edges.shape[1] self.edge_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) face_nodes = self.node_desc.face_nodes if face_nodes is not None: n_fp = self.gel.faces.shape[1] self.face_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) def _setup_edge_dofs(self): """ Setup edge DOF connectivity. """ if self.node_desc.edge is None: return 0, None, None return self._setup_facet_dofs(1, self.node_desc.edge, self.edge_dof_perms, self.n_vertex_dof) def _setup_face_dofs(self): """ Setup face DOF connectivity. """ if self.node_desc.face is None: return 0, None, None return self._setup_facet_dofs(self.domain.shape.tdim - 1, self.node_desc.face, self.face_dof_perms, self.n_vertex_dof + self.n_edge_dof) def _setup_facet_dofs(self, dim, facet_desc, facet_perms, offset): """ Helper function to setup facet DOF connectivity, works for both edges and faces. """ facet_desc = nm.array(facet_desc) n_dof_per_facet = facet_desc.shape[1] cmesh = self.domain.cmesh facets = self.region.entities[dim] ii = nm.arange(facets.shape[0], dtype=nm.int32) all_dofs = offset + expand_nodes_to_dofs(ii, n_dof_per_facet) # Prepare global facet id remapping to field-local numbering. remap = prepare_remap(facets, cmesh.num[dim]) cconn = self.region.domain.cmesh.get_conn(self.region.tdim, dim) offs = cconn.offsets n_f = self.gel.edges.shape[0] if dim == 1 else self.gel.faces.shape[0] oris = cmesh.get_orientations(dim) for ig, ap in self.aps.iteritems(): gcells = self.region.get_cells(ig, offset=False) n_el = gcells.shape[0] indices = cconn.indices[offs[gcells[0]]:offs[gcells[-1]+1]] facets_of_cells = remap[indices] ori = oris[offs[gcells[0]]:offs[gcells[-1]+1]] perms = facet_perms[ig][ori] # Define global facet dof numbers. gdofs = offset + expand_nodes_to_dofs(facets_of_cells, n_dof_per_facet) # Elements of facets. iel = nm.arange(n_el, dtype=nm.int32).repeat(n_f) ies = nm.tile(nm.arange(n_f, dtype=nm.int32), n_el) # DOF columns in econn for each facet. iep = facet_desc[ies] iaux = nm.arange(gdofs.shape[0], dtype=nm.int32) ap.econn[iel[:, None], iep] = gdofs[iaux[:, None], perms] n_dof = n_dof_per_facet * facets.shape[0] assert_(n_dof == nm.prod(all_dofs.shape)) return n_dof, all_dofs, remap def _setup_bubble_dofs(self): """ Setup bubble DOF connectivity. """ if self.node_desc.bubble is None: return 0, None, None offset = self.n_vertex_dof + self.n_edge_dof + self.n_face_dof n_dof = 0 n_dof_per_cell = self.node_desc.bubble.shape[0] all_dofs = {} remaps = {} for ig, ap in self.aps.iteritems(): ii = self.region.get_cells(ig) n_cell = ii.shape[0] nd = n_dof_per_cell * n_cell group = self.domain.groups[ig] remaps[ig] = prepare_remap(ii, group.shape.n_el) aux = nm.arange(offset + n_dof, offset + n_dof + nd, dtype=nm.int32) aux.shape = (n_cell, n_dof_per_cell) iep = self.node_desc.bubble[0] ap.econn[:,iep:] = aux all_dofs[ig] = aux n_dof += nd return n_dof, all_dofs, remaps def set_dofs(self, fun=0.0, region=None, dpn=None, warn=None): """ Set the values of DOFs in a given region using a function of space coordinates or value `fun`. """ if region is None: region = self.region if dpn is None: dpn = self.n_components aux = self.get_dofs_in_region(region, clean=True, warn=warn) nods = nm.unique(nm.hstack(aux)) if callable(fun): vals = fun(self.get_coor(nods)) elif nm.isscalar(fun): vals = nm.repeat([fun], nods.shape[0] * dpn) elif isinstance(fun, nm.ndarray): assert_(len(fun) == dpn) vals = nm.repeat(fun, nods.shape[0]) else: raise ValueError('unknown function/value type! (%s)' % type(fun)) return nods, vals def evaluate_at(self, coors, source_vals, strategy='kdtree', close_limit=0.1, cache=None, ret_cells=False, ret_status=False, ret_ref_coors=False, verbose=True): """ Evaluate source DOF values corresponding to the field in the given coordinates using the field interpolation. Parameters ---------- coors : array The coordinates the source values should be interpolated into. source_vals : array The source DOF values corresponding to the field. strategy : str, optional The strategy for finding the elements that contain the coordinates. Only 'kdtree' is supported for the moment. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh, the inverse connectivity of the field mesh and the KDTree instance can be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and `cache.kdtree`. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the KDTree related data are ignored. ret_cells : bool, optional If True, return also the cell indices the coordinates are in. ret_status : bool, optional If True, return also the status for each point: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure. ret_ref_coors : bool, optional If True, return also the found reference element coordinates. verbose : bool If False, reduce verbosity. Returns ------- vals : array The interpolated values. cells : array The cell indices, if `ret_cells` or `ret_status` are True. status : array The status, if `ret_status` is True. """ output('evaluating in %d points...' % coors.shape[0], verbose=verbose) ref_coors, cells, status = get_ref_coors(self, coors, strategy=strategy, close_limit=close_limit, cache=cache, verbose=verbose) tt = time.clock() vertex_coorss, nodess, orders, mtx_is = [], [], [], [] conns = [] for ap in self.aps.itervalues(): ps = ap.interp.poly_spaces['v'] vertex_coorss.append(ps.geometry.coors) nodess.append(ps.nodes) mtx_is.append(ps.get_mtx_i()) orders.append(ps.order) conns.append(ap.econn) orders = nm.array(orders, dtype=nm.int32) # Interpolate to the reference coordinates. vals = nm.empty((coors.shape[0], source_vals.shape[1]), dtype=source_vals.dtype) evaluate_in_rc(vals, ref_coors, cells, status, source_vals, conns, vertex_coorss, nodess, orders, mtx_is, 1e-15) output('interpolation: %f s' % (time.clock()-tt),verbose=verbose) output('...done',verbose=verbose) if ret_ref_coors: return vals, ref_coors, cells, status elif ret_status: return vals, cells, status elif ret_cells: return vals, cells else: return vals class H1NodalVolumeField(H1NodalMixin, VolumeField): family_name = 'volume_H1_lagrange' def interp_v_vals_to_n_vals(self, vec): """ Interpolate a function defined by vertex DOF values using the FE geometry base (P1 or Q1) into the extra nodes, i.e. define the extra DOF values. """ if not self.node_desc.has_extra_nodes(): enod_vol_val = vec.copy() else: dim = vec.shape[1] enod_vol_val = nm.zeros((self.n_nod, dim), dtype=nm.float64) for ig, ap in self.aps.iteritems(): group = self.domain.groups[ig] econn = ap.econn coors = ap.interp.poly_spaces['v'].node_coors ginterp = ap.interp.gel.interp bf = ginterp.poly_spaces['v'].eval_base(coors) bf = bf[:,0,:].copy() evec = nm.dot(bf, vec[group.conn]) enod_vol_val[econn] = nm.swapaxes(evec, 0, 1) return enod_vol_val def set_basis(self, maps, methods): """ This function along with eval_basis supports the general term IntFE. It sets parameters and basis functions at reference element according to its method (val, grad, div, etc). Parameters ---------- maps : class It provides information about mapping between reference and real element. Quadrature points stored in maps.qp_coor are used here. method : list of string It stores methods for variable evaluation. At first position, there is one of val, grad, or div. self.bfref : numpy.array of shape = (n_qp, n_basis) + basis_shape An array that stores basis functions evaluated at quadrature points. Here n_qp is number of quadrature points, n_basis is number of basis functions, and basis_shape is a shape of basis function, i.e. (1,) for scalar-valued, (dim,) for vector-valued, (dim, dim) for matrix-valued, etc. Returns ------- self.bfref : numpy.array It stores a basis functions at quadrature points of shape according to proceeded methods. self.n_basis : int number of basis functions """ self.eval_method = methods def get_grad(maps, shape): bfref0 = eval_base(maps.qp_coor, diff=True).swapaxes(1, 2) if shape == (1,): # scalar variable bfref = bfref0 elif len(shape) == 1: # vector variable vec_shape = nm.array(bfref0.shape + shape) vec_shape[1] *= shape[0] bfref = nm.zeros(vec_shape) for ii in nm.arange(shape[0]): slc = slice(ii*bfref0.shape[1], (ii+1)*bfref0.shape[1]) bfref[:, slc, ii] = bfref0 else: # higher-order tensors variable msg = "Evaluation of basis has not been implemented \ for higher-order tensors yet." raise NotImplementedError(msg) return bfref def get_val(maps, shape): bfref0 = eval_base(maps.qp_coor, diff=False).swapaxes(1, 2) if self.shape == (1,): # scalar variable bfref = bfref0 elif len(shape) == 1: vec_shape = nm.array(bfref0.shape) vec_shape[1:3] *= shape[0] bfref = nm.zeros(vec_shape) for ii in nm.arange(shape[0]): slc = slice(ii*bfref0.shape[1], (ii+1)*bfref0.shape[1]) bfref[:, slc] = bfref0 else: # higher-order tensors variable msg = "Evaluation of basis has not been implemented \ for higher-order tensors yet." raise NotImplementedError(msg) return bfref eval_base = self.interp.poly_spaces['v'].eval_base if self.eval_method[0] == 'val': bfref = get_val(maps, self.shape) elif self.eval_method[0] == 'grad': bfref = get_grad(maps, self.shape) elif self.eval_method[0] == 'div': bfref = get_grad(maps, self.shape) else: raise NotImplementedError("The method '%s' is not implemented" \ % (self.eval_method)) self.bfref = bfref self.n_basis = self.bfref.shape[1] def eval_basis(self, maps): """ It returns basis functions evaluated at quadrature points and mapped at reference element according to real element. """ if self.eval_method == ['grad']: val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0)) return val elif self.eval_method == ['val']: return self.bfref elif self.eval_method == ['div']: val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0)) val = nm.atleast_3d(nm.einsum('ijkk', val)) return val elif self.eval_method == ['grad', 'sym', 'Man']: val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0)) from sfepy.terms.terms_general import proceed_methods val = proceed_methods(val, self.eval_method[1:]) return val else: msg = "Improper method '%s' for evaluation of basis functions" \ % (self.eval_method) raise NotImplementedError(msg) class H1DiscontinuousField(H1NodalMixin, VolumeField): family_name = 'volume_H1_lagrange_discontinuous' def _setup_approximations(self): self.aps = {} self.aps_by_name = {} for ig in self.igs: name = self.interp.name + '_%s_ig%d' % (self.region.name, ig) ap = fea.DiscontinuousApproximation(name, self.interp, self.region, ig) self.aps[ig] = ap self.aps_by_name[ap.name] = ap def _setup_global_base(self): """ Setup global DOF/base function indices and connectivity of the field. """ self._setup_facet_orientations() self._init_econn() n_dof = 0 all_dofs = {} remaps = {} for ig, ap in self.aps.iteritems(): ii = self.region.get_cells(ig) nd = nm.prod(ap.econn.shape) group = self.domain.groups[ig] remaps[ig] = prepare_remap(ii, group.shape.n_el) aux = nm.arange(n_dof, n_dof + nd, dtype=nm.int32) aux.shape = ap.econn.shape ap.econn[:] = aux all_dofs[ig] = aux n_dof += nd self.n_nod = n_dof self.n_bubble_dof = n_dof self.bubble_dofs = all_dofs self.bubble_remaps = remaps self.n_vertex_dof = self.n_edge_dof = self.n_face_dof = 0 self._setup_esurface() def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if self.approx_order != 0: dofs = self.average_to_vertices(dofs) new_dofs =
FEField.extend_dofs(self, dofs)
sfepy.discrete.fem.fields_base.FEField.extend_dofs
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ import time import numpy as nm from sfepy.base.base import output, assert_ import fea from sfepy.discrete.fem.utils import prepare_remap from sfepy.discrete.common.dof_info import expand_nodes_to_dofs from sfepy.discrete.fem.global_interp import get_ref_coors from sfepy.discrete.fem.facets import get_facet_dof_permutations from sfepy.discrete.fem.fields_base import (FEField, VolumeField, SurfaceField, H1Mixin) from sfepy.discrete.fem.extmods.bases import evaluate_in_rc class H1NodalMixin(H1Mixin): def _setup_facet_orientations(self): order = self.approx_order self.node_desc = self.interp.describe_nodes() edge_nodes = self.node_desc.edge_nodes if edge_nodes is not None: n_fp = self.gel.edges.shape[1] self.edge_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) face_nodes = self.node_desc.face_nodes if face_nodes is not None: n_fp = self.gel.faces.shape[1] self.face_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) def _setup_edge_dofs(self): """ Setup edge DOF connectivity. """ if self.node_desc.edge is None: return 0, None, None return self._setup_facet_dofs(1, self.node_desc.edge, self.edge_dof_perms, self.n_vertex_dof) def _setup_face_dofs(self): """ Setup face DOF connectivity. """ if self.node_desc.face is None: return 0, None, None return self._setup_facet_dofs(self.domain.shape.tdim - 1, self.node_desc.face, self.face_dof_perms, self.n_vertex_dof + self.n_edge_dof) def _setup_facet_dofs(self, dim, facet_desc, facet_perms, offset): """ Helper function to setup facet DOF connectivity, works for both edges and faces. """ facet_desc = nm.array(facet_desc) n_dof_per_facet = facet_desc.shape[1] cmesh = self.domain.cmesh facets = self.region.entities[dim] ii = nm.arange(facets.shape[0], dtype=nm.int32) all_dofs = offset + expand_nodes_to_dofs(ii, n_dof_per_facet) # Prepare global facet id remapping to field-local numbering. remap = prepare_remap(facets, cmesh.num[dim]) cconn = self.region.domain.cmesh.get_conn(self.region.tdim, dim) offs = cconn.offsets n_f = self.gel.edges.shape[0] if dim == 1 else self.gel.faces.shape[0] oris = cmesh.get_orientations(dim) for ig, ap in self.aps.iteritems(): gcells = self.region.get_cells(ig, offset=False) n_el = gcells.shape[0] indices = cconn.indices[offs[gcells[0]]:offs[gcells[-1]+1]] facets_of_cells = remap[indices] ori = oris[offs[gcells[0]]:offs[gcells[-1]+1]] perms = facet_perms[ig][ori] # Define global facet dof numbers. gdofs = offset + expand_nodes_to_dofs(facets_of_cells, n_dof_per_facet) # Elements of facets. iel = nm.arange(n_el, dtype=nm.int32).repeat(n_f) ies = nm.tile(nm.arange(n_f, dtype=nm.int32), n_el) # DOF columns in econn for each facet. iep = facet_desc[ies] iaux = nm.arange(gdofs.shape[0], dtype=nm.int32) ap.econn[iel[:, None], iep] = gdofs[iaux[:, None], perms] n_dof = n_dof_per_facet * facets.shape[0] assert_(n_dof == nm.prod(all_dofs.shape)) return n_dof, all_dofs, remap def _setup_bubble_dofs(self): """ Setup bubble DOF connectivity. """ if self.node_desc.bubble is None: return 0, None, None offset = self.n_vertex_dof + self.n_edge_dof + self.n_face_dof n_dof = 0 n_dof_per_cell = self.node_desc.bubble.shape[0] all_dofs = {} remaps = {} for ig, ap in self.aps.iteritems(): ii = self.region.get_cells(ig) n_cell = ii.shape[0] nd = n_dof_per_cell * n_cell group = self.domain.groups[ig] remaps[ig] = prepare_remap(ii, group.shape.n_el) aux = nm.arange(offset + n_dof, offset + n_dof + nd, dtype=nm.int32) aux.shape = (n_cell, n_dof_per_cell) iep = self.node_desc.bubble[0] ap.econn[:,iep:] = aux all_dofs[ig] = aux n_dof += nd return n_dof, all_dofs, remaps def set_dofs(self, fun=0.0, region=None, dpn=None, warn=None): """ Set the values of DOFs in a given region using a function of space coordinates or value `fun`. """ if region is None: region = self.region if dpn is None: dpn = self.n_components aux = self.get_dofs_in_region(region, clean=True, warn=warn) nods = nm.unique(nm.hstack(aux)) if callable(fun): vals = fun(self.get_coor(nods)) elif nm.isscalar(fun): vals = nm.repeat([fun], nods.shape[0] * dpn) elif isinstance(fun, nm.ndarray): assert_(len(fun) == dpn) vals = nm.repeat(fun, nods.shape[0]) else: raise ValueError('unknown function/value type! (%s)' % type(fun)) return nods, vals def evaluate_at(self, coors, source_vals, strategy='kdtree', close_limit=0.1, cache=None, ret_cells=False, ret_status=False, ret_ref_coors=False, verbose=True): """ Evaluate source DOF values corresponding to the field in the given coordinates using the field interpolation. Parameters ---------- coors : array The coordinates the source values should be interpolated into. source_vals : array The source DOF values corresponding to the field. strategy : str, optional The strategy for finding the elements that contain the coordinates. Only 'kdtree' is supported for the moment. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh, the inverse connectivity of the field mesh and the KDTree instance can be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and `cache.kdtree`. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the KDTree related data are ignored. ret_cells : bool, optional If True, return also the cell indices the coordinates are in. ret_status : bool, optional If True, return also the status for each point: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure. ret_ref_coors : bool, optional If True, return also the found reference element coordinates. verbose : bool If False, reduce verbosity. Returns ------- vals : array The interpolated values. cells : array The cell indices, if `ret_cells` or `ret_status` are True. status : array The status, if `ret_status` is True. """ output('evaluating in %d points...' % coors.shape[0], verbose=verbose) ref_coors, cells, status = get_ref_coors(self, coors, strategy=strategy, close_limit=close_limit, cache=cache, verbose=verbose) tt = time.clock() vertex_coorss, nodess, orders, mtx_is = [], [], [], [] conns = [] for ap in self.aps.itervalues(): ps = ap.interp.poly_spaces['v'] vertex_coorss.append(ps.geometry.coors) nodess.append(ps.nodes) mtx_is.append(ps.get_mtx_i()) orders.append(ps.order) conns.append(ap.econn) orders = nm.array(orders, dtype=nm.int32) # Interpolate to the reference coordinates. vals = nm.empty((coors.shape[0], source_vals.shape[1]), dtype=source_vals.dtype) evaluate_in_rc(vals, ref_coors, cells, status, source_vals, conns, vertex_coorss, nodess, orders, mtx_is, 1e-15) output('interpolation: %f s' % (time.clock()-tt),verbose=verbose) output('...done',verbose=verbose) if ret_ref_coors: return vals, ref_coors, cells, status elif ret_status: return vals, cells, status elif ret_cells: return vals, cells else: return vals class H1NodalVolumeField(H1NodalMixin, VolumeField): family_name = 'volume_H1_lagrange' def interp_v_vals_to_n_vals(self, vec): """ Interpolate a function defined by vertex DOF values using the FE geometry base (P1 or Q1) into the extra nodes, i.e. define the extra DOF values. """ if not self.node_desc.has_extra_nodes(): enod_vol_val = vec.copy() else: dim = vec.shape[1] enod_vol_val = nm.zeros((self.n_nod, dim), dtype=nm.float64) for ig, ap in self.aps.iteritems(): group = self.domain.groups[ig] econn = ap.econn coors = ap.interp.poly_spaces['v'].node_coors ginterp = ap.interp.gel.interp bf = ginterp.poly_spaces['v'].eval_base(coors) bf = bf[:,0,:].copy() evec = nm.dot(bf, vec[group.conn]) enod_vol_val[econn] = nm.swapaxes(evec, 0, 1) return enod_vol_val def set_basis(self, maps, methods): """ This function along with eval_basis supports the general term IntFE. It sets parameters and basis functions at reference element according to its method (val, grad, div, etc). Parameters ---------- maps : class It provides information about mapping between reference and real element. Quadrature points stored in maps.qp_coor are used here. method : list of string It stores methods for variable evaluation. At first position, there is one of val, grad, or div. self.bfref : numpy.array of shape = (n_qp, n_basis) + basis_shape An array that stores basis functions evaluated at quadrature points. Here n_qp is number of quadrature points, n_basis is number of basis functions, and basis_shape is a shape of basis function, i.e. (1,) for scalar-valued, (dim,) for vector-valued, (dim, dim) for matrix-valued, etc. Returns ------- self.bfref : numpy.array It stores a basis functions at quadrature points of shape according to proceeded methods. self.n_basis : int number of basis functions """ self.eval_method = methods def get_grad(maps, shape): bfref0 = eval_base(maps.qp_coor, diff=True).swapaxes(1, 2) if shape == (1,): # scalar variable bfref = bfref0 elif len(shape) == 1: # vector variable vec_shape = nm.array(bfref0.shape + shape) vec_shape[1] *= shape[0] bfref = nm.zeros(vec_shape) for ii in nm.arange(shape[0]): slc = slice(ii*bfref0.shape[1], (ii+1)*bfref0.shape[1]) bfref[:, slc, ii] = bfref0 else: # higher-order tensors variable msg = "Evaluation of basis has not been implemented \ for higher-order tensors yet." raise NotImplementedError(msg) return bfref def get_val(maps, shape): bfref0 = eval_base(maps.qp_coor, diff=False).swapaxes(1, 2) if self.shape == (1,): # scalar variable bfref = bfref0 elif len(shape) == 1: vec_shape = nm.array(bfref0.shape) vec_shape[1:3] *= shape[0] bfref = nm.zeros(vec_shape) for ii in nm.arange(shape[0]): slc = slice(ii*bfref0.shape[1], (ii+1)*bfref0.shape[1]) bfref[:, slc] = bfref0 else: # higher-order tensors variable msg = "Evaluation of basis has not been implemented \ for higher-order tensors yet." raise NotImplementedError(msg) return bfref eval_base = self.interp.poly_spaces['v'].eval_base if self.eval_method[0] == 'val': bfref = get_val(maps, self.shape) elif self.eval_method[0] == 'grad': bfref = get_grad(maps, self.shape) elif self.eval_method[0] == 'div': bfref = get_grad(maps, self.shape) else: raise NotImplementedError("The method '%s' is not implemented" \ % (self.eval_method)) self.bfref = bfref self.n_basis = self.bfref.shape[1] def eval_basis(self, maps): """ It returns basis functions evaluated at quadrature points and mapped at reference element according to real element. """ if self.eval_method == ['grad']: val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0)) return val elif self.eval_method == ['val']: return self.bfref elif self.eval_method == ['div']: val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0)) val = nm.atleast_3d(nm.einsum('ijkk', val)) return val elif self.eval_method == ['grad', 'sym', 'Man']: val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0)) from sfepy.terms.terms_general import proceed_methods val = proceed_methods(val, self.eval_method[1:]) return val else: msg = "Improper method '%s' for evaluation of basis functions" \ % (self.eval_method) raise NotImplementedError(msg) class H1DiscontinuousField(H1NodalMixin, VolumeField): family_name = 'volume_H1_lagrange_discontinuous' def _setup_approximations(self): self.aps = {} self.aps_by_name = {} for ig in self.igs: name = self.interp.name + '_%s_ig%d' % (self.region.name, ig) ap = fea.DiscontinuousApproximation(name, self.interp, self.region, ig) self.aps[ig] = ap self.aps_by_name[ap.name] = ap def _setup_global_base(self): """ Setup global DOF/base function indices and connectivity of the field. """ self._setup_facet_orientations() self._init_econn() n_dof = 0 all_dofs = {} remaps = {} for ig, ap in self.aps.iteritems(): ii = self.region.get_cells(ig) nd = nm.prod(ap.econn.shape) group = self.domain.groups[ig] remaps[ig] = prepare_remap(ii, group.shape.n_el) aux = nm.arange(n_dof, n_dof + nd, dtype=nm.int32) aux.shape = ap.econn.shape ap.econn[:] = aux all_dofs[ig] = aux n_dof += nd self.n_nod = n_dof self.n_bubble_dof = n_dof self.bubble_dofs = all_dofs self.bubble_remaps = remaps self.n_vertex_dof = self.n_edge_dof = self.n_face_dof = 0 self._setup_esurface() def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if self.approx_order != 0: dofs = self.average_to_vertices(dofs) new_dofs = FEField.extend_dofs(self, dofs) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: dofs = self.average_to_vertices(dofs) new_dofs =
FEField.remove_extra_dofs(self, dofs)
sfepy.discrete.fem.fields_base.FEField.remove_extra_dofs
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ import time import numpy as nm from sfepy.base.base import output, assert_ import fea from sfepy.discrete.fem.utils import prepare_remap from sfepy.discrete.common.dof_info import expand_nodes_to_dofs from sfepy.discrete.fem.global_interp import get_ref_coors from sfepy.discrete.fem.facets import get_facet_dof_permutations from sfepy.discrete.fem.fields_base import (FEField, VolumeField, SurfaceField, H1Mixin) from sfepy.discrete.fem.extmods.bases import evaluate_in_rc class H1NodalMixin(H1Mixin): def _setup_facet_orientations(self): order = self.approx_order self.node_desc = self.interp.describe_nodes() edge_nodes = self.node_desc.edge_nodes if edge_nodes is not None: n_fp = self.gel.edges.shape[1] self.edge_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) face_nodes = self.node_desc.face_nodes if face_nodes is not None: n_fp = self.gel.faces.shape[1] self.face_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) def _setup_edge_dofs(self): """ Setup edge DOF connectivity. """ if self.node_desc.edge is None: return 0, None, None return self._setup_facet_dofs(1, self.node_desc.edge, self.edge_dof_perms, self.n_vertex_dof) def _setup_face_dofs(self): """ Setup face DOF connectivity. """ if self.node_desc.face is None: return 0, None, None return self._setup_facet_dofs(self.domain.shape.tdim - 1, self.node_desc.face, self.face_dof_perms, self.n_vertex_dof + self.n_edge_dof) def _setup_facet_dofs(self, dim, facet_desc, facet_perms, offset): """ Helper function to setup facet DOF connectivity, works for both edges and faces. """ facet_desc = nm.array(facet_desc) n_dof_per_facet = facet_desc.shape[1] cmesh = self.domain.cmesh facets = self.region.entities[dim] ii = nm.arange(facets.shape[0], dtype=nm.int32) all_dofs = offset +
expand_nodes_to_dofs(ii, n_dof_per_facet)
sfepy.discrete.common.dof_info.expand_nodes_to_dofs
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ import time import numpy as nm from sfepy.base.base import output, assert_ import fea from sfepy.discrete.fem.utils import prepare_remap from sfepy.discrete.common.dof_info import expand_nodes_to_dofs from sfepy.discrete.fem.global_interp import get_ref_coors from sfepy.discrete.fem.facets import get_facet_dof_permutations from sfepy.discrete.fem.fields_base import (FEField, VolumeField, SurfaceField, H1Mixin) from sfepy.discrete.fem.extmods.bases import evaluate_in_rc class H1NodalMixin(H1Mixin): def _setup_facet_orientations(self): order = self.approx_order self.node_desc = self.interp.describe_nodes() edge_nodes = self.node_desc.edge_nodes if edge_nodes is not None: n_fp = self.gel.edges.shape[1] self.edge_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) face_nodes = self.node_desc.face_nodes if face_nodes is not None: n_fp = self.gel.faces.shape[1] self.face_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) def _setup_edge_dofs(self): """ Setup edge DOF connectivity. """ if self.node_desc.edge is None: return 0, None, None return self._setup_facet_dofs(1, self.node_desc.edge, self.edge_dof_perms, self.n_vertex_dof) def _setup_face_dofs(self): """ Setup face DOF connectivity. """ if self.node_desc.face is None: return 0, None, None return self._setup_facet_dofs(self.domain.shape.tdim - 1, self.node_desc.face, self.face_dof_perms, self.n_vertex_dof + self.n_edge_dof) def _setup_facet_dofs(self, dim, facet_desc, facet_perms, offset): """ Helper function to setup facet DOF connectivity, works for both edges and faces. """ facet_desc = nm.array(facet_desc) n_dof_per_facet = facet_desc.shape[1] cmesh = self.domain.cmesh facets = self.region.entities[dim] ii = nm.arange(facets.shape[0], dtype=nm.int32) all_dofs = offset + expand_nodes_to_dofs(ii, n_dof_per_facet) # Prepare global facet id remapping to field-local numbering. remap = prepare_remap(facets, cmesh.num[dim]) cconn = self.region.domain.cmesh.get_conn(self.region.tdim, dim) offs = cconn.offsets n_f = self.gel.edges.shape[0] if dim == 1 else self.gel.faces.shape[0] oris = cmesh.get_orientations(dim) for ig, ap in self.aps.iteritems(): gcells = self.region.get_cells(ig, offset=False) n_el = gcells.shape[0] indices = cconn.indices[offs[gcells[0]]:offs[gcells[-1]+1]] facets_of_cells = remap[indices] ori = oris[offs[gcells[0]]:offs[gcells[-1]+1]] perms = facet_perms[ig][ori] # Define global facet dof numbers. gdofs = offset + expand_nodes_to_dofs(facets_of_cells, n_dof_per_facet) # Elements of facets. iel = nm.arange(n_el, dtype=nm.int32).repeat(n_f) ies = nm.tile(nm.arange(n_f, dtype=nm.int32), n_el) # DOF columns in econn for each facet. iep = facet_desc[ies] iaux = nm.arange(gdofs.shape[0], dtype=nm.int32) ap.econn[iel[:, None], iep] = gdofs[iaux[:, None], perms] n_dof = n_dof_per_facet * facets.shape[0] assert_(n_dof == nm.prod(all_dofs.shape)) return n_dof, all_dofs, remap def _setup_bubble_dofs(self): """ Setup bubble DOF connectivity. """ if self.node_desc.bubble is None: return 0, None, None offset = self.n_vertex_dof + self.n_edge_dof + self.n_face_dof n_dof = 0 n_dof_per_cell = self.node_desc.bubble.shape[0] all_dofs = {} remaps = {} for ig, ap in self.aps.iteritems(): ii = self.region.get_cells(ig) n_cell = ii.shape[0] nd = n_dof_per_cell * n_cell group = self.domain.groups[ig] remaps[ig] =
prepare_remap(ii, group.shape.n_el)
sfepy.discrete.fem.utils.prepare_remap
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ import time import numpy as nm from sfepy.base.base import output, assert_ import fea from sfepy.discrete.fem.utils import prepare_remap from sfepy.discrete.common.dof_info import expand_nodes_to_dofs from sfepy.discrete.fem.global_interp import get_ref_coors from sfepy.discrete.fem.facets import get_facet_dof_permutations from sfepy.discrete.fem.fields_base import (FEField, VolumeField, SurfaceField, H1Mixin) from sfepy.discrete.fem.extmods.bases import evaluate_in_rc class H1NodalMixin(H1Mixin): def _setup_facet_orientations(self): order = self.approx_order self.node_desc = self.interp.describe_nodes() edge_nodes = self.node_desc.edge_nodes if edge_nodes is not None: n_fp = self.gel.edges.shape[1] self.edge_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) face_nodes = self.node_desc.face_nodes if face_nodes is not None: n_fp = self.gel.faces.shape[1] self.face_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) def _setup_edge_dofs(self): """ Setup edge DOF connectivity. """ if self.node_desc.edge is None: return 0, None, None return self._setup_facet_dofs(1, self.node_desc.edge, self.edge_dof_perms, self.n_vertex_dof) def _setup_face_dofs(self): """ Setup face DOF connectivity. """ if self.node_desc.face is None: return 0, None, None return self._setup_facet_dofs(self.domain.shape.tdim - 1, self.node_desc.face, self.face_dof_perms, self.n_vertex_dof + self.n_edge_dof) def _setup_facet_dofs(self, dim, facet_desc, facet_perms, offset): """ Helper function to setup facet DOF connectivity, works for both edges and faces. """ facet_desc = nm.array(facet_desc) n_dof_per_facet = facet_desc.shape[1] cmesh = self.domain.cmesh facets = self.region.entities[dim] ii = nm.arange(facets.shape[0], dtype=nm.int32) all_dofs = offset + expand_nodes_to_dofs(ii, n_dof_per_facet) # Prepare global facet id remapping to field-local numbering. remap = prepare_remap(facets, cmesh.num[dim]) cconn = self.region.domain.cmesh.get_conn(self.region.tdim, dim) offs = cconn.offsets n_f = self.gel.edges.shape[0] if dim == 1 else self.gel.faces.shape[0] oris = cmesh.get_orientations(dim) for ig, ap in self.aps.iteritems(): gcells = self.region.get_cells(ig, offset=False) n_el = gcells.shape[0] indices = cconn.indices[offs[gcells[0]]:offs[gcells[-1]+1]] facets_of_cells = remap[indices] ori = oris[offs[gcells[0]]:offs[gcells[-1]+1]] perms = facet_perms[ig][ori] # Define global facet dof numbers. gdofs = offset + expand_nodes_to_dofs(facets_of_cells, n_dof_per_facet) # Elements of facets. iel = nm.arange(n_el, dtype=nm.int32).repeat(n_f) ies = nm.tile(nm.arange(n_f, dtype=nm.int32), n_el) # DOF columns in econn for each facet. iep = facet_desc[ies] iaux = nm.arange(gdofs.shape[0], dtype=nm.int32) ap.econn[iel[:, None], iep] = gdofs[iaux[:, None], perms] n_dof = n_dof_per_facet * facets.shape[0] assert_(n_dof == nm.prod(all_dofs.shape)) return n_dof, all_dofs, remap def _setup_bubble_dofs(self): """ Setup bubble DOF connectivity. """ if self.node_desc.bubble is None: return 0, None, None offset = self.n_vertex_dof + self.n_edge_dof + self.n_face_dof n_dof = 0 n_dof_per_cell = self.node_desc.bubble.shape[0] all_dofs = {} remaps = {} for ig, ap in self.aps.iteritems(): ii = self.region.get_cells(ig) n_cell = ii.shape[0] nd = n_dof_per_cell * n_cell group = self.domain.groups[ig] remaps[ig] = prepare_remap(ii, group.shape.n_el) aux = nm.arange(offset + n_dof, offset + n_dof + nd, dtype=nm.int32) aux.shape = (n_cell, n_dof_per_cell) iep = self.node_desc.bubble[0] ap.econn[:,iep:] = aux all_dofs[ig] = aux n_dof += nd return n_dof, all_dofs, remaps def set_dofs(self, fun=0.0, region=None, dpn=None, warn=None): """ Set the values of DOFs in a given region using a function of space coordinates or value `fun`. """ if region is None: region = self.region if dpn is None: dpn = self.n_components aux = self.get_dofs_in_region(region, clean=True, warn=warn) nods = nm.unique(nm.hstack(aux)) if callable(fun): vals = fun(self.get_coor(nods)) elif nm.isscalar(fun): vals = nm.repeat([fun], nods.shape[0] * dpn) elif isinstance(fun, nm.ndarray): assert_(len(fun) == dpn) vals = nm.repeat(fun, nods.shape[0]) else: raise ValueError('unknown function/value type! (%s)' % type(fun)) return nods, vals def evaluate_at(self, coors, source_vals, strategy='kdtree', close_limit=0.1, cache=None, ret_cells=False, ret_status=False, ret_ref_coors=False, verbose=True): """ Evaluate source DOF values corresponding to the field in the given coordinates using the field interpolation. Parameters ---------- coors : array The coordinates the source values should be interpolated into. source_vals : array The source DOF values corresponding to the field. strategy : str, optional The strategy for finding the elements that contain the coordinates. Only 'kdtree' is supported for the moment. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh, the inverse connectivity of the field mesh and the KDTree instance can be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and `cache.kdtree`. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the KDTree related data are ignored. ret_cells : bool, optional If True, return also the cell indices the coordinates are in. ret_status : bool, optional If True, return also the status for each point: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure. ret_ref_coors : bool, optional If True, return also the found reference element coordinates. verbose : bool If False, reduce verbosity. Returns ------- vals : array The interpolated values. cells : array The cell indices, if `ret_cells` or `ret_status` are True. status : array The status, if `ret_status` is True. """ output('evaluating in %d points...' % coors.shape[0], verbose=verbose) ref_coors, cells, status = get_ref_coors(self, coors, strategy=strategy, close_limit=close_limit, cache=cache, verbose=verbose) tt = time.clock() vertex_coorss, nodess, orders, mtx_is = [], [], [], [] conns = [] for ap in self.aps.itervalues(): ps = ap.interp.poly_spaces['v'] vertex_coorss.append(ps.geometry.coors) nodess.append(ps.nodes) mtx_is.append(ps.get_mtx_i()) orders.append(ps.order) conns.append(ap.econn) orders = nm.array(orders, dtype=nm.int32) # Interpolate to the reference coordinates. vals = nm.empty((coors.shape[0], source_vals.shape[1]), dtype=source_vals.dtype) evaluate_in_rc(vals, ref_coors, cells, status, source_vals, conns, vertex_coorss, nodess, orders, mtx_is, 1e-15) output('interpolation: %f s' % (time.clock()-tt),verbose=verbose) output('...done',verbose=verbose) if ret_ref_coors: return vals, ref_coors, cells, status elif ret_status: return vals, cells, status elif ret_cells: return vals, cells else: return vals class H1NodalVolumeField(H1NodalMixin, VolumeField): family_name = 'volume_H1_lagrange' def interp_v_vals_to_n_vals(self, vec): """ Interpolate a function defined by vertex DOF values using the FE geometry base (P1 or Q1) into the extra nodes, i.e. define the extra DOF values. """ if not self.node_desc.has_extra_nodes(): enod_vol_val = vec.copy() else: dim = vec.shape[1] enod_vol_val = nm.zeros((self.n_nod, dim), dtype=nm.float64) for ig, ap in self.aps.iteritems(): group = self.domain.groups[ig] econn = ap.econn coors = ap.interp.poly_spaces['v'].node_coors ginterp = ap.interp.gel.interp bf = ginterp.poly_spaces['v'].eval_base(coors) bf = bf[:,0,:].copy() evec = nm.dot(bf, vec[group.conn]) enod_vol_val[econn] = nm.swapaxes(evec, 0, 1) return enod_vol_val def set_basis(self, maps, methods): """ This function along with eval_basis supports the general term IntFE. It sets parameters and basis functions at reference element according to its method (val, grad, div, etc). Parameters ---------- maps : class It provides information about mapping between reference and real element. Quadrature points stored in maps.qp_coor are used here. method : list of string It stores methods for variable evaluation. At first position, there is one of val, grad, or div. self.bfref : numpy.array of shape = (n_qp, n_basis) + basis_shape An array that stores basis functions evaluated at quadrature points. Here n_qp is number of quadrature points, n_basis is number of basis functions, and basis_shape is a shape of basis function, i.e. (1,) for scalar-valued, (dim,) for vector-valued, (dim, dim) for matrix-valued, etc. Returns ------- self.bfref : numpy.array It stores a basis functions at quadrature points of shape according to proceeded methods. self.n_basis : int number of basis functions """ self.eval_method = methods def get_grad(maps, shape): bfref0 = eval_base(maps.qp_coor, diff=True).swapaxes(1, 2) if shape == (1,): # scalar variable bfref = bfref0 elif len(shape) == 1: # vector variable vec_shape = nm.array(bfref0.shape + shape) vec_shape[1] *= shape[0] bfref = nm.zeros(vec_shape) for ii in nm.arange(shape[0]): slc = slice(ii*bfref0.shape[1], (ii+1)*bfref0.shape[1]) bfref[:, slc, ii] = bfref0 else: # higher-order tensors variable msg = "Evaluation of basis has not been implemented \ for higher-order tensors yet." raise NotImplementedError(msg) return bfref def get_val(maps, shape): bfref0 = eval_base(maps.qp_coor, diff=False).swapaxes(1, 2) if self.shape == (1,): # scalar variable bfref = bfref0 elif len(shape) == 1: vec_shape = nm.array(bfref0.shape) vec_shape[1:3] *= shape[0] bfref = nm.zeros(vec_shape) for ii in nm.arange(shape[0]): slc = slice(ii*bfref0.shape[1], (ii+1)*bfref0.shape[1]) bfref[:, slc] = bfref0 else: # higher-order tensors variable msg = "Evaluation of basis has not been implemented \ for higher-order tensors yet." raise NotImplementedError(msg) return bfref eval_base = self.interp.poly_spaces['v'].eval_base if self.eval_method[0] == 'val': bfref = get_val(maps, self.shape) elif self.eval_method[0] == 'grad': bfref = get_grad(maps, self.shape) elif self.eval_method[0] == 'div': bfref = get_grad(maps, self.shape) else: raise NotImplementedError("The method '%s' is not implemented" \ % (self.eval_method)) self.bfref = bfref self.n_basis = self.bfref.shape[1] def eval_basis(self, maps): """ It returns basis functions evaluated at quadrature points and mapped at reference element according to real element. """ if self.eval_method == ['grad']: val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0)) return val elif self.eval_method == ['val']: return self.bfref elif self.eval_method == ['div']: val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0)) val = nm.atleast_3d(nm.einsum('ijkk', val)) return val elif self.eval_method == ['grad', 'sym', 'Man']: val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0)) from sfepy.terms.terms_general import proceed_methods val = proceed_methods(val, self.eval_method[1:]) return val else: msg = "Improper method '%s' for evaluation of basis functions" \ % (self.eval_method) raise NotImplementedError(msg) class H1DiscontinuousField(H1NodalMixin, VolumeField): family_name = 'volume_H1_lagrange_discontinuous' def _setup_approximations(self): self.aps = {} self.aps_by_name = {} for ig in self.igs: name = self.interp.name + '_%s_ig%d' % (self.region.name, ig) ap = fea.DiscontinuousApproximation(name, self.interp, self.region, ig) self.aps[ig] = ap self.aps_by_name[ap.name] = ap def _setup_global_base(self): """ Setup global DOF/base function indices and connectivity of the field. """ self._setup_facet_orientations() self._init_econn() n_dof = 0 all_dofs = {} remaps = {} for ig, ap in self.aps.iteritems(): ii = self.region.get_cells(ig) nd = nm.prod(ap.econn.shape) group = self.domain.groups[ig] remaps[ig] =
prepare_remap(ii, group.shape.n_el)
sfepy.discrete.fem.utils.prepare_remap
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ import time import numpy as nm from sfepy.base.base import output, assert_ import fea from sfepy.discrete.fem.utils import prepare_remap from sfepy.discrete.common.dof_info import expand_nodes_to_dofs from sfepy.discrete.fem.global_interp import get_ref_coors from sfepy.discrete.fem.facets import get_facet_dof_permutations from sfepy.discrete.fem.fields_base import (FEField, VolumeField, SurfaceField, H1Mixin) from sfepy.discrete.fem.extmods.bases import evaluate_in_rc class H1NodalMixin(H1Mixin): def _setup_facet_orientations(self): order = self.approx_order self.node_desc = self.interp.describe_nodes() edge_nodes = self.node_desc.edge_nodes if edge_nodes is not None: n_fp = self.gel.edges.shape[1] self.edge_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) face_nodes = self.node_desc.face_nodes if face_nodes is not None: n_fp = self.gel.faces.shape[1] self.face_dof_perms = get_facet_dof_permutations(n_fp, self.igs, order) def _setup_edge_dofs(self): """ Setup edge DOF connectivity. """ if self.node_desc.edge is None: return 0, None, None return self._setup_facet_dofs(1, self.node_desc.edge, self.edge_dof_perms, self.n_vertex_dof) def _setup_face_dofs(self): """ Setup face DOF connectivity. """ if self.node_desc.face is None: return 0, None, None return self._setup_facet_dofs(self.domain.shape.tdim - 1, self.node_desc.face, self.face_dof_perms, self.n_vertex_dof + self.n_edge_dof) def _setup_facet_dofs(self, dim, facet_desc, facet_perms, offset): """ Helper function to setup facet DOF connectivity, works for both edges and faces. """ facet_desc = nm.array(facet_desc) n_dof_per_facet = facet_desc.shape[1] cmesh = self.domain.cmesh facets = self.region.entities[dim] ii = nm.arange(facets.shape[0], dtype=nm.int32) all_dofs = offset + expand_nodes_to_dofs(ii, n_dof_per_facet) # Prepare global facet id remapping to field-local numbering. remap = prepare_remap(facets, cmesh.num[dim]) cconn = self.region.domain.cmesh.get_conn(self.region.tdim, dim) offs = cconn.offsets n_f = self.gel.edges.shape[0] if dim == 1 else self.gel.faces.shape[0] oris = cmesh.get_orientations(dim) for ig, ap in self.aps.iteritems(): gcells = self.region.get_cells(ig, offset=False) n_el = gcells.shape[0] indices = cconn.indices[offs[gcells[0]]:offs[gcells[-1]+1]] facets_of_cells = remap[indices] ori = oris[offs[gcells[0]]:offs[gcells[-1]+1]] perms = facet_perms[ig][ori] # Define global facet dof numbers. gdofs = offset + expand_nodes_to_dofs(facets_of_cells, n_dof_per_facet) # Elements of facets. iel = nm.arange(n_el, dtype=nm.int32).repeat(n_f) ies = nm.tile(nm.arange(n_f, dtype=nm.int32), n_el) # DOF columns in econn for each facet. iep = facet_desc[ies] iaux = nm.arange(gdofs.shape[0], dtype=nm.int32) ap.econn[iel[:, None], iep] = gdofs[iaux[:, None], perms] n_dof = n_dof_per_facet * facets.shape[0] assert_(n_dof == nm.prod(all_dofs.shape)) return n_dof, all_dofs, remap def _setup_bubble_dofs(self): """ Setup bubble DOF connectivity. """ if self.node_desc.bubble is None: return 0, None, None offset = self.n_vertex_dof + self.n_edge_dof + self.n_face_dof n_dof = 0 n_dof_per_cell = self.node_desc.bubble.shape[0] all_dofs = {} remaps = {} for ig, ap in self.aps.iteritems(): ii = self.region.get_cells(ig) n_cell = ii.shape[0] nd = n_dof_per_cell * n_cell group = self.domain.groups[ig] remaps[ig] = prepare_remap(ii, group.shape.n_el) aux = nm.arange(offset + n_dof, offset + n_dof + nd, dtype=nm.int32) aux.shape = (n_cell, n_dof_per_cell) iep = self.node_desc.bubble[0] ap.econn[:,iep:] = aux all_dofs[ig] = aux n_dof += nd return n_dof, all_dofs, remaps def set_dofs(self, fun=0.0, region=None, dpn=None, warn=None): """ Set the values of DOFs in a given region using a function of space coordinates or value `fun`. """ if region is None: region = self.region if dpn is None: dpn = self.n_components aux = self.get_dofs_in_region(region, clean=True, warn=warn) nods = nm.unique(nm.hstack(aux)) if callable(fun): vals = fun(self.get_coor(nods)) elif nm.isscalar(fun): vals = nm.repeat([fun], nods.shape[0] * dpn) elif isinstance(fun, nm.ndarray): assert_(len(fun) == dpn) vals = nm.repeat(fun, nods.shape[0]) else: raise ValueError('unknown function/value type! (%s)' % type(fun)) return nods, vals def evaluate_at(self, coors, source_vals, strategy='kdtree', close_limit=0.1, cache=None, ret_cells=False, ret_status=False, ret_ref_coors=False, verbose=True): """ Evaluate source DOF values corresponding to the field in the given coordinates using the field interpolation. Parameters ---------- coors : array The coordinates the source values should be interpolated into. source_vals : array The source DOF values corresponding to the field. strategy : str, optional The strategy for finding the elements that contain the coordinates. Only 'kdtree' is supported for the moment. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh, the inverse connectivity of the field mesh and the KDTree instance can be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and `cache.kdtree`. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the KDTree related data are ignored. ret_cells : bool, optional If True, return also the cell indices the coordinates are in. ret_status : bool, optional If True, return also the status for each point: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure. ret_ref_coors : bool, optional If True, return also the found reference element coordinates. verbose : bool If False, reduce verbosity. Returns ------- vals : array The interpolated values. cells : array The cell indices, if `ret_cells` or `ret_status` are True. status : array The status, if `ret_status` is True. """ output('evaluating in %d points...' % coors.shape[0], verbose=verbose) ref_coors, cells, status = get_ref_coors(self, coors, strategy=strategy, close_limit=close_limit, cache=cache, verbose=verbose) tt = time.clock() vertex_coorss, nodess, orders, mtx_is = [], [], [], [] conns = [] for ap in self.aps.itervalues(): ps = ap.interp.poly_spaces['v'] vertex_coorss.append(ps.geometry.coors) nodess.append(ps.nodes) mtx_is.append(ps.get_mtx_i()) orders.append(ps.order) conns.append(ap.econn) orders = nm.array(orders, dtype=nm.int32) # Interpolate to the reference coordinates. vals = nm.empty((coors.shape[0], source_vals.shape[1]), dtype=source_vals.dtype) evaluate_in_rc(vals, ref_coors, cells, status, source_vals, conns, vertex_coorss, nodess, orders, mtx_is, 1e-15) output('interpolation: %f s' % (time.clock()-tt),verbose=verbose) output('...done',verbose=verbose) if ret_ref_coors: return vals, ref_coors, cells, status elif ret_status: return vals, cells, status elif ret_cells: return vals, cells else: return vals class H1NodalVolumeField(H1NodalMixin, VolumeField): family_name = 'volume_H1_lagrange' def interp_v_vals_to_n_vals(self, vec): """ Interpolate a function defined by vertex DOF values using the FE geometry base (P1 or Q1) into the extra nodes, i.e. define the extra DOF values. """ if not self.node_desc.has_extra_nodes(): enod_vol_val = vec.copy() else: dim = vec.shape[1] enod_vol_val = nm.zeros((self.n_nod, dim), dtype=nm.float64) for ig, ap in self.aps.iteritems(): group = self.domain.groups[ig] econn = ap.econn coors = ap.interp.poly_spaces['v'].node_coors ginterp = ap.interp.gel.interp bf = ginterp.poly_spaces['v'].eval_base(coors) bf = bf[:,0,:].copy() evec = nm.dot(bf, vec[group.conn]) enod_vol_val[econn] = nm.swapaxes(evec, 0, 1) return enod_vol_val def set_basis(self, maps, methods): """ This function along with eval_basis supports the general term IntFE. It sets parameters and basis functions at reference element according to its method (val, grad, div, etc). Parameters ---------- maps : class It provides information about mapping between reference and real element. Quadrature points stored in maps.qp_coor are used here. method : list of string It stores methods for variable evaluation. At first position, there is one of val, grad, or div. self.bfref : numpy.array of shape = (n_qp, n_basis) + basis_shape An array that stores basis functions evaluated at quadrature points. Here n_qp is number of quadrature points, n_basis is number of basis functions, and basis_shape is a shape of basis function, i.e. (1,) for scalar-valued, (dim,) for vector-valued, (dim, dim) for matrix-valued, etc. Returns ------- self.bfref : numpy.array It stores a basis functions at quadrature points of shape according to proceeded methods. self.n_basis : int number of basis functions """ self.eval_method = methods def get_grad(maps, shape): bfref0 = eval_base(maps.qp_coor, diff=True).swapaxes(1, 2) if shape == (1,): # scalar variable bfref = bfref0 elif len(shape) == 1: # vector variable vec_shape = nm.array(bfref0.shape + shape) vec_shape[1] *= shape[0] bfref = nm.zeros(vec_shape) for ii in nm.arange(shape[0]): slc = slice(ii*bfref0.shape[1], (ii+1)*bfref0.shape[1]) bfref[:, slc, ii] = bfref0 else: # higher-order tensors variable msg = "Evaluation of basis has not been implemented \ for higher-order tensors yet." raise NotImplementedError(msg) return bfref def get_val(maps, shape): bfref0 = eval_base(maps.qp_coor, diff=False).swapaxes(1, 2) if self.shape == (1,): # scalar variable bfref = bfref0 elif len(shape) == 1: vec_shape = nm.array(bfref0.shape) vec_shape[1:3] *= shape[0] bfref = nm.zeros(vec_shape) for ii in nm.arange(shape[0]): slc = slice(ii*bfref0.shape[1], (ii+1)*bfref0.shape[1]) bfref[:, slc] = bfref0 else: # higher-order tensors variable msg = "Evaluation of basis has not been implemented \ for higher-order tensors yet." raise NotImplementedError(msg) return bfref eval_base = self.interp.poly_spaces['v'].eval_base if self.eval_method[0] == 'val': bfref = get_val(maps, self.shape) elif self.eval_method[0] == 'grad': bfref = get_grad(maps, self.shape) elif self.eval_method[0] == 'div': bfref = get_grad(maps, self.shape) else: raise NotImplementedError("The method '%s' is not implemented" \ % (self.eval_method)) self.bfref = bfref self.n_basis = self.bfref.shape[1] def eval_basis(self, maps): """ It returns basis functions evaluated at quadrature points and mapped at reference element according to real element. """ if self.eval_method == ['grad']: val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0)) return val elif self.eval_method == ['val']: return self.bfref elif self.eval_method == ['div']: val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0)) val = nm.atleast_3d(nm.einsum('ijkk', val)) return val elif self.eval_method == ['grad', 'sym', 'Man']: val = nm.tensordot(self.bfref, maps.inv_jac, axes=(-1, 0)) from sfepy.terms.terms_general import proceed_methods val =
proceed_methods(val, self.eval_method[1:])
sfepy.terms.terms_general.proceed_methods
#!/usr/bin/env python import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.fem import Mesh from sfepy.fem.meshio import io_table, supported_capabilities usage = """%prog [options] filename_in filename_out Convert a mesh file from one SfePy-supported format to another. Examples: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 """ help = { 'scale' : 'scale factor [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported writable output mesh formats', } def output_writable_meshes():
output('Supported writable mesh formats are:')
sfepy.base.base.output
#!/usr/bin/env python import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.fem import Mesh from sfepy.fem.meshio import io_table, supported_capabilities usage = """%prog [options] filename_in filename_out Convert a mesh file from one SfePy-supported format to another. Examples: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 """ help = { 'scale' : 'scale factor [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported writable output mesh formats', } def output_writable_meshes(): output('Supported writable mesh formats are:') for key, val in
supported_capabilities.iteritems()
sfepy.fem.meshio.supported_capabilities.iteritems
#!/usr/bin/env python import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.fem import Mesh from sfepy.fem.meshio import io_table, supported_capabilities usage = """%prog [options] filename_in filename_out Convert a mesh file from one SfePy-supported format to another. Examples: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 """ help = { 'scale' : 'scale factor [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported writable output mesh formats', } def output_writable_meshes(): output('Supported writable mesh formats are:') for key, val in supported_capabilities.iteritems(): if 'w' in val: output(key) def main(): parser = OptionParser(usage=usage) parser.add_option("-s", "--scale", metavar='scale', action="store", dest="scale", default=None, help=help['scale']) parser.add_option("-f", "--format", metavar='format', action="store", type='string', dest="format", default=None, help=help['format']) parser.add_option("-l", "--list", action="store_true", dest="list", help=help['list']) (options, args) = parser.parse_args() if options.list: output_writable_meshes() sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = options.scale if scale is not None: try: try: scale = float(scale) except ValueError: scale = [float(ii) for ii in scale.split(',')] scale = nm.array(scale, dtype=nm.float64, ndmin=1) except: output('bad scale! (%s)' % scale) parser.print_help() sys.exit(1) filename_in, filename_out = args mesh =
Mesh.from_file(filename_in)
sfepy.fem.Mesh.from_file
#!/usr/bin/env python import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.fem import Mesh from sfepy.fem.meshio import io_table, supported_capabilities usage = """%prog [options] filename_in filename_out Convert a mesh file from one SfePy-supported format to another. Examples: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 """ help = { 'scale' : 'scale factor [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported writable output mesh formats', } def output_writable_meshes(): output('Supported writable mesh formats are:') for key, val in supported_capabilities.iteritems(): if 'w' in val: output(key) def main(): parser = OptionParser(usage=usage) parser.add_option("-s", "--scale", metavar='scale', action="store", dest="scale", default=None, help=help['scale']) parser.add_option("-f", "--format", metavar='format', action="store", type='string', dest="format", default=None, help=help['format']) parser.add_option("-l", "--list", action="store_true", dest="list", help=help['list']) (options, args) = parser.parse_args() if options.list: output_writable_meshes() sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = options.scale if scale is not None: try: try: scale = float(scale) except ValueError: scale = [float(ii) for ii in scale.split(',')] scale = nm.array(scale, dtype=nm.float64, ndmin=1) except: output('bad scale! (%s)' % scale) parser.print_help() sys.exit(1) filename_in, filename_out = args mesh = Mesh.from_file(filename_in) if scale is not None: if len(scale) == 1: tr = nm.eye(mesh.dim, dtype=nm.float64) * scale elif len(scale) == mesh.dim: tr = nm.diag(scale) else: raise ValueError('bad scale! (%s)' % scale) mesh.transform_coors(tr) io = 'auto' if options.format: try: io = io_table[options.format](filename_out) except KeyError: output('unknown output mesh format! (%s)' % options.format) output_writable_meshes() sys.exit(1) if 'w' not in supported_capabilities[options.format]: output('write support not implemented for output mesh format! (%s)' % options.format) output_writable_meshes() sys.exit(1)
output('writing %s...' % filename_out)
sfepy.base.base.output
#!/usr/bin/env python import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.fem import Mesh from sfepy.fem.meshio import io_table, supported_capabilities usage = """%prog [options] filename_in filename_out Convert a mesh file from one SfePy-supported format to another. Examples: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 """ help = { 'scale' : 'scale factor [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported writable output mesh formats', } def output_writable_meshes(): output('Supported writable mesh formats are:') for key, val in supported_capabilities.iteritems(): if 'w' in val: output(key) def main(): parser = OptionParser(usage=usage) parser.add_option("-s", "--scale", metavar='scale', action="store", dest="scale", default=None, help=help['scale']) parser.add_option("-f", "--format", metavar='format', action="store", type='string', dest="format", default=None, help=help['format']) parser.add_option("-l", "--list", action="store_true", dest="list", help=help['list']) (options, args) = parser.parse_args() if options.list: output_writable_meshes() sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = options.scale if scale is not None: try: try: scale = float(scale) except ValueError: scale = [float(ii) for ii in scale.split(',')] scale = nm.array(scale, dtype=nm.float64, ndmin=1) except: output('bad scale! (%s)' % scale) parser.print_help() sys.exit(1) filename_in, filename_out = args mesh = Mesh.from_file(filename_in) if scale is not None: if len(scale) == 1: tr = nm.eye(mesh.dim, dtype=nm.float64) * scale elif len(scale) == mesh.dim: tr = nm.diag(scale) else: raise ValueError('bad scale! (%s)' % scale) mesh.transform_coors(tr) io = 'auto' if options.format: try: io = io_table[options.format](filename_out) except KeyError: output('unknown output mesh format! (%s)' % options.format) output_writable_meshes() sys.exit(1) if 'w' not in supported_capabilities[options.format]: output('write support not implemented for output mesh format! (%s)' % options.format) output_writable_meshes() sys.exit(1) output('writing %s...' % filename_out) mesh.write(filename_out, io=io)
output('...done')
sfepy.base.base.output
#!/usr/bin/env python import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.fem import Mesh from sfepy.fem.meshio import io_table, supported_capabilities usage = """%prog [options] filename_in filename_out Convert a mesh file from one SfePy-supported format to another. Examples: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 """ help = { 'scale' : 'scale factor [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported writable output mesh formats', } def output_writable_meshes(): output('Supported writable mesh formats are:') for key, val in supported_capabilities.iteritems(): if 'w' in val:
output(key)
sfepy.base.base.output
#!/usr/bin/env python import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.fem import Mesh from sfepy.fem.meshio import io_table, supported_capabilities usage = """%prog [options] filename_in filename_out Convert a mesh file from one SfePy-supported format to another. Examples: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 """ help = { 'scale' : 'scale factor [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported writable output mesh formats', } def output_writable_meshes(): output('Supported writable mesh formats are:') for key, val in supported_capabilities.iteritems(): if 'w' in val: output(key) def main(): parser = OptionParser(usage=usage) parser.add_option("-s", "--scale", metavar='scale', action="store", dest="scale", default=None, help=help['scale']) parser.add_option("-f", "--format", metavar='format', action="store", type='string', dest="format", default=None, help=help['format']) parser.add_option("-l", "--list", action="store_true", dest="list", help=help['list']) (options, args) = parser.parse_args() if options.list: output_writable_meshes() sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = options.scale if scale is not None: try: try: scale = float(scale) except ValueError: scale = [float(ii) for ii in scale.split(',')] scale =
nm.array(scale, dtype=nm.float64, ndmin=1)
sfepy.base.base.nm.array
#!/usr/bin/env python import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.fem import Mesh from sfepy.fem.meshio import io_table, supported_capabilities usage = """%prog [options] filename_in filename_out Convert a mesh file from one SfePy-supported format to another. Examples: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 """ help = { 'scale' : 'scale factor [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported writable output mesh formats', } def output_writable_meshes(): output('Supported writable mesh formats are:') for key, val in supported_capabilities.iteritems(): if 'w' in val: output(key) def main(): parser = OptionParser(usage=usage) parser.add_option("-s", "--scale", metavar='scale', action="store", dest="scale", default=None, help=help['scale']) parser.add_option("-f", "--format", metavar='format', action="store", type='string', dest="format", default=None, help=help['format']) parser.add_option("-l", "--list", action="store_true", dest="list", help=help['list']) (options, args) = parser.parse_args() if options.list: output_writable_meshes() sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = options.scale if scale is not None: try: try: scale = float(scale) except ValueError: scale = [float(ii) for ii in scale.split(',')] scale = nm.array(scale, dtype=nm.float64, ndmin=1) except:
output('bad scale! (%s)' % scale)
sfepy.base.base.output
#!/usr/bin/env python import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.fem import Mesh from sfepy.fem.meshio import io_table, supported_capabilities usage = """%prog [options] filename_in filename_out Convert a mesh file from one SfePy-supported format to another. Examples: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 """ help = { 'scale' : 'scale factor [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported writable output mesh formats', } def output_writable_meshes(): output('Supported writable mesh formats are:') for key, val in supported_capabilities.iteritems(): if 'w' in val: output(key) def main(): parser = OptionParser(usage=usage) parser.add_option("-s", "--scale", metavar='scale', action="store", dest="scale", default=None, help=help['scale']) parser.add_option("-f", "--format", metavar='format', action="store", type='string', dest="format", default=None, help=help['format']) parser.add_option("-l", "--list", action="store_true", dest="list", help=help['list']) (options, args) = parser.parse_args() if options.list: output_writable_meshes() sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = options.scale if scale is not None: try: try: scale = float(scale) except ValueError: scale = [float(ii) for ii in scale.split(',')] scale = nm.array(scale, dtype=nm.float64, ndmin=1) except: output('bad scale! (%s)' % scale) parser.print_help() sys.exit(1) filename_in, filename_out = args mesh = Mesh.from_file(filename_in) if scale is not None: if len(scale) == 1: tr =
nm.eye(mesh.dim, dtype=nm.float64)
sfepy.base.base.nm.eye
#!/usr/bin/env python import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.fem import Mesh from sfepy.fem.meshio import io_table, supported_capabilities usage = """%prog [options] filename_in filename_out Convert a mesh file from one SfePy-supported format to another. Examples: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 """ help = { 'scale' : 'scale factor [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported writable output mesh formats', } def output_writable_meshes(): output('Supported writable mesh formats are:') for key, val in supported_capabilities.iteritems(): if 'w' in val: output(key) def main(): parser = OptionParser(usage=usage) parser.add_option("-s", "--scale", metavar='scale', action="store", dest="scale", default=None, help=help['scale']) parser.add_option("-f", "--format", metavar='format', action="store", type='string', dest="format", default=None, help=help['format']) parser.add_option("-l", "--list", action="store_true", dest="list", help=help['list']) (options, args) = parser.parse_args() if options.list: output_writable_meshes() sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = options.scale if scale is not None: try: try: scale = float(scale) except ValueError: scale = [float(ii) for ii in scale.split(',')] scale = nm.array(scale, dtype=nm.float64, ndmin=1) except: output('bad scale! (%s)' % scale) parser.print_help() sys.exit(1) filename_in, filename_out = args mesh = Mesh.from_file(filename_in) if scale is not None: if len(scale) == 1: tr = nm.eye(mesh.dim, dtype=nm.float64) * scale elif len(scale) == mesh.dim: tr =
nm.diag(scale)
sfepy.base.base.nm.diag
#!/usr/bin/env python import sys sys.path.append('.') from optparse import OptionParser from sfepy.base.base import nm, output from sfepy.fem import Mesh from sfepy.fem.meshio import io_table, supported_capabilities usage = """%prog [options] filename_in filename_out Convert a mesh file from one SfePy-supported format to another. Examples: $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s2.5 $ ./script/convert_mesh.py meshes/3d/cylinder.mesh new.vtk -s0.5,2,1 """ help = { 'scale' : 'scale factor [default: %default]', 'format' : 'output mesh format (overrides filename_out extension)', 'list' : 'list supported writable output mesh formats', } def output_writable_meshes(): output('Supported writable mesh formats are:') for key, val in supported_capabilities.iteritems(): if 'w' in val: output(key) def main(): parser = OptionParser(usage=usage) parser.add_option("-s", "--scale", metavar='scale', action="store", dest="scale", default=None, help=help['scale']) parser.add_option("-f", "--format", metavar='format', action="store", type='string', dest="format", default=None, help=help['format']) parser.add_option("-l", "--list", action="store_true", dest="list", help=help['list']) (options, args) = parser.parse_args() if options.list: output_writable_meshes() sys.exit(0) if len(args) != 2: parser.print_help() sys.exit(1) scale = options.scale if scale is not None: try: try: scale = float(scale) except ValueError: scale = [float(ii) for ii in scale.split(',')] scale = nm.array(scale, dtype=nm.float64, ndmin=1) except: output('bad scale! (%s)' % scale) parser.print_help() sys.exit(1) filename_in, filename_out = args mesh = Mesh.from_file(filename_in) if scale is not None: if len(scale) == 1: tr = nm.eye(mesh.dim, dtype=nm.float64) * scale elif len(scale) == mesh.dim: tr = nm.diag(scale) else: raise ValueError('bad scale! (%s)' % scale) mesh.transform_coors(tr) io = 'auto' if options.format: try: io = io_table[options.format](filename_out) except KeyError:
output('unknown output mesh format! (%s)' % options.format)
sfepy.base.base.output
#!/usr/bin/env python # This code was adapted from http://sfepy.org/doc-devel/mat_optim.html. """ Compare various elastic materials w.r.t. uniaxial tension/compression test. Requires Matplotlib. """ from __future__ import absolute_import from argparse import ArgumentParser, RawDescriptionHelpFormatter import sys import six sys.path.append('.') from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.discrete import Problem from sfepy.base.plotutils import plt from matplotlib.collections import PolyCollection from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import numpy as np from functools import partial def define( K=8.333, mu_nh=3.846, mu_mr=1.923, kappa=1.923, lam=5.769, mu=3.846 ): """Define the problem to solve.""" from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import stiffness_from_lame def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3', verbose=False) return mesh elif mode == 'write': pass filename_mesh =
UserMeshIO(mesh_hook)
sfepy.discrete.fem.meshio.UserMeshIO
#!/usr/bin/env python # This code was adapted from http://sfepy.org/doc-devel/mat_optim.html. """ Compare various elastic materials w.r.t. uniaxial tension/compression test. Requires Matplotlib. """ from __future__ import absolute_import from argparse import ArgumentParser, RawDescriptionHelpFormatter import sys import six sys.path.append('.') from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.discrete import Problem from sfepy.base.plotutils import plt from matplotlib.collections import PolyCollection from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import numpy as np from functools import partial def define( K=8.333, mu_nh=3.846, mu_mr=1.923, kappa=1.923, lam=5.769, mu=3.846 ): """Define the problem to solve.""" from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import stiffness_from_lame def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3', verbose=False) return mesh elif mode == 'write': pass filename_mesh = UserMeshIO(mesh_hook) options = { 'nls' : 'newton', 'ls' : 'ls', 'ts' : 'ts', 'save_times' : 'all', } functions = { 'linear_pressure' : (linear_pressure,), 'empty' : (lambda ts, coor, mode, region, ig: None,), } fields = { 'displacement' : ('real', 3, 'Omega', 1), } # Coefficients are chosen so that the tangent stiffness is the same for all # material for zero strains. materials = { 'solid' : ({ 'K' : K, # bulk modulus 'mu_nh' : mu_nh, # shear modulus of neoHookean term 'mu_mr' : mu_mr, # shear modulus of Mooney-Rivlin term 'kappa' : kappa, # second modulus of Mooney-Rivlin term # elasticity for LE term 'D' : stiffness_from_lame(dim=3, lam=lam, mu=mu), },), 'load' : 'empty', } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Bottom' : ('vertices in (z < 0.1)', 'facet'), 'Top' : ('vertices in (z > 2.9)', 'facet'), } ebcs = { 'fixb' : ('Bottom', {'u.all' : 0.0}), 'fixt' : ('Top', {'u.[0,1]' : 0.0}), } integrals = { 'i' : 1, 'isurf' : 2, } equations = { 'linear' : """dw_lin_elastic.i.Omega(solid.D, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'neo-Hookean' : """dw_tl_he_neohook.i.Omega(solid.mu_nh, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'Mooney-Rivlin' : """dw_tl_he_neohook.i.Omega(solid.mu_mr, v, u) + dw_tl_he_mooney_rivlin.i.Omega(solid.kappa, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 5, 'eps_a' : 1e-10, 'eps_r' : 1.0, }), 'ts' : ('ts.simple', { 't0' : 0, 't1' : 1, 'dt' : None, 'n_step' : 26, # has precedence over dt! 'verbose' : 1, }), } return locals() ## # Pressure tractions. def linear_pressure(ts, coor, mode=None, coef=1, **kwargs): if mode == 'qp': val = np.tile(coef * ts.step, (coor.shape[0], 1, 1)) return {'val' : val} def store_top_u(displacements): """Function _store() will be called at the end of each loading step. Top displacements will be stored into `displacements`.""" def _store(problem, ts, state): top = problem.domain.regions['Top'] top_u = problem.get_variables()['u'].get_state_in_region(top) displacements.append(np.mean(top_u[:,-1])) return _store def solve_branch(problem, branch_function, material_type): eq = problem.conf.equations[material_type] problem.set_equations({material_type : eq}) load = problem.get_materials()['load'] load.set_function(branch_function) out = [] problem.solve(save_results=False, step_hook=store_top_u(out)) displacements = np.array(out, dtype=np.float64) return displacements helps = { 'no_plot' : 'do not show plot window', } def plot_mesh(pb): # plot mesh for macro problem coors = pb.domain.mesh.coors graph = pb.domain.mesh.get_conn(pb.domain.mesh.descs[0]) fig2 =
plt.figure(figsize=(5,6))
sfepy.base.plotutils.plt.figure