def main(): import os import numpy as nm import matplotlib.pyplot as plt from sfepy.fem import MeshIO import sfepy.linalg as la from sfepy.mechanics.contact_bodies import (ContactPlane, plot_polygon, plot_points) conf_dir = os.path.dirname(__file__) io = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir) bb = io.read_bounding_box() outline = [vv for vv in la.combine(zip(*bb))] ax = plot_points(None, nm.array(outline), 'r*') for name in ['cp%d' % ii for ii in range(4)]: cpc = materials[name][0] cp = ContactPlane(cpc['.a'], cpc['.n'], cpc['.bs']) v1, v2 = la.get_perpendiculars(cp.normal) ax = plot_polygon(ax, cp.bounds) ax = plot_polygon( ax, nm.r_[cp.anchor[None, :], cp.anchor[None, :] + cp.normal[None, :]]) ax = plot_polygon(ax, nm.r_[cp.anchor[None, :], cp.anchor[None, :] + v1]) ax = plot_polygon(ax, nm.r_[cp.anchor[None, :], cp.anchor[None, :] + v2]) plt.show()
def main(): import os import numpy as nm import matplotlib.pyplot as plt from sfepy.fem import MeshIO import sfepy.linalg as la from sfepy.mechanics.contact_planes import (ContactPlane, plot_polygon, plot_points) conf_dir = os.path.dirname(__file__) io = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir) bb = io.read_bounding_box() outline = [vv for vv in la.combine(zip(*bb))] ax = plot_points(None, nm.array(outline), 'r*') for name in ['cp%d' % ii for ii in range(4)]: cpc = materials[name][0] cp = ContactPlane(cpc['.a'], cpc['.n'], cpc['.bs']) v1, v2 = la.get_perpendiculars(cp.normal) ax = plot_polygon(ax, cp.bounds) ax = plot_polygon(ax, nm.r_[cp.anchor[None, :], cp.anchor[None, :] + cp.normal[None, :]]) ax = plot_polygon(ax, nm.r_[cp.anchor[None, :], cp.anchor[None, :] + v1]) ax = plot_polygon(ax, nm.r_[cp.anchor[None, :], cp.anchor[None, :] + v2]) plt.show()
def main(): import os import numpy as nm import matplotlib.pyplot as plt from sfepy.fem import MeshIO import sfepy.linalg as la from sfepy.mechanics.contact_bodies import ContactSphere, plot_points conf_dir = os.path.dirname(__file__) io = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir) bb = io.read_bounding_box() outline = [vv for vv in la.combine(zip(*bb))] ax = plot_points(None, nm.array(outline), 'r*') csc = materials['cs'][0] cs = ContactSphere(csc['.c'], csc['.r']) pps = (bb[1] - bb[0]) * nm.random.rand(5000, 3) + bb[0] mask = cs.mask_points(pps, 0.0) ax = plot_points(ax, cs.centre[None, :], 'b*', ms=30) ax = plot_points(ax, pps[mask], 'kv') ax = plot_points(ax, pps[~mask], 'r.') plt.show()
def __init__(self, filename, approx, region_selects, mat_pars, options, evp_options, eigenmomenta_options, band_gaps_options, coefs_save_name='coefs', corrs_save_names=None, incwd=None, output_dir=None, **kwargs): Struct.__init__(self, approx=approx, region_selects=region_selects, mat_pars=mat_pars, options=options, evp_options=evp_options, eigenmomenta_options=eigenmomenta_options, band_gaps_options=band_gaps_options, **kwargs) self.incwd = get_default(incwd, lambda x: x) self.conf = Struct() self.conf.filename_mesh = self.incwd(filename) output_dir = get_default(output_dir, self.incwd('output')) default = {'evp' : 'evp', 'corrs_rs' : 'corrs_rs'} self.corrs_save_names = get_default(corrs_save_names, default) io = MeshIO.any_from_filename(self.conf.filename_mesh) self.bbox, self.dim = io.read_bounding_box(ret_dim=True) rpc_axes = nm.eye(self.dim, dtype=nm.float64) \ * (self.bbox[1] - self.bbox[0]) self.conf.options = options self.conf.options.update({ 'output_dir' : output_dir, 'volume' : { 'value' : get_lattice_volume(rpc_axes), }, 'coefs' : 'coefs', 'requirements' : 'requirements', 'coefs_filename' : coefs_save_name, }) self.conf.mat_pars = mat_pars self.conf.solvers = self.define_solvers() self.conf.regions = self.define_regions() self.conf.materials = self.define_materials() self.conf.fields = self.define_fields() self.conf.variables = self.define_variables() (self.conf.ebcs, self.conf.epbcs, self.conf.lcbcs, self.all_periodic) = self.define_bcs() self.conf.functions = self.define_functions() self.conf.integrals = self.define_integrals() self.equations, self.expr_coefs = self.define_equations() self.conf.coefs = self.define_coefs() self.conf.requirements = self.define_requirements()
def test_read_dimension( self ): from sfepy.fem import MeshIO meshes = {'database/tests/small2d.mesh' : 2, 'database/tests/small2d.vtk' : 2, 'database/tests/small3d.mesh' : 3, 'database/simple.mesh' : 3, 'database/simple.vtk' : 3} ok = True for filename, adim in meshes.iteritems(): self.report( 'mesh: %s, dimension %d' % (filename, adim) ) io = MeshIO.any_from_filename( filename ) dim = io.read_dimension() if dim != adim: self.report( 'read dimension %d -> failed' % dim ) ok = False else: self.report( 'read dimension %d -> ok' % dim ) return ok
def test_read_dimension( self ): from sfepy.fem import MeshIO meshes = {data_dir + '/meshes/various_formats/small2d.mesh' : 2, data_dir + '/meshes/various_formats/small2d.vtk' : 2, data_dir + '/meshes/various_formats/small3d.mesh' : 3} ok = True conf_dir = op.dirname(__file__) for filename, adim in meshes.iteritems(): self.report( 'mesh: %s, dimension %d' % (filename, adim) ) io = MeshIO.any_from_filename(filename, prefix_dir=conf_dir) dim = io.read_dimension() if dim != adim: self.report( 'read dimension %d -> failed' % dim ) ok = False else: self.report( 'read dimension %d -> ok' % dim ) return ok
def test_read_dimension(self): from sfepy.fem import MeshIO meshes = { data_dir + '/meshes/various_formats/small2d.mesh': 2, data_dir + '/meshes/various_formats/small2d.vtk': 2, data_dir + '/meshes/various_formats/small3d.mesh': 3 } ok = True conf_dir = op.dirname(__file__) for filename, adim in meshes.iteritems(): self.report('mesh: %s, dimension %d' % (filename, adim)) io = MeshIO.any_from_filename(filename, prefix_dir=conf_dir) dim = io.read_dimension() if dim != adim: self.report('read dimension %d -> failed' % dim) ok = False else: self.report('read dimension %d -> ok' % dim) return ok
def common(fun_v, mesh='../../tmp/mesh.vtk', n_eigs=5, tau=0.0): filename_mesh = mesh conf_dir = os.path.dirname(__file__) dim = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir).read_dimension() options = { 'save_eig_vectors' : None, 'n_eigs' : n_eigs, 'eigen_solver' : 'eigen1', } # Whole domain $Y$. region_1000 = { 'name' : 'Omega', 'select' : 'all', } # Domain $Y_2$. region_2 = { 'name' : 'Surface', 'select' : 'nodes of surface', } functions = { 'fun_v' : (fun_v,), } material_1 = { 'name' : 'm', 'values' : { 'val' : 0.5, }, } material_2 = { 'name' : 'mat_v', 'function' : 'fun_v', } field_0 = { 'name' : 'field_Psi', 'dtype' : 'real', 'shape' : 'scalar', 'region' : 'Omega', 'approx_order' : 1, } if dim == 3: quadr = "gauss_o2_d3" else: quadr = "gauss_o2_d2" integral_1 = { 'name' : 'i1', 'kind' : 'v', 'quadrature' : quadr, } variable_1 = { 'name' : 'Psi', 'kind' : 'unknown field', 'field' : 'field_Psi', 'order' : 0, } variable_2 = { 'name' : 'v', 'kind' : 'test field', 'field' : 'field_Psi', 'dual' : 'Psi', } variable_3 = { 'name' : 'V', 'kind' : 'parameter field', 'field' : 'field_Psi', 'like' : 'Psi', } ebc_1 = { 'name' : 'ZeroSurface', 'region' : 'Surface', 'dofs' : {'Psi.0' : 0.0}, } equations = { 'lhs' : """ dw_laplace.i1.Omega( m.val, v, Psi ) + dw_mass_scalar.i1.Omega( mat_v.V, v, Psi )""", 'rhs' : """dw_mass_scalar.i1.Omega( v, Psi )""", } solver_2 = { 'name' : 'eigen1', 'kind' : 'eig.pysparse', 'tau' : tau, 'eps_a' : 1e-10, 'i_max' : 150, 'method' : 'qmrs', 'verbosity' : 0, 'strategy' : 1, } return locals()
def generate_probes(filename_input, filename_results, options, conf=None, problem=None, probes=None, labels=None, probe_hooks=None): """ Generate probe figures and data files. """ if conf is None: required, other = get_standard_keywords() conf = ProblemConf.from_file(filename_input, required, other) opts = conf.options if options.auto_dir: output_dir = opts.get_('output_dir', '.') filename_results = os.path.join(output_dir, filename_results) output('results in: %s' % filename_results) io = MeshIO.any_from_filename(filename_results) step = options.step if options.step >= 0 else io.read_last_step() all_data = io.read_data(step) output('loaded:', all_data.keys()) output('from step:', step) if options.only_names is None: data = all_data else: data = {} for key, val in all_data.iteritems(): if key in options.only_names: data[key] = val if problem is None: problem = ProblemDefinition.from_conf(conf, init_equations=False, init_solvers=False) if probes is None: gen_probes = conf.get_function(conf.options.gen_probes) probes, labels = gen_probes(problem) if probe_hooks is None: probe_hooks = {None : conf.get_function(conf.options.probe_hook)} if options.output_filename_trunk is None: options.output_filename_trunk = problem.ofn_trunk filename_template = options.output_filename_trunk \ + ('_%%d.%s' % options.output_format) if options.same_dir: filename_template = os.path.join(os.path.dirname(filename_results), filename_template) output_dir = os.path.dirname(filename_results) for ip, probe in enumerate(probes): output(ip, probe.name) probe.set_options(close_limit=options.close_limit) for key, probe_hook in probe_hooks.iteritems(): out = probe_hook(data, probe, labels[ip], problem) if out is None: continue if isinstance(out, tuple): fig, results = out else: fig = out if key is not None: filename = filename_template % (key, ip) else: filename = filename_template % ip if fig is not None: if isinstance(fig, dict): for fig_name, fig_fig in fig.iteritems(): fig_filename = edit_filename(filename, suffix='_' + fig_name) fig_fig.savefig(fig_filename) output('figure ->', os.path.normpath(fig_filename)) else: fig.savefig(filename) output('figure ->', os.path.normpath(filename)) if results is not None: txt_filename = edit_filename(filename, new_ext='.txt') write_results(txt_filename, probe, results) output('data ->', os.path.normpath(txt_filename))
\;, \quad \forall s \;. The same values of :math:`p`, :math:`r` should be obtained. """ import os import numpy as nm from sfepy import data_dir from sfepy.fem import MeshIO filename_mesh = data_dir + '/meshes/3d/cylinder.mesh' #filename_mesh = data_dir + '/meshes/3d/cube_big_tetra.mesh' conf_dir = os.path.dirname(__file__) io = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir) bbox = io.read_bounding_box() dd = bbox[1] - bbox[0] xmin, ymin, zmin = bbox[0, :] + 1e-4 * dd xmax, ymax, zmax = bbox[1, :] - 1e-4 * dd def post_process(out, pb, state, extend=False): for vn in ['p', 'r']: try: dd = pb.evaluate('dw_new_diffusion.2.Omega(m.c, %s, %s)' % (vn, vn), verbose=False) print 'dw_new_diffusion', vn, dd
} material_3 = { 'name' : 'rigid', # lead, in 1e+10 Pa, does not matter 'values' : { 'lam' : 4.074 , 'mu' : 0.5556, 'density' : 1.1340, # in 1e4 kg/m3 }, 'flags' : {'special_constant' : True}, } conf_dir = os.path.dirname(__file__) dim = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir).read_dimension() field_0 = { 'name' : 'displacement_Y', 'dtype' : nm.float64, 'shape' : dim, 'region' : 'Y', 'approx_order' : 1, } field_1 = { 'name' : 'displacement_Y23', 'dtype' : nm.float64, 'shape' : dim, 'region' : 'Y23', 'approx_order' : 1,
= 0 \;, \quad \forall \ul{s} \;. The same values of :math:`\ul{u}`, :math:`\ul{r}` should be obtained. """ import os from sfepy import data_dir from sfepy.fem import MeshIO from sfepy.mechanics.matcoefs import stiffness_from_lame filename_mesh = data_dir + '/meshes/3d/cylinder.mesh' #filename_mesh = data_dir + '/meshes/3d/cube_medium_hexa.mesh' conf_dir = os.path.dirname(__file__) io = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir) bbox = io.read_bounding_box() dd = bbox[1] - bbox[0] xmin, ymin, zmin = bbox[0, :] + 1e-4 * dd xmax, ymax, zmax = bbox[1, :] - 1e-4 * dd def post_process(out, pb, state, extend=False): for vn in ['u', 'r']: try: val = pb.evaluate('dw_new_mass.2.Omega(%s, %s)' % (vn, vn), verbose=False) print 'dw_new_mass', vn, val
def generate_probes(filename_input, filename_results, options, conf=None, problem=None, probes=None, labels=None, probe_hooks=None): """Generate probe figures and data files.""" if conf is None: required, other = get_standard_keywords() conf = ProblemConf.from_file( filename_input, required, other ) opts = conf.options if options.auto_dir: output_dir = get_default_attr( opts, 'output_dir', '.' ) filename_results = os.path.join(output_dir, filename_results) output('results in: %s' % filename_results) io = MeshIO.any_from_filename(filename_results) all_data = io.read_data(options.step) output('loaded:', all_data.keys()) if options.only_names is None: data = all_data else: data = {} for key, val in all_data.iteritems(): if key in options.only_names: data[key] = val if problem is None: problem = ProblemDefinition.from_conf(conf, init_equations=False, init_solvers=False) if probes is None: gen_probes = getattr(conf.funmod, conf.options.gen_probes) probes, labels = gen_probes(problem) if probe_hooks is None: probe_hooks = {None : getattr(conf.funmod, conf.options.probe_hook)} if options.output_filename_trunk is None: options.output_filename_trunk = problem.ofn_trunk filename_template = options.output_filename_trunk \ + ('_%%d.%s' % options.output_format) if options.same_dir: filename_template = os.path.join(os.path.dirname(filename_results), filename_template) output_dir = os.path.dirname(filename_results) edit_pname = re.compile('[^a-zA-Z0-9-_.\[\]]').sub for ip, probe in enumerate(probes): output(ip, probe.name) for key, probe_hook in probe_hooks.iteritems(): out = probe_hook(data, probe, labels[ip], problem) if out is None: continue if isinstance(out, tuple): fig, results = out else: fig = out if key is not None: filename = filename_template % (key, ip) else: filename = filename_template % ip if fig is not None: fig.savefig(filename) output('figure ->', os.path.normpath(filename)) if results is not None: aux = os.path.splitext(filename)[0] txt_filename = aux + '.txt' fd = open(txt_filename, 'w') fd.write('\n'.join(probe.report()) + '\n') for key, res in results.iteritems(): pars, vals = res fd.write('\n# %s\n' % key) if vals.ndim == 1: aux = nm.hstack((pars[:,None], vals[:,None])) else: aux = nm.hstack((pars[:,None], vals)) nm.savetxt(fd, aux) fd.close() output('data ->', os.path.normpath(txt_filename))
'density' : 0.1142, # in 1e4 kg/m3 } material_3 = { 'name' : 'rigid', 'mode' : 'here', 'region' : 'Y3', # lead # 'lame' : {'lambda' : 0.1798, 'mu' : 0.148}, # in 1e+10 Pa 'lame' : {'lambda' : 4.074 , 'mu' : 0.5556}, # in 1e+10 Pa, does not matter # 'density' : 0.1142, # in 1e4 kg/m3 'density' : 1.1340, # in 1e4 kg/m3 } dim = MeshIO.any_from_filename( filename_mesh ).read_dimension() geom = {3 : '3_4', 2 : '2_3'}[dim] field_0 = { 'name' : 'displacement_Y', 'dim' : (dim,1), 'domain' : 'Y', 'bases' : {'Y' : '%s_P1' % geom} } field_1 = { 'name' : 'displacement_Y23', 'dim' : (dim,1), 'domain' : 'Y23', 'bases' : {'Y23' : '%s_P1' % geom} }
def main(): version = open( op.join( init_sfepy.install_dir, 'VERSION' ) ).readlines()[0][:-1] parser = OptionParser( usage = usage, version = "%prog " + version ) parser.add_option( "--mesh", action = "store_true", dest = "mesh", default = False, help = help['mesh'] ) parser.add_option( "--2d", action = "store_true", dest = "dim2", default = False, help = help['dim'] ) parser.add_option( "-o", "", metavar = 'filename', action = "store", dest = "output_filename_trunk", default = "mesh", help = help['filename'] ) parser.add_option( "--oscillator", action = "store_true", dest = "oscillator", default = False, help = help['oscillator'] ) parser.add_option( "--well", action = "store_true", dest = "well", default = False, help = help['well'] ) parser.add_option( "--hydrogen", action = "store_true", dest = "hydrogen", default = False, help = help['hydrogen'] ) parser.add_option( "--boron", action = "store_true", dest = "boron", default = False, help = help['boron'] ) parser.add_option( "--dft", action = "store_true", dest = "dft", default = False, help = help['dft'] ) parser.add_option( "-p", "--plot", action = "store_true", dest = "plot", default = False, help = help['plot'] ) options, args = parser.parse_args() if len( args ) == 1: filename_in = args[0]; elif len( args ) == 0: if options.oscillator: dim = MeshIO.any_from_filename("tmp/mesh.vtk").read_dimension() if dim == 2: filename_in = "input/quantum/oscillator2d.py" else: assert_( dim == 3 ) filename_in = "input/quantum/oscillator3d.py" options.dim = dim print "Dimension:", dim elif options.well: dim = MeshIO.any_from_filename("tmp/mesh.vtk").read_dimension() if dim == 2: filename_in = "input/quantum/well2d.py" else: assert_( dim == 3 ) filename_in = "input/quantum/well3d.py" options.dim = dim print "Dimension:", dim elif options.hydrogen: dim = MeshIO.any_from_filename("tmp/mesh.vtk").read_dimension() if dim == 2: filename_in = "input/quantum/hydrogen2d.py" else: assert_( dim == 3 ) filename_in = "input/quantum/hydrogen3d.py" options.dim = dim print "Dimension:", dim elif options.boron: dim = MeshIO.any_from_filename("tmp/mesh.vtk").read_dimension() if dim == 2: filename_in = "input/quantum/boron2d.py" else: assert_( dim == 3 ) filename_in = "input/quantum/boron3d.py" options.dim = dim print "Dimension:", dim elif options.mesh: try: os.makedirs("tmp") except OSError, e: if e.errno != 17: # [Errno 17] File exists raise if options.dim2: print "Dimension: 2" os.system("cp database/quantum/square.geo tmp/mesh.geo") os.system("gmsh -2 tmp/mesh.geo -format mesh") os.system("script/mesh_to_vtk.py tmp/mesh.mesh tmp/mesh.vtk") else: print "Dimension: 3" import geom from sfepy.fem.mesh import Mesh try: from site_cfg import tetgen_path except ImportError: tetgen_path = '/usr/bin/tetgen' os.system("gmsh -0 database/box.geo -o tmp/x.geo") g = geom.read_gmsh("tmp/x.geo") g.printinfo() geom.write_tetgen(g, "tmp/t.poly") geom.runtetgen("tmp/t.poly", a=0.03, Q=1.0, quadratic=False, tetgenpath=tetgen_path) m = Mesh.from_file("tmp/t.1.node") m.write("tmp/mesh.vtk", io="auto") print "Mesh written to tmp/mesh.vtk" return elif options.dft: dim = MeshIO.any_from_filename("tmp/mesh.vtk").read_dimension() if dim == 2: filename_in = "input/quantum/dft2d.py" else: assert_( dim == 3 ) filename_in = "input/quantum/dft3d.py" print "Dimension:", dim options.dim = dim else: parser.print_help() return