def gen_two_bodies(dims0, shape0, centre0, dims1, shape1, centre1, shift1): from sfepy.discrete.fem import Mesh from sfepy.mesh.mesh_generators import gen_block_mesh m0 = gen_block_mesh(dims0, shape0, centre0) m1 = gen_block_mesh(dims1, shape1, centre1) coors = nm.concatenate((m0.coors, m1.coors + shift1), axis=0) desc = m0.descs[0] c0 = m0.get_conn(desc) c1 = m1.get_conn(desc) conn = nm.concatenate((c0, c1 + m0.n_nod), axis=0) ngroups = nm.zeros(coors.shape[0], dtype=nm.int32) ngroups[m0.n_nod:] = 1 mat_id = nm.zeros(conn.shape[0], dtype=nm.int32) mat_id[m0.n_el:] = 1 name = 'two_bodies.mesh' mesh = Mesh.from_data(name, coors, ngroups, [conn], [mat_id], m0.descs) mesh.write(name, io='auto') return mesh
def main(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-d', '--dims', metavar='dims', action='store', dest='dims', default='[1.0, 1.0]', help=helps['dims']) parser.add_argument('-c', '--centre', metavar='centre', action='store', dest='centre', default='[0.0, 0.0]', help=helps['centre']) parser.add_argument('-s', '--shape', metavar='shape', action='store', dest='shape', default='[11, 11]', help=helps['shape']) parser.add_argument('--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() dims = nm.array(eval(options.dims), dtype=nm.float64) centre = nm.array(eval(options.centre), dtype=nm.float64) shape = nm.array(eval(options.shape), dtype=nm.int32) output('dimensions:', dims) output('centre: ', centre) output('shape: ', shape) mesh = gen_block_mesh(dims, shape, centre, name='block-fem') fe_domain = FEDomain('domain', mesh) pb, state = run(fe_domain, 1) pb.save_state('laplace_shifted_periodic.vtk', state) if options.show: from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.domain_specific import DomainSpecificPlot view = Viewer('laplace_shifted_periodic.vtk') view(rel_scaling=1, domain_specific={ 'u': DomainSpecificPlot('plot_warp_scalar', ['rel_scaling=1']) }, is_scalar_bar=True, is_wireframe=True, opacity=0.3)
def mesh_hook(mesh, mode): if mode == 'read': mesh = gen_block_mesh([0.0098, 0.0011, 0.1], [5, 3, 17], [0, 0, 0.05], name='specimen', verbose=False) return mesh elif mode == 'write': pass
def test_gen_block_mesh(self): from sfepy.mesh.mesh_generators import gen_block_mesh mesh = gen_block_mesh([1, 2, 3], [4, 3, 5], [2, 1, 0], verbose=False) filename = op.join(self.options.out_dir, 'gen_block.mesh') mesh.write(filename) self.report('block mesh generated') return True
def test_projection_iga_fem(self): from sfepy.discrete import FieldVariable from sfepy.discrete.fem import FEDomain, Field from sfepy.discrete.iga.domain import IGDomain from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.discrete.iga.domain_generators import gen_patch_block_domain from sfepy.discrete.projections import (make_l2_projection, make_l2_projection_data) shape = [10, 12, 12] dims = [5, 6, 6] centre = [0, 0, 0] degrees = [2, 2, 2] nurbs, bmesh, regions = gen_patch_block_domain(dims, shape, centre, degrees, cp_mode='greville', name='iga') ig_domain = IGDomain('iga', nurbs, bmesh, regions=regions) ig_omega = ig_domain.create_region('Omega', 'all') ig_field = Field.from_args('iga', nm.float64, 1, ig_omega, approx_order='iga', poly_space_base='iga') ig_u = FieldVariable('ig_u', 'parameter', ig_field, primary_var_name='(set-to-None)') mesh = gen_block_mesh(dims, shape, centre, name='fem') fe_domain = FEDomain('fem', mesh) fe_omega = fe_domain.create_region('Omega', 'all') fe_field = Field.from_args('fem', nm.float64, 1, fe_omega, approx_order=2) fe_u = FieldVariable('fe_u', 'parameter', fe_field, primary_var_name='(set-to-None)') def _eval_data(ts, coors, mode, **kwargs): return nm.prod(coors**2, axis=1)[:, None, None] make_l2_projection_data(ig_u, _eval_data) make_l2_projection(fe_u, ig_u) # This calls ig_u.evaluate_at(). coors = 0.5 * nm.random.rand(20, 3) * dims ig_vals = ig_u.evaluate_at(coors) fe_vals = fe_u.evaluate_at(coors) ok = nm.allclose(ig_vals, fe_vals, rtol=0.0, atol=1e-12) if not ok: self.report('iga-fem projection failed!') self.report('coors:') self.report(coors) self.report('iga fem diff:') self.report(nm.c_[ig_vals, fe_vals, nm.abs(ig_vals - fe_vals)]) return ok
def test_gen_block_mesh(self): from sfepy.mesh.mesh_generators import gen_block_mesh mesh = gen_block_mesh([1, 2, 3], [4, 3, 5], [2, 1, 0], verbose=False) filename = op.join(self.options.out_dir, 'gen_block.mesh') mesh.write(filename) self.report('block mesh generated') csum = nm.sum(mesh.coors - nm.min(mesh.coors, axis=0), axis=0) return nm.linalg.norm(csum - nm.array([30, 60, 90])) < tolerance
def test_create_output2D(self): mesh = gen_block_mesh((1, 1), (4, 4), (.5, .5)) approx_order = 2 n_cell_nod = 9 field, regions = prepare_dgfield(approx_order, mesh) dofs = nm.zeros((n_cell_nod * 9, 1)) output = field.create_output(dofs, "u") assert output["u_cell_nodes"].mode == "cell_nodes" assert nm.allclose(output["u_cell_nodes"].data, nm.zeros((9, n_cell_nod))) assert output["u_cell_nodes"].scheme is not None
def test_create_output1D(self): mesh = gen_block_mesh((1,), (4,), (.5,)) approx_order = 2 n_cell_nod = approx_order + 1 field, regions = prepare_dgfield(approx_order, mesh) dofs = nm.zeros((n_cell_nod * 3, 1)) output = field.create_output(dofs, "u") for i in range(n_cell_nod): assert output["u_modal{}".format(i)].mode == "cell" assert nm.allclose(output["u_modal{}".format(i)].data, nm.zeros((3, 1)))
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
def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh(dims, shape, [0, 0, 0], name='user_block', verbose=False) return mesh elif mode == 'write': pass
def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh(dims, shape, [0, 0], name='user_block', verbose=False) return mesh elif mode == 'write': pass
def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False)
def __init__( self, dims, center_location, cell_sizes=np.array([2, 2]), prob_file="C:\\Users\\wbald\\sfepythings\\blocks\\fem\\prob_desc_2d.py", put_mesh="C:\\Users\\wbald\\sfepythings"): """ dims: array, dimensions of rectangle [x,y] center_location: array, centre of rectangle [x,y] cell sizes: array, x and y side length of FEM rectangular elements stretch: default distance by which to displace the upper y axis edge. prob_file: problem description file put_mesh: where to save the mesh file """ assert (dims.shape[0] == 2) assert (cell_sizes.shape[0] == 2) # assume linear elasticity. Fix strain of rectangle to 0.001 and query # at different strains by scaling linearly self.dims = dims self.prob_file = prob_file self.FEM_model_strain = 0.001 self.elongation = self.FEM_model_strain * self.dims[1] nums = np.divide(dims, cell_sizes) nums = np.around(nums).astype(int) + np.array([1, 1]) blockmesh = gen_block_mesh(dims, nums, center_location) blockmesh.write(put_mesh + '\\mesh.vtk') conf = ProblemConf.from_file(prob_file) # 'region_ylower__1' holds the edge to be fixed # 'region_yupper__2' holds the edge to be displaced conf.regions['region_ylower__1'].select = 'vertices in (y < ' + str( 0.01) + ')' conf.regions['region_yupper__2'].select = 'vertices in (y > ' + str( dims[1] - 0.01) + ')' conf.ebcs['ebc_Displaced__1'].dofs['u.1'] = self.elongation self.prob = Problem.from_conf(conf) # for reshaping sfepy output into xyz displacements self.reshape_tuple = ((self.prob.fields['displacement'].n_nod, self.prob.fields['displacement'].n_components))
def mesh_hook(mesh, mode): """ Generate the 1D mesh. """ if mode == 'read': mesh = gen_block_mesh(dims, shape, centre, mat_id=mat_id, name=name, coors=coors, verbose=verbose) return mesh elif mode == 'write': pass
def main(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-d', '--dims', metavar='dims', action='store', dest='dims', default='[1.0, 1.0]', help=helps['dims']) parser.add_argument('-c', '--centre', metavar='centre', action='store', dest='centre', default='[0.0, 0.0]', help=helps['centre']) parser.add_argument('-s', '--shape', metavar='shape', action='store', dest='shape', default='[11, 11]', help=helps['shape']) parser.add_argument('--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() dims = nm.array(eval(options.dims), dtype=nm.float64) centre = nm.array(eval(options.centre), dtype=nm.float64) shape = nm.array(eval(options.shape), dtype=nm.int32) output('dimensions:', dims) output('centre: ', centre) output('shape: ', shape) mesh = gen_block_mesh(dims, shape, centre, name='block-fem') fe_domain = FEDomain('domain', mesh) pb, state = run(fe_domain, 1) pb.save_state('laplace_shifted_periodic.vtk', state) if options.show: from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.domain_specific import DomainSpecificPlot view = Viewer('laplace_shifted_periodic.vtk') view(rel_scaling=1, domain_specific={'u' : DomainSpecificPlot('plot_warp_scalar', ['rel_scaling=1'])}, is_scalar_bar=True, is_wireframe=True, opacity=0.3)
def main(): parser = OptionParser(usage=usage, version="%prog") parser.add_option( "-d", "--dims", metavar="dims", action="store", dest="dims", default="[1.0, 1.0]", help=helps["dims"] ) parser.add_option( "-c", "--centre", metavar="centre", action="store", dest="centre", default="[0.0, 0.0]", help=helps["centre"] ) parser.add_option( "-s", "--shape", metavar="shape", action="store", dest="shape", default="[11, 11]", help=helps["shape"] ) parser.add_option("", "--show", action="store_true", dest="show", default=False, help=helps["show"]) (options, args) = parser.parse_args() dims = nm.array(eval(options.dims), dtype=nm.float64) centre = nm.array(eval(options.centre), dtype=nm.float64) shape = nm.array(eval(options.shape), dtype=nm.int32) output("dimensions:", dims) output("centre: ", centre) output("shape: ", shape) mesh = gen_block_mesh(dims, shape, centre, name="block-fem") fe_domain = FEDomain("domain", mesh) pb, state = run(fe_domain, 1) pb.save_state("laplace_shifted_periodic.vtk", state) if options.show: from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.domain_specific import DomainSpecificPlot view = Viewer("laplace_shifted_periodic.vtk") view( rel_scaling=1, domain_specific={"u": DomainSpecificPlot("plot_warp_scalar", ["rel_scaling=1"])}, is_scalar_bar=True, is_wireframe=True, opacity=0.3, )
def main(): parser = ArgumentParser(description=__doc__) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-o', metavar='filename', action='store', dest='output_filename', default='out.vtk', help=helps['filename']) parser.add_argument('-f', '--format', metavar='format', action='store', type=str, dest='format', default=None, help=helps['format']) parser.add_argument('-d', '--dims', metavar='dims', action='store', dest='dims', default='[1.0, 1.0, 1.0]', help=helps['dims']) parser.add_argument('-s', '--shape', metavar='shape', action='store', dest='shape', default='[11, 11, 11]', help=helps['shape']) parser.add_argument('-c', '--centre', metavar='centre', action='store', dest='centre', default='[0.0, 0.0, 0.0]', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) options = parser.parse_args() dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output.prefix = 'blockgen:' output('dimensions:', dims) output('shape:', shape) output('centre:', centre) mesh = gen_block_mesh(dims, shape, centre, name=options.output_filename) io = MeshIO.for_format(options.output_filename, format=options.format, writable=True) mesh.write(options.output_filename, io=io)
def make_mesh(dims, shape, transform=None): """ Generate a 2D rectangle mesh in 3D space, and optionally apply a coordinate transform. """ _mesh = gen_block_mesh(dims, shape, [0, 0], name='shell10x', verbose=False) coors = nm.c_[_mesh.coors, nm.zeros(_mesh.n_nod, dtype=nm.float64)] coors = nm.ascontiguousarray(coors) conns = [_mesh.get_conn(_mesh.descs[0])] mesh = Mesh.from_data(_mesh.name, coors, _mesh.cmesh.vertex_groups, conns, [_mesh.cmesh.cell_groups], _mesh.descs) if transform == 'bend': bbox = mesh.get_bounding_box() x0, x1 = bbox[:, 0] angles = 0.5 * nm.pi * (coors[:, 0] - x0) / (x1 - x0) mtx = make_axis_rotation_matrix([0, -1, 0], angles[:, None, None]) coors = mesh.coors.copy() coors[:, 0] = 0 coors[:, 2] = (x1 - x0) mesh.coors[:] = transform_data(coors, mtx=mtx) mesh.coors[:, 0] -= 0.5 * (x1 - x0) elif transform == 'twist': bbox = mesh.get_bounding_box() x0, x1 = bbox[:, 0] angles = 0.5 * nm.pi * (coors[:, 0] - x0) / (x1 - x0) mtx = make_axis_rotation_matrix([-1, 0, 0], angles[:, None, None]) mesh.coors[:] = transform_data(mesh.coors, mtx=mtx) return mesh
def test_laplace_shifted_periodic(self): import numpy as nm from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.discrete.fem import FEDomain from examples.diffusion.laplace_shifted_periodic import run dims = [2.0, 1.0] shape = [21, 11] centre = [0.0, 0.0] mesh = gen_block_mesh(dims, shape, centre, name='block-fem') fe_domain = FEDomain('domain', mesh) pb, state = run(fe_domain, 3) gamma3 = pb.domain.regions['Gamma3'] gamma4 = pb.domain.regions['Gamma4'] field = pb.fields['fu'] # Check that the shift equals to one. i3 = field.get_dofs_in_region(gamma3, merge=True) i4 = field.get_dofs_in_region(gamma4, merge=True) i_corners = nm.array([0, shape[0] - 1]) ii = nm.setdiff1d(nm.arange(len(i3)), i_corners) vals = state() shift = vals[i3] - vals[i4] ok = (shift[i_corners] == 0.0).all() ok = ok and nm.allclose(shift[ii], 1.0, rtol=0.0, atol=1e-14) if not ok: self.report('wrong shift:', shift) return ok
def get_fields(shape, delta_x): """Get the fields for the displacement and test function Args: shape: the shape of the domain delta_x: the mesh spacing Returns: tuple of field variables """ return pipe( np.array(shape), lambda x: gen_block_mesh( x * delta_x, x + 1, np.zeros_like(shape), verbose=False ), lambda x: Domain("domain", x), lambda x: x.create_region("region_all", "all"), lambda x: Field.from_args("fu", np.float64, "vector", x, approx_order=2), lambda x: ( FieldVariable("u", "unknown", x), FieldVariable("v", "test", x, primary_var_name="u"), ), )
def main(): parser = ArgumentParser(description=__doc__) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-o', metavar='filename', action='store', dest='output_filename', default='out.vtk', help=help['filename']) parser.add_argument('-f', '--format', metavar='format', action='store', type=str, dest='format', default=None, help=help['format']) parser.add_argument('-d', '--dims', metavar='dims', action='store', dest='dims', default='[1.0, 1.0, 1.0]', help=help['dims']) parser.add_argument('-s', '--shape', metavar='shape', action='store', dest='shape', default='[11, 11, 11]', help=help['shape']) parser.add_argument('-c', '--centre', metavar='centre', action='store', dest='centre', default='[0.0, 0.0, 0.0]', help=help['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=help['2d']) options = parser.parse_args() dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output.prefix = 'blockgen:' output('dimensions:', dims) output('shape:', shape) output('centre:', centre) mesh = gen_block_mesh(dims, shape, centre, name=options.output_filename) io = MeshIO.for_format(options.output_filename, format=options.format, writable=True) mesh.write(options.output_filename, io=io)
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 ### c10, c01 = material_parameters m = Material( 'm', mu=2*c10, kappa=2*c01, ) ### 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) term_neohook = Term.new( 'dw_tl_he_neohook(m.mu, v, u)', integral, omega, m=m, v=v, u=u) term_mooney = Term.new( 'dw_tl_he_mooney_rivlin(m.kappa, v, u)', integral, omega, m=m, 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_neohook+term_mooney+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' : 5}, lin_solver=ls, status=nls_status ) ### Problem ### pb = Problem('hyper', equations=equations) pb.set_bcs(ebcs=ebcs) pb.set_ics(ics=Conditions([])) tss = SimpleTimeSteppingSolver(ts, nls=nls, context=pb) pb.set_solver(tss) ### Solution ### axial_stress = [] axial_displacement = [] def stress_strain_fun(*args, **kwargs): return stress_strain( *args, order=order, global_stress=axial_stress, global_displacement=axial_displacement, **kwargs) pb.solve(save_results=True, post_process_hook=stress_strain_fun) if do_plot: plot_graphs( material_parameters, axial_stress, axial_displacement, undeformed_length=dims[0])
def main(): from sfepy import data_dir parser = OptionParser(usage=usage, version='%prog') parser.add_option('-s', '--show', action="store_true", dest='show', default=False, help=help['show']) options, args = parser.parse_args() options_probe = True folder = str(uuid.uuid4()) os.mkdir(folder) os.chdir(folder) file = open('README.txt', 'w') file.write('DIMENSIONS\n') file.write('Lx = '+str(dims[0])+' Ly = '+str(dims[1])+' Lz = '+str(dims[2])+'\n') file.write('DISCRETIZATION (NX, NY, NZ)\n') file.write(str(NX)+' '+str(NY)+' '+str(NZ)+'\n') file.write('MATERIALS\n') file.write(str(E_f)+' '+str(nu_f)+' '+str(E_m)+' '+str(nu_m)+'\n') #mesh = Mesh.from_file(data_dir + '/meshes/2d/rectangle_tri.mesh') mesh = mesh_generators.gen_block_mesh(dims,shape,centre,name='block') domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:,0] min_y, max_y = domain.get_mesh_bounding_box()[:,1] min_z, max_z = domain.get_mesh_bounding_box()[:,2] eps = 1e-8 * (max_x - min_x) print min_x, max_x print min_y, max_y print min_z, max_z R1 = domain.create_region('Ym', 'vertices in z < %.10f' % (max_z/2)) R2 = domain.create_region('Yf', 'vertices in z >= %.10f' % (min_z/2)) omega = domain.create_region('Omega', 'all') gamma1 = domain.create_region('Left', 'vertices in x < %.10f' % (min_x + eps), 'facet') gamma2 = domain.create_region('Right', 'vertices in x > %.10f' % (max_x - eps), 'facet') gamma3 = domain.create_region('Front', 'vertices in y < %.10f' % (min_y + eps), 'facet') gamma4 = domain.create_region('Back', 'vertices in y > %.10f' % (max_y - eps), 'facet') gamma5 = domain.create_region('Bottom', 'vertices in z < %.10f' % (min_z + eps), 'facet') gamma6 = domain.create_region('Top', 'vertices in z > %.10f' % (max_z - eps), 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') mu=1.1 lam=1.0 m = Material('m', lam=lam, mu=mu) f = Material('f', val=[[0.0], [0.0],[-1.0]]) load = Material('Load',val=[[0.0],[0.0],[-Load]]) D = stiffness_from_lame(3,lam, mu) mat = Material('Mat', D=D) get_mat = Function('get_mat1',get_mat1) get_mat_f = Function('get_mat_f',get_mat1) integral = Integral('i', order=3) s_integral = Integral('is',order=2) t1 = Term.new('dw_lin_elastic(Mat.D, v, u)', integral, omega, Mat=mat, v=v, u=u) t2 = Term.new('dw_volume_lvf(f.val, v)', integral, omega, f=f, v=v) #t3 = Term.new('DotProductSurfaceTerm(Load.val, v)',s_integral,gamma5,Load=load,v=v) t3 = Term.new('dw_surface_ltr( Load.val, v )',s_integral,gamma6,Load=load,v=v) eq = Equation('balance', t1 + t2 + t3) eqs = Equations([eq]) fix_u = EssentialBC('fix_u', gamma1, {'u.all' : 0.0}) left_bc = EssentialBC('Left', gamma1, {'u.0' : 0.0}) right_bc = EssentialBC('Right', gamma2, {'u.0' : 0.0}) back_bc = EssentialBC('Front', gamma3, {'u.1' : 0.0}) front_bc = EssentialBC('Back', gamma4, {'u.1' : 0.0}) bottom_bc = EssentialBC('Bottom', gamma5, {'u.all' : 0.0}) top_bc = EssentialBC('Top', gamma6, {'u.2' : 0.2}) bc=[left_bc,right_bc,back_bc,front_bc,bottom_bc] #bc=[bottom_bc,top_bc] ############################## # ##### SOLVER SECTION ##### ############################## conf = Struct(method='bcgsl', precond='jacobi', sub_precond=None, i_max=10000, eps_a=1e-50, eps_r=1e-10, eps_d=1e4, verbose=True) ls = PETScKrylovSolver(conf) file.write(str(ls.name)+' '+str(ls.conf.method)+' '+str(ls.conf.precond)+' '+str(ls.conf.eps_r)+' '+str(ls.conf.i_max)+'\n' ) nls_status = IndexedStruct() nls = Newton({'i_max':1,'eps_a':1e-10}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) dd=pb.get_materials()['Mat'] dd.set_function(get_mat1) #xload = pb.get_materials()['f'] #xload.set_function(get_mat_f) pb.save_regions_as_groups('regions') pb.time_update(ebcs=Conditions(bc)) vec = pb.solve() print nls_status file.write('TIME TO SOLVE\n') file.write(str(nls.status.time_stats['solve'])+'\n') file.write('TIME TO CREATE MATRIX\n') file.write(str(nls.status.time_stats['matrix'])+'\n') ev = pb.evaluate out = vec.create_output_dict() strain = ev('ev_cauchy_strain.3.Omega(u)', mode='el_avg') stress = ev('ev_cauchy_stress.3.Omega(Mat.D, u)', mode='el_avg', copy_materials=False) out['cauchy_strain'] = Struct(name='output_data', mode='cell', data=strain, dofs=None) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) pb.save_state('strain.vtk', out=out) print nls_status file.close()
def main(): from sfepy import data_dir parser = OptionParser(usage=usage, version='%prog') parser.add_option('-s', '--show', action="store_true", dest='show', default=False, help=help['show']) options, args = parser.parse_args() options_probe = True folder = str(uuid.uuid4()) os.mkdir(folder) os.chdir(folder) file = open('README.txt', 'w') file.write('DIMENSIONS\n') file.write('Lx = '+str(dims[0])+' Ly = '+str(dims[1])+' Lz = '+str(dims[2])+'\n') file.write('DISCRETIZATION (NX, NY, NZ)\n') file.write(str(NX)+' '+str(NY)+' '+str(NZ)+'\n') file.write('MATERIALS\n') file.write(str(E_f)+' '+str(nu_f)+' '+str(E_m)+' '+str(nu_m)+'\n') #mesh = Mesh.from_file(data_dir + '/meshes/2d/rectangle_tri.mesh') mesh = mesh_generators.gen_block_mesh(dims,shape,centre,name='block') domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:,0] min_y, max_y = domain.get_mesh_bounding_box()[:,1] min_z, max_z = domain.get_mesh_bounding_box()[:,2] eps = 1e-8 * (max_x - min_x) print min_x, max_x print min_y, max_y print min_z, max_z R1 = domain.create_region('Ym', 'vertices in z < %.10f' % (max_z/2)) R2 = domain.create_region('Yf', 'vertices in z >= %.10f' % (min_z/2)) omega = domain.create_region('Omega', 'all') gamma1 = domain.create_region('Left', 'vertices in x < %.10f' % (min_x + eps), 'facet') gamma2 = domain.create_region('Right', 'vertices in x > %.10f' % (max_x - eps), 'facet') gamma3 = domain.create_region('Front', 'vertices in y < %.10f' % (min_y + eps), 'facet') gamma4 = domain.create_region('Back', 'vertices in y > %.10f' % (max_y - eps), 'facet') gamma5 = domain.create_region('Bottom', 'vertices in z < %.10f' % (min_z + eps), 'facet') gamma6 = domain.create_region('Top', 'vertices in z > %.10f' % (max_z - eps), 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') mu=1.1 lam=1.0 m = Material('m', lam=lam, mu=mu) f = Material('f', val=[[0.0], [0.0],[0.0]]) #mu,lam=m.get_constants_mu_lam() #print mu.lam D = stiffness_from_lame(3,lam, mu) mat = Material('Mat', D=D) #D = stiffness_from_youngpoisson(2, options.young, options.poisson) get_mat = Function('get_mat1',get_mat1) #get_mat1=Function('get_mat', (lambda ts, coors, mode=None, problem=None, **kwargs: # get_mat(coors, mode, problem))) #mat = Material('Mat', function=Function('get_mat1',get_mat1)) #mat = Material('Mat', 'get_mat') integral = Integral('i', order=3) t1 = Term.new('dw_lin_elastic(Mat.D, v, u)', integral, omega, Mat=mat, v=v, u=u) t2 = Term.new('dw_volume_lvf(f.val, v)', integral, omega, f=f, v=v) eq = Equation('balance', t1 + t2) eqs = Equations([eq]) fix_u = EssentialBC('fix_u', gamma1, {'u.all' : 0.0}) left_bc = EssentialBC('Left', gamma1, {'u.0' : 0.0}) right_bc = EssentialBC('Right', gamma2, {'u.0' : 0.0}) back_bc = EssentialBC('Front', gamma3, {'u.1' : 0.0}) front_bc = EssentialBC('Back', gamma4, {'u.1' : 0.0}) bottom_bc = EssentialBC('Bottom', gamma5, {'u.all' : 0.0}) top_bc = EssentialBC('Top', gamma6, {'u.2' : 0.2}) bc=[left_bc,right_bc,back_bc,front_bc,bottom_bc,top_bc] #bc=[bottom_bc,top_bc] bc_fun = Function('shift_u_fun', shift_u_fun, extra_args={'shift' : 0.01}) shift_u = EssentialBC('shift_u', gamma2, {'u.0' : bc_fun}) #get_mat = Function('get_mat1',get_mat1) #mat = Material('Mat', function=Function('get_mat1',get_mat1)) #ls = ScipyDirect({'method':'umfpack'}) ############################## # ##### SOLVER SECTION ##### ############################## # GET MATRIX FOR PRECONTITIONER # #ls = ScipyIterative({'method':'bicgstab','i_max':5000,'eps_r':1e-10}) #ls = ScipyIterative({}) #ls = PyAMGSolver({'i_max':5000,'eps_r':1e-10}) #conf = Struct(method='cg', precond='gamg', sub_precond=None,i_max=10000, eps_a=1e-50, eps_r=1e-5, eps_d=1e4, verbose=True) #ls = PETScKrylovSolver({'method' : 'cg', 'precond' : 'icc', 'eps_r' : 1e-10, 'i_max' : 5000}) conf = Struct(method='bcgsl', precond='jacobi', sub_precond=None, i_max=10000, eps_a=1e-50, eps_r=1e-10, eps_d=1e4, verbose=True) #conf = Struct(method = 'cg', precond = 'icc', eps_r = 1e-10, i_max = 5000) ls = PETScKrylovSolver(conf) #if hasattr(ls.name,'ls.scipy_iterative'): file.write(str(ls.name)+' '+str(ls.conf.method)+' '+str(ls.conf.precond)+' '+str(ls.conf.eps_r)+' '+str(ls.conf.i_max)+'\n' ) # else: #file.write(str(ls.name)+' '+str(ls.conf.method)+'\n') # conf = Struct(method='bcgsl', precond='jacobi', sub_precond=None, # i_max=10000, eps_a=1e-50, eps_r=1e-8, eps_d=1e4, # verbose=True) #ls = PETScKrylovSolver(conf) #ls = ScipyIterative({'method':'bicgstab','i_max':100,'eps_r':1e-10}) nls_status = IndexedStruct() nls = Newton({'i_max':1,'eps_a':1e-10}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) dd=pb.get_materials()['Mat'] dd.set_function(get_mat1) pb.save_regions_as_groups('regions') #pb.time_update(ebcs=Conditions([fix_u, shift_u])) pb.time_update(ebcs=Conditions(bc)) pb.save_regions_as_groups('regions') #ls = ScipyIterative({'method':'bicgstab','i_max':100,'eps_r':1e-10}) # A = pb.mtx_a # M = spilu(A,fill_factor = 1) #conf = Struct(solvers ='ScipyIterative',method='bcgsl', sub_precond=None, # i_max=1000, eps_r=1e-8) #pb.set_conf_solvers(conf) vec = pb.solve() print nls_status file.write('TIME TO SOLVE\n') file.write(str(nls.status.time_stats['solve'])+'\n') file.write('TIME TO CREATE MATRIX\n') file.write(str(nls.status.time_stats['matrix'])+'\n') #out = post_process(out, pb, state, extend=False) ev = pb.evaluate out = vec.create_output_dict() strain = ev('ev_cauchy_strain.3.Omega(u)', mode='el_avg') stress = ev('ev_cauchy_stress.3.Omega(Mat.D, u)', mode='el_avg', copy_materials=False) out['cauchy_strain'] = Struct(name='output_data', mode='cell', data=strain, dofs=None) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) # Postprocess the solution. #out = vec.create_output_dict() #out = stress_strain(out, pb, vec,lam,mu, extend=True) #pb.save_state('its2D_interactive.vtk', out=out) #print 'aqui estoy' pb.save_state('strain.vtk', out=out) #pb.save_state('disp.vtk', out=vec) #print 'ahora estoy aqui' #out = stress_strain(out, pb, vec, extend=True) #pb.save_state('out.vtk', out=out) print nls_status order = 3 strain_qp = ev('ev_cauchy_strain.%d.Omega(u)' % order, mode='qp') stress_qp = ev('ev_cauchy_stress.%d.Omega(Mat.D, u)' % order, mode='qp', copy_materials=False) file.close() options_probe=False if options_probe: # Probe the solution. probes, labels = gen_lines(pb) nls_options = {'eps_a':1e-8,'i_max':1} ls = ScipyDirect({}) ls2 = ScipyIterative({'method':'bicgstab','i_max':5000,'eps_r':1e-20}) order = 5 sfield = Field.from_args('sym_tensor', nm.float64, (3,), omega, approx_order=order-1) stress = FieldVariable('stress', 'parameter', sfield, primary_var_name='(set-to-None)') strain = FieldVariable('strain', 'parameter', sfield, primary_var_name='(set-to-None)') cfield = Field.from_args('component', nm.float64, 1, omega, approx_order=order-1) component = FieldVariable('component', 'parameter', cfield, primary_var_name='(set-to-None)') ev = pb.evaluate order = 2*(order - 1) #2 * (2- 1) print "before strain_qp" strain_qp = ev('ev_cauchy_strain.%d.Omega(u)' % order, mode='qp') stress_qp = ev('ev_cauchy_stress.%d.Omega(Mat.D, u)' % order, mode='qp', copy_materials=False) print "before projections" print stress project_by_component(strain, strain_qp, component, order,ls2,nls_options) #print 'strain done' project_by_component(stress, stress_qp, component, order,ls2,nls_options) print "after projections" all_results = [] for ii, probe in enumerate(probes): fig, results = probe_results2(u, strain, stress, probe, labels[ii]) fig.savefig('test_probe_%d.png' % ii) all_results.append(results) for ii, results in enumerate(all_results): output('probe %d:' % ii) output.level += 2 for key, res in ordered_iteritems(results): output(key + ':') val = res[1] output(' min: %+.2e, mean: %+.2e, max: %+.2e' % (val.min(), val.mean(), val.max())) output.level -= 2
def main(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-d', '--dims', metavar='dims', action='store', dest='dims', default='[1.0, 1.0]', help=helps['dims']) parser.add_argument('-c', '--centre', metavar='centre', action='store', dest='centre', default='[0.0, 0.0]', help=helps['centre']) parser.add_argument('-s', '--shape', metavar='shape', action='store', dest='shape', default='[11, 11]', help=helps['shape']) parser.add_argument('-b', '--bc-kind', metavar='kind', action='store', dest='bc_kind', choices=['free', 'cantilever', 'fixed'], default='free', help=helps['bc_kind']) parser.add_argument('-a', '--axis', metavar='0, ..., dim, or -1', type=int, action='store', dest='axis', default=-1, help=helps['axis']) parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=6.80e+10, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.36, help=helps['poisson']) parser.add_argument('--density', metavar='float', type=float, action='store', dest='density', default=2700.0, help=helps['density']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-n', '--n-eigs', metavar='int', type=int, action='store', dest='n_eigs', default=6, help=helps['n_eigs']) parser.add_argument('-i', '--ignore', metavar='int', type=int, action='store', dest='ignore', default=None, help=helps['ignore']) parser.add_argument('--solver', metavar='solver', action='store', dest='solver', default= \ "eig.scipy,method:'eigh',tol:1e-5,maxiter:1000", help=helps['solver']) parser.add_argument('--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('filename', nargs='?', default=None) options = parser.parse_args() aux = options.solver.split(',') kwargs = {} for option in aux[1:]: key, val = option.split(':') kwargs[key.strip()] = eval(val) eig_conf = Struct(name='evp', kind=aux[0], **kwargs) output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' density:', options.density) output('displacement field approximation order:', options.order) output('requested %d eigenvalues' % options.n_eigs) output('using eigenvalue problem solver:', eig_conf.kind) output.level += 1 for key, val in six.iteritems(kwargs): output('%s: %r' % (key, val)) output.level -= 1 assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') filename = options.filename if filename is not None: mesh = Mesh.from_file(filename) dim = mesh.dim dims = nm.diff(mesh.get_bounding_box(), axis=0) else: dims = nm.array(eval(options.dims), dtype=nm.float64) dim = len(dims) centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] output('dimensions:', dims) output('centre: ', centre) output('shape: ', shape) mesh = gen_block_mesh(dims, shape, centre, name='mesh') output('axis: ', options.axis) assert_((-dim <= options.axis < dim), 'invalid axis value!') eig_solver = Solver.any_from_conf(eig_conf) # Build the problem definition. domain = FEDomain('domain', mesh) bbox = domain.get_mesh_bounding_box() min_coor, max_coor = bbox[:, options.axis] eps = 1e-8 * (max_coor - min_coor) ax = 'xyz'[:dim][options.axis] omega = domain.create_region('Omega', 'all') bottom = domain.create_region('Bottom', 'vertices in (%s < %.10f)' % (ax, min_coor + eps), 'facet') bottom_top = domain.create_region('BottomTop', 'r.Bottom +v vertices in (%s > %.10f)' % (ax, max_coor - eps), 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') mtx_d = stiffness_from_youngpoisson(dim, options.young, options.poisson) m = Material('m', D=mtx_d, rho=options.density) integral = Integral('i', order=2*options.order) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) t2 = Term.new('dw_volume_dot(m.rho, v, u)', integral, omega, m=m, v=v, u=u) eq1 = Equation('stiffness', t1) eq2 = Equation('mass', t2) lhs_eqs = Equations([eq1, eq2]) pb = Problem('modal', equations=lhs_eqs) if options.bc_kind == 'free': pb.time_update() n_rbm = dim * (dim + 1) / 2 elif options.bc_kind == 'cantilever': fixed = EssentialBC('Fixed', bottom, {'u.all' : 0.0}) pb.time_update(ebcs=Conditions([fixed])) n_rbm = 0 elif options.bc_kind == 'fixed': fixed = EssentialBC('Fixed', bottom_top, {'u.all' : 0.0}) pb.time_update(ebcs=Conditions([fixed])) n_rbm = 0 else: raise ValueError('unsupported BC kind! (%s)' % options.bc_kind) if options.ignore is not None: n_rbm = options.ignore pb.update_materials() # Assemble stiffness and mass matrices. mtx_k = eq1.evaluate(mode='weak', dw_mode='matrix', asm_obj=pb.mtx_a) mtx_m = mtx_k.copy() mtx_m.data[:] = 0.0 mtx_m = eq2.evaluate(mode='weak', dw_mode='matrix', asm_obj=mtx_m) try: eigs, svecs = eig_solver(mtx_k, mtx_m, options.n_eigs + n_rbm, eigenvectors=True) except sla.ArpackNoConvergence as ee: eigs = ee.eigenvalues svecs = ee.eigenvectors output('only %d eigenvalues converged!' % len(eigs)) output('%d eigenvalues converged (%d ignored as rigid body modes)' % (len(eigs), n_rbm)) eigs = eigs[n_rbm:] svecs = svecs[:, n_rbm:] omegas = nm.sqrt(eigs) freqs = omegas / (2 * nm.pi) output('number | eigenvalue | angular frequency ' '| frequency') for ii, eig in enumerate(eigs): output('%6d | %17.12e | %17.12e | %17.12e' % (ii + 1, eig, omegas[ii], freqs[ii])) # Make full eigenvectors (add DOFs fixed by boundary conditions). variables = pb.get_variables() vecs = nm.empty((variables.di.ptr[-1], svecs.shape[1]), dtype=nm.float64) for ii in range(svecs.shape[1]): vecs[:, ii] = variables.make_full_vec(svecs[:, ii]) # Save the eigenvectors. out = {} state = pb.create_state() for ii in range(eigs.shape[0]): state.set_full(vecs[:, ii]) aux = state.create_output_dict() strain = pb.evaluate('ev_cauchy_strain.i.Omega(u)', integrals=Integrals([integral]), mode='el_avg', verbose=False) out['u%03d' % ii] = aux.popitem()[1] out['strain%03d' % ii] = Struct(mode='cell', data=strain) pb.save_state('eigenshapes.vtk', out=out) pb.save_regions_as_groups('regions') if len(eigs) and options.show: # Show the solution. If the approximation order is greater than 1, the # extra DOFs are simply thrown away. from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.domain_specific import DomainSpecificPlot scaling = 0.05 * dims.max() / nm.abs(vecs).max() ds = {} for ii in range(eigs.shape[0]): pd = DomainSpecificPlot('plot_displacements', ['rel_scaling=%s' % scaling, 'color_kind="tensors"', 'color_name="strain%03d"' % ii]) ds['u%03d' % ii] = pd view = Viewer('eigenshapes.vtk') view(domain_specific=ds, only_names=sorted(ds.keys()), is_scalar_bar=False, is_wireframe=True)
def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--verify', action='store_true', dest='verify', default=False, help=helps['verify']) parser.add_argument('--plot', action='store_true', dest='plot', default=False, help=helps['plot']) parser.add_argument('--show', action='store_true', dest='show', default=False, help=helps['show']) parser.add_argument('--save-inter-regions', action='store_true', dest='save_inter_regions', default=False, help=helps['save_inter_regions']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() if options.show: options.plot = True comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank output.set_output(filename=filename, combined=options.silent == False) output('petsc options:', petsc_opts) mesh_filename = os.path.join(options.output_dir, 'para.h5') if comm.rank == 0: from sfepy.mesh.mesh_generators import gen_block_mesh if options.clear: remove_files_patterns(output_dir, ['*.h5', '*.mesh', '*.txt', '*.png'], ignores=['output_log_%02d.txt' % ii for ii in range(comm.size)], verbose=True) save_options(os.path.join(output_dir, 'options.txt'), [('options', vars(options))]) dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output('dimensions:', dims) output('shape: ', shape) output('centre: ', centre) mesh = gen_block_mesh(dims, shape, centre, name='block-fem', verbose=True) mesh.write(mesh_filename, io='auto') comm.barrier() output('field order:', options.order) solve_problem(mesh_filename, options, comm)
from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer import matplotlib.pyplot as plt print "inside main" from sfepy import data_dir #mesh = Mesh.from_file(data_dir + '/meshes/2d/rectangle_tri.mesh') mesh = gen_block_mesh([2], [100, 100], [0, 0], coors=[-2, 2]) domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:, 0] eps = 1e-8 * (max_x - min_x) omega = domain.create_region('Omega', 'all') gammaL = domain.create_region('Gamma_Left', 'vertices in x < %.9f' % (min_x + eps), 'facet') gammaR = domain.create_region('Gamma_Right', 'vertices in x > %.9f' % (max_x - eps), 'facet') min_y, max_y = domain.get_mesh_bounding_box()[:, 1] eps = 1e-8 * (max_y - min_y) gammaT = domain.create_region('Gamma_Top', 'vertices in y < %.9f' % (min_y + eps), 'facet') gammaB = domain.create_region('Gamma_Bottom',
def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='7,7,7', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-3', '--3d', action='store_true', dest='is_3d', default=False, help=helps['3d']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) options = parser.parse_args() dim = 3 if options.is_3d else 2 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output('dimensions:', dims) output('shape: ', shape) output('centre: ', centre) mesh0 = gen_block_mesh(dims, shape, centre, name='block-fem', verbose=True) domain0 = FEDomain('d', mesh0) bbox = domain0.get_mesh_bounding_box() min_x, max_x = bbox[:, 0] eps = 1e-8 * (max_x - min_x) cnt = (shape[0] - 1) // 2 g0 = 0.5 * dims[0] grading = nm.array([g0 / 2**ii for ii in range(cnt)]) + eps + centre[0] - g0 domain, subs = refine_towards_facet(domain0, grading, 'x <') omega = domain.create_region('Omega', 'all') gamma1 = domain.create_region('Gamma1', 'vertices in (x < %.10f)' % (min_x + eps), 'facet') gamma2 = domain.create_region('Gamma2', 'vertices in (x > %.10f)' % (max_x - eps), 'facet') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=options.order) if subs is not None: field.substitute_dofs(subs) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') integral = Integral('i', order=2*options.order) t1 = Term.new('dw_laplace(v, u)', integral, omega, v=v, u=u) eq = Equation('eq', t1) eqs = Equations([eq]) def u_fun(ts, coors, bc=None, problem=None): """ Define a displacement depending on the y coordinate. """ if coors.shape[1] == 2: min_y, max_y = bbox[:, 1] y = (coors[:, 1] - min_y) / (max_y - min_y) val = (max_y - min_y) * nm.cos(3 * nm.pi * y) else: min_y, max_y = bbox[:, 1] min_z, max_z = bbox[:, 2] y = (coors[:, 1] - min_y) / (max_y - min_y) z = (coors[:, 2] - min_z) / (max_z - min_z) val = ((max_y - min_y) * (max_z - min_z) * nm.cos(3 * nm.pi * y) * (1.0 + 3.0 * (z - 0.5)**2)) return val bc_fun = Function('u_fun', u_fun) fix1 = EssentialBC('shift_u', gamma1, {'u.0' : bc_fun}) fix2 = EssentialBC('fix2', gamma2, {'u.all' : 0.0}) ls = ScipyDirect({}) nls = Newton({}, lin_solver=ls) pb = Problem('heat', equations=eqs, nls=nls, ls=ls) pb.time_update(ebcs=Conditions([fix1, fix2])) state = pb.solve() if subs is not None: field.restore_dofs() filename = os.path.join(options.output_dir, 'hanging.vtk') ensure_path(filename) pb.save_state(filename, state) if options.order > 1: pb.save_state(filename, state, linearization=Struct(kind='adaptive', min_level=0, max_level=8, eps=1e-3))
def test_continuity(self): from sfepy.base.base import Struct from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.discrete import FieldVariable from sfepy.discrete.fem import FEDomain, Field from sfepy.discrete.projections import make_l2_projection_data import sfepy.discrete.fem.refine_hanging as rh dims = [1.5, 2.0, 1.3] shape = [3, 3, 3] centre = [0.0, 0.0, 0.0] probe_gens = {'2_4': _gen_lines_2_4, '3_8': _gen_grid_3_8} ok = True for key in self.gel_names: gel = self.gels[key] probe_gen = probe_gens[key] perms = gel.get_conn_permutations() dim = gel.dim for io, order in enumerate(range(1, 4)): mesh00 = gen_block_mesh(dims[:dim], shape[:dim], centre[:dim], name='block') for ip, perm in enumerate(perms): self.report( 'geometry: %s, order: %d, permutation: %d: %s' % (key, order, ip, perm)) mesh0 = mesh00.copy() conn = mesh0.cmesh.get_conn(dim, 0).indices conn = conn.reshape((mesh0.n_el, -1)) conn[-1, :] = conn[-1, perm] domain0 = FEDomain('d', mesh0) refine = nm.zeros(mesh0.n_el, dtype=nm.uint8) refine[:-1] = 1 subs = None domain, subs = rh.refine(domain0, refine, subs=subs) omega = domain.create_region('Omega', 'all') field = Field.from_args('fu', nm.float64, 1, omega, approx_order=order) field.substitute_dofs(subs) uvar = FieldVariable('u', 'parameter', field, primary_var_name='(set-to-None)') field.restore_dofs(store=True) field.substitute_dofs(subs=None, restore=True) make_l2_projection_data(uvar, eval_fun) field.restore_dofs() bbox = domain.get_mesh_bounding_box() eps = 1e-7 save = False for ii, (probe0, probe1) in enumerate(probe_gen(bbox, eps)): probe0.set_options(close_limit=0.0) probe1.set_options(close_limit=0.0) pars0, vals0 = probe0(uvar) pars1, vals1 = probe1(uvar) assert_(nm.allclose(pars0, pars1, atol=1e-14, rtol=0.0)) _ok = nm.allclose(vals0, vals1, atol=20.0 * eps, rtol=0.0) if not _ok: save = True self.report('probe %d failed! (max. error: %e)' % (ii, nm.abs(vals0 - vals1).max())) ok = ok and _ok if (ip == 0) or save: out = uvar.create_output() filenames = _build_filenames(self.options.out_dir, key, order, ip) domain.mesh.write(filenames[0], out=out) linearization = Struct(kind='adaptive', min_level=0, max_level=4, eps=1e-2) out = uvar.create_output(linearization=linearization) val = out['u'] mesh = val.get('mesh', domain.mesh) mesh.write(filenames[1], out=out) return ok
def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument("output_dir", help=helps["output_dir"]) parser.add_argument( "--dims", metavar="dims", action="store", dest="dims", default="1.0,1.0,1.0", help=helps["dims"] ) parser.add_argument( "--shape", metavar="shape", action="store", dest="shape", default="11,11,11", help=helps["shape"] ) parser.add_argument( "--centre", metavar="centre", action="store", dest="centre", default="0.0,0.0,0.0", help=helps["centre"] ) parser.add_argument("-2", "--2d", action="store_true", dest="is_2d", default=False, help=helps["2d"]) parser.add_argument( "--u-order", metavar="int", type=int, action="store", dest="order_u", default=1, help=helps["u-order"] ) parser.add_argument( "--p-order", metavar="int", type=int, action="store", dest="order_p", default=1, help=helps["p-order"] ) parser.add_argument( "--linearization", choices=["strip", "adaptive"], action="store", dest="linearization", default="strip", help=helps["linearization"], ) parser.add_argument("--metis", action="store_true", dest="metis", default=False, help=helps["metis"]) parser.add_argument("--silent", action="store_true", dest="silent", default=False, help=helps["silent"]) parser.add_argument("--clear", action="store_true", dest="clear", default=False, help=helps["clear"]) options, petsc_opts = parser.parse_known_args() comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, "output_log_%02d.txt" % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = "sfepy_%02d:" % comm.rank output.set_output(filename=filename, combined=options.silent == False) output("petsc options:", petsc_opts) mesh_filename = os.path.join(options.output_dir, "para.h5") if comm.rank == 0: from sfepy.mesh.mesh_generators import gen_block_mesh if options.clear: for _f in chain( *[glob.glob(os.path.join(output_dir, clean_pattern)) for clean_pattern in ["*.h5", "*.txt", "*.png"]] ): output('removing "%s"' % _f) os.remove(_f) dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output("dimensions:", dims) output("shape: ", shape) output("centre: ", centre) mesh = gen_block_mesh(dims, shape, centre, name="block-fem", verbose=True) mesh.write(mesh_filename, io="auto") comm.barrier() output("field u order:", options.order_u) output("field p order:", options.order_p) solve_problem(mesh_filename, options, comm)
def main(): parser = OptionParser(usage=usage, version='%prog') parser.add_option('-d', '--dims', metavar='dims', action='store', dest='dims', default='[1.0, 1.0]', help=helps['dims']) parser.add_option('-c', '--centre', metavar='centre', action='store', dest='centre', default='[0.0, 0.0]', help=helps['centre']) parser.add_option('-s', '--shape', metavar='shape', action='store', dest='shape', default='[11, 11]', help=helps['shape']) parser.add_option('-b', '--bc-kind', metavar='kind', action='store', dest='bc_kind', choices=['free', 'clamped'], default='free', help=helps['bc_kind']) parser.add_option('--young', metavar='float', type=float, action='store', dest='young', default=6.80e+10, help=helps['young']) parser.add_option('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.36, help=helps['poisson']) parser.add_option('--density', metavar='float', type=float, action='store', dest='density', default=2700.0, help=helps['density']) parser.add_option('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_option('-n', '--n-eigs', metavar='int', type=int, action='store', dest='n_eigs', default=6, help=helps['order']) parser.add_option('', '--show', action="store_true", dest='show', default=False, help=helps['show']) options, args = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') dims = nm.array(eval(options.dims), dtype=nm.float64) dim = len(dims) centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] output('dimensions:', dims) output('centre: ', centre) output('shape: ', shape) output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' density:', options.density) # Build the problem definition. mesh = gen_block_mesh(dims, shape, centre, name='mesh') domain = FEDomain('domain', mesh) bbox = domain.get_mesh_bounding_box() min_y, max_y = bbox[:, 1] eps = 1e-8 * (max_y - min_y) omega = domain.create_region('Omega', 'all') bottom = domain.create_region('Bottom', 'vertices in (y < %.10f)' % (min_y + eps), 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') mtx_d = stiffness_from_youngpoisson(dim, options.young, options.poisson) m = Material('m', D=mtx_d, rho=options.density) integral = Integral('i', order=2 * options.order) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) t2 = Term.new('dw_volume_dot(m.rho, v, u)', integral, omega, m=m, v=v, u=u) eq1 = Equation('stiffness', t1) eq2 = Equation('mass', t2) lhs_eqs = Equations([eq1, eq2]) pb = Problem('modal', equations=lhs_eqs) if options.bc_kind == 'free': pb.time_update() n_rbm = dim * (dim + 1) / 2 else: fixed_b = EssentialBC('FixedB', bottom, {'u.all': 0.0}) pb.time_update(ebcs=Conditions([fixed_b])) n_rbm = 0 pb.update_materials() # Assemble stiffness and mass matrices. mtx_k = eq1.evaluate(mode='weak', dw_mode='matrix', asm_obj=pb.mtx_a) mtx_m = mtx_k.copy() mtx_m.data[:] = 0.0 mtx_m = eq2.evaluate(mode='weak', dw_mode='matrix', asm_obj=mtx_m) try: eigs, svecs = sla.eigsh(mtx_k, k=options.n_eigs + n_rbm, M=mtx_m, which='SM', tol=1e-5, maxiter=10000) except sla.ArpackNoConvergence as ee: eigs = ee.eigenvalues svecs = ee.eigenvectors output('only %d eigenvalues converged!' % len(eigs)) eigs = eigs[n_rbm:] svecs = svecs[:, n_rbm:] output('eigenvalues:', eigs) output('eigen-frequencies:', nm.sqrt(eigs)) # Make full eigenvectors (add DOFs fixed by boundary conditions). variables = pb.get_variables() vecs = nm.empty((variables.di.ptr[-1], svecs.shape[1]), dtype=nm.float64) for ii in xrange(svecs.shape[1]): vecs[:, ii] = variables.make_full_vec(svecs[:, ii]) # Save the eigenvectors. out = {} state = pb.create_state() for ii in xrange(eigs.shape[0]): state.set_full(vecs[:, ii]) aux = state.create_output_dict() strain = pb.evaluate('ev_cauchy_strain.i.Omega(u)', integrals=Integrals([integral]), mode='el_avg', verbose=False) out['u%03d' % ii] = aux.popitem()[1] out['strain%03d' % ii] = Struct(mode='cell', data=strain) pb.save_state('eigenshapes.vtk', out=out) pb.save_regions_as_groups('regions') if options.show: # Show the solution. If the approximation order is greater than 1, the # extra DOFs are simply thrown away. from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.domain_specific import DomainSpecificPlot scaling = 0.05 * dims.max() / nm.abs(vecs).max() ds = {} for ii in xrange(eigs.shape[0]): pd = DomainSpecificPlot('plot_displacements', [ 'rel_scaling=%s' % scaling, 'color_kind="tensors"', 'color_name="strain%03d"' % ii ]) ds['u%03d' % ii] = pd view = Viewer('eigenshapes.vtk') view(domain_specific=ds, only_names=sorted(ds.keys()), is_scalar_bar=False, is_wireframe=True)
def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--u-order', metavar='int', type=int, action='store', dest='order_u', default=1, help=helps['u-order']) parser.add_argument('--p-order', metavar='int', type=int, action='store', dest='order_p', default=1, help=helps['p-order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank output.set_output(filename=filename, combined=options.silent == False) output('petsc options:', petsc_opts) mesh_filename = os.path.join(options.output_dir, 'para.h5') if comm.rank == 0: from sfepy.mesh.mesh_generators import gen_block_mesh if options.clear: for _f in chain(*[ glob.glob(os.path.join(output_dir, clean_pattern)) for clean_pattern in ['*.h5', '*.txt', '*.png'] ]): output('removing "%s"' % _f) os.remove(_f) dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output('dimensions:', dims) output('shape: ', shape) output('centre: ', centre) mesh = gen_block_mesh(dims, shape, centre, name='block-fem', verbose=True) mesh.write(mesh_filename, io='auto') comm.barrier() output('field u order:', options.order_u) output('field p order:', options.order_p) solve_problem(mesh_filename, options, comm)
def test_continuity(self): from sfepy.base.base import Struct from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.discrete import FieldVariable from sfepy.discrete.fem import FEDomain, Field from sfepy.discrete.projections import make_l2_projection_data import sfepy.discrete.fem.refine_hanging as rh dims = [1.5, 2.0, 1.3] shape = [3, 3, 3] centre = [0.0, 0.0, 0.0] probe_gens = {"2_4": _gen_lines_2_4, "3_8": _gen_grid_3_8} ok = True for key in self.gel_names: gel = self.gels[key] probe_gen = probe_gens[key] perms = gel.get_conn_permutations() dim = gel.dim for io, order in enumerate(range(1, 4)): mesh00 = gen_block_mesh(dims[:dim], shape[:dim], centre[:dim], name="block") for ip, perm in enumerate(perms): self.report("geometry: %s, order: %d, permutation: %d: %s" % (key, order, ip, perm)) mesh0 = mesh00.copy() conn = mesh0.cmesh.get_conn(dim, 0).indices conn = conn.reshape((mesh0.n_el, -1)) conn[-1, :] = conn[-1, perm] domain0 = FEDomain("d", mesh0) refine = nm.zeros(mesh0.n_el, dtype=nm.uint8) refine[:-1] = 1 subs = None domain, subs = rh.refine(domain0, refine, subs=subs) omega = domain.create_region("Omega", "all") field = Field.from_args("fu", nm.float64, 1, omega, approx_order=order) field.substitute_dofs(subs) uvar = FieldVariable("u", "parameter", field, primary_var_name="(set-to-None)") field.restore_dofs(store=True) field.substitute_dofs(subs=None, restore=True) make_l2_projection_data(uvar, eval_fun) field.restore_dofs() bbox = domain.get_mesh_bounding_box() eps = 1e-7 save = False for ii, (probe0, probe1) in enumerate(probe_gen(bbox, eps)): probe0.set_options(close_limit=0.0) probe1.set_options(close_limit=0.0) pars0, vals0 = probe0(uvar) pars1, vals1 = probe1(uvar) assert_(nm.allclose(pars0, pars1, atol=1e-14, rtol=0.0)) _ok = nm.allclose(vals0, vals1, atol=20.0 * eps, rtol=0.0) if not _ok: save = True self.report("probe %d failed! (max. error: %e)" % (ii, nm.abs(vals0 - vals1).max())) ok = ok and _ok if (ip == 0) or save: out = uvar.create_output() filenames = _build_filenames(self.options.out_dir, key, order, ip) domain.mesh.write(filenames[0], out=out) linearization = Struct(kind="adaptive", min_level=0, max_level=4, eps=1e-2) out = uvar.create_output(linearization=linearization) val = out["u"] mesh = val.get("mesh", domain.mesh) mesh.write(filenames[1], out=out) return ok
def main(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-d', '--dims', metavar='dims', action='store', dest='dims', default='[1.0, 1.0]', help=helps['dims']) parser.add_argument('-c', '--centre', metavar='centre', action='store', dest='centre', default='[0.0, 0.0]', help=helps['centre']) parser.add_argument('-s', '--shape', metavar='shape', action='store', dest='shape', default='[11, 11]', help=helps['shape']) parser.add_argument('-b', '--bc-kind', metavar='kind', action='store', dest='bc_kind', choices=['free', 'cantilever', 'fixed'], default='free', help=helps['bc_kind']) parser.add_argument('-a', '--axis', metavar='0, ..., dim, or -1', type=int, action='store', dest='axis', default=-1, help=helps['axis']) parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=200e+9, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.3, help=helps['poisson']) parser.add_argument('--density', metavar='float', type=float, action='store', dest='density', default=7800.0, help=helps['density']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-n', '--n-eigs', metavar='int', type=int, action='store', dest='n_eigs', default=6, help=helps['n_eigs']) parser.add_argument('-i', '--ignore', metavar='int', type=int, action='store', dest='ignore', default=None, help=helps['ignore']) parser.add_argument('--solver', metavar='solver', action='store', dest='solver', default= \ "eig.scipy,method:'eigh',tol:1e-5,maxiter:1000", help=helps['solver']) parser.add_argument('--show', action="store_true", dest='show', default=False, help=helps['show']) #parser.add_argument('filename', nargs='?', default=None) #read block.mesh #parser.add_argument('filename', nargs='?', default="platehexat200mm.mesh") parser.add_argument('filename', nargs='?', default="block_1m.mesh") options = parser.parse_args() aux = options.solver.split(',') kwargs = {} for option in aux[1:]: key, val = option.split(':') kwargs[key.strip()] = eval(val) eig_conf = Struct(name='evp', kind=aux[0], **kwargs) output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' density:', options.density) output('displacement field approximation order:', options.order) output('requested %d eigenvalues' % options.n_eigs) output('using eigenvalue problem solver:', eig_conf.kind) output.level += 1 for key, val in six.iteritems(kwargs): output('%s: %r' % (key, val)) output.level -= 1 assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') filename = options.filename if filename is not None: mesh = Mesh.from_file(filename) dim = mesh.dim dims = nm.diff(mesh.get_bounding_box(), axis=0) else: dims = nm.array(eval(options.dims), dtype=nm.float64) dim = len(dims) centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] output('dimensions:', dims) output('centre: ', centre) output('shape: ', shape) mesh = gen_block_mesh(dims, shape, centre, name='mesh') output('axis: ', options.axis) assert_((-dim <= options.axis < dim), 'invalid axis value!') eig_solver = Solver.any_from_conf(eig_conf) # Build the problem definition. domain = FEDomain('domain', mesh) bbox = domain.get_mesh_bounding_box() min_coor, max_coor = bbox[:, options.axis] eps = 1e-8 * (max_coor - min_coor) ax = 'xyz'[:dim][options.axis] omega = domain.create_region('Omega', 'all') """ bottom = domain.create_region('Bottom', 'vertices in (%s < %.10f)' % (ax, min_coor + eps), 'facet') bottom_top = domain.create_region('BottomTop', 'r.Bottom +v vertices in (%s > %.10f)' % (ax, max_coor - eps), 'facet') """ #import pdb; pdb.set_trace() left = domain.create_region('left', 'vertices in (x < -0.49)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') mtx_d = stiffness_from_youngpoisson(dim, options.young, options.poisson) m = Material('m', D=mtx_d, rho=options.density) integral = Integral('i', order=2 * options.order) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) t2 = Term.new('dw_volume_dot(m.rho, v, u)', integral, omega, m=m, v=v, u=u) eq1 = Equation('stiffness', t1) eq2 = Equation('mass', t2) lhs_eqs = Equations([eq1, eq2]) pb = Problem('modal', equations=lhs_eqs) """ if options.bc_kind == 'free': pb.time_update() n_rbm = dim * (dim + 1) // 2 elif options.bc_kind == 'cantilever': fixed = EssentialBC('Fixed', bottom, {'u.all' : 0.0}) pb.time_update(ebcs=Conditions([fixed])) n_rbm = 0 elif options.bc_kind == 'fixed': fixed = EssentialBC('Fixed', bottom_top, {'u.all' : 0.0}) pb.time_update(ebcs=Conditions([fixed])) n_rbm = 0 else: raise ValueError('unsupported BC kind! (%s)' % options.bc_kind) if options.ignore is not None: n_rbm = options.ignore """ fixed = EssentialBC('Fixed', left, {'u.all': 0.0}) pb.time_update(ebcs=Conditions([fixed])) n_rbm = 0 pb.update_materials() # Assemble stiffness and mass matrices. mtx_k = eq1.evaluate(mode='weak', dw_mode='matrix', asm_obj=pb.mtx_a) mtx_m = mtx_k.copy() mtx_m.data[:] = 0.0 mtx_m = eq2.evaluate(mode='weak', dw_mode='matrix', asm_obj=mtx_m) try: eigs, svecs = eig_solver(mtx_k, mtx_m, options.n_eigs + n_rbm, eigenvectors=True) except sla.ArpackNoConvergence as ee: eigs = ee.eigenvalues svecs = ee.eigenvectors output('only %d eigenvalues converged!' % len(eigs)) output('%d eigenvalues converged (%d ignored as rigid body modes)' % (len(eigs), n_rbm)) eigs = eigs[n_rbm:] svecs = svecs[:, n_rbm:] omegas = nm.sqrt(eigs) freqs = omegas / (2 * nm.pi) output('number | eigenvalue | angular frequency ' '| frequency') for ii, eig in enumerate(eigs): output('%6d | %17.12e | %17.12e | %17.12e' % (ii + 1, eig, omegas[ii], freqs[ii])) # Make full eigenvectors (add DOFs fixed by boundary conditions). variables = pb.get_variables() vecs = nm.empty((variables.di.ptr[-1], svecs.shape[1]), dtype=nm.float64) for ii in range(svecs.shape[1]): vecs[:, ii] = variables.make_full_vec(svecs[:, ii]) # Save the eigenvectors. out = {} state = pb.create_state() for ii in range(eigs.shape[0]): state.set_full(vecs[:, ii]) aux = state.create_output_dict() strain = pb.evaluate('ev_cauchy_strain.i.Omega(u)', integrals=Integrals([integral]), mode='el_avg', verbose=False) out['u%03d' % ii] = aux.popitem()[1] out['strain%03d' % ii] = Struct(mode='cell', data=strain) pb.save_state('eigenshapes.vtk', out=out) pb.save_regions_as_groups('regions') if len(eigs) and options.show: # Show the solution. If the approximation order is greater than 1, the # extra DOFs are simply thrown away. from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.domain_specific import DomainSpecificPlot scaling = 0.05 * dims.max() / nm.abs(vecs).max() ds = {} for ii in range(eigs.shape[0]): pd = DomainSpecificPlot('plot_displacements', [ 'rel_scaling=%s' % scaling, 'color_kind="tensors"', 'color_name="strain%03d"' % ii ]) ds['u%03d' % ii] = pd view = Viewer('eigenshapes.vtk') view(domain_specific=ds, only_names=sorted(ds.keys()), is_scalar_bar=False, is_wireframe=True)
def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--u-order', metavar='int', type=int, action='store', dest='order_u', default=1, help=helps['u-order']) parser.add_argument('--p-order', metavar='int', type=int, action='store', dest='order_p', default=1, help=helps['p-order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank output.set_output(filename=filename, combined=options.silent == False) output('petsc options:', petsc_opts) mesh_filename = os.path.join(options.output_dir, 'para.h5') if comm.rank == 0: from sfepy.mesh.mesh_generators import gen_block_mesh if options.clear: for _f in chain(*[glob.glob(os.path.join(output_dir, clean_pattern)) for clean_pattern in ['*.h5', '*.txt', '*.png']]): output('removing "%s"' % _f) os.remove(_f) dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output('dimensions:', dims) output('shape: ', shape) output('centre: ', centre) mesh = gen_block_mesh(dims, shape, centre, name='block-fem', verbose=True) mesh.write(mesh_filename, io='auto') comm.barrier() output('field u order:', options.order_u) output('field p order:', options.order_p) solve_problem(mesh_filename, options, comm)
import scipy aux = "eig.scipy,method:'eigh',tol:1e-7,maxiter:10000".split(',') kwargs = {} for option in aux[1:]: key, val = option.split(':') kwargs[key.strip()] = eval(val) eig_conf = Struct(name='evp', kind=aux[0], **kwargs) dims = nm.array([1.0, 1.5], dtype=nm.float64) dim = len(dims) centre = nm.array([0.0, 0.0], dtype=nm.float64)[:dim] shape = nm.array([11, 16], dtype=nm.int32)[:dim] mesh = gen_block_mesh(dims, shape, centre, name='mesh') eig_solver = Solver.any_from_conf(eig_conf) # Build the problem definition. domain = FEDomain('domain', mesh) bbox = domain.get_mesh_bounding_box() min_coor, max_coor = bbox[:, -1] eps = 1e-8 * (max_coor - min_coor) ax = 'xyz'[:dim][-1] omega = domain.create_region('Omega', 'all') bottom = domain.create_region('Bottom', 'vertices in (%s < %.10f)' % (ax, min_coor + eps), 'facet') bottom_top = domain.create_region('BottomTop', 'r.Bottom +v vertices in (%s > %.10f)' % (ax, max_coor - eps), 'facet')
def prepare_dgfield_1D(approx_order): mesh = gen_block_mesh((1,), (4,), (.5,)) return prepare_dgfield(approx_order, mesh), mesh
def test_preserve_coarse_entities(self): from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.discrete.fem import FEDomain import sfepy.discrete.fem.refine_hanging as rh dims = [1.5, 2.0] shape = [11, 11] centre = [0.0, 0.0] mesh0 = gen_block_mesh(dims, shape, centre, name='block') domain0 = FEDomain('d', mesh0) reg = domain0.create_region('surface', 'vertices of surface', 'facet', add_to_regions=False) cmesh0 = mesh0.cmesh cmesh0.vertex_groups[5::11] = 2 cmesh0.vertex_groups[reg.vertices] = 1 cmesh0.cell_groups[0] = 1 cmesh0.cell_groups[50:60] = 2 mesh0.write(op.join(self.options.out_dir, 'test_refine_hanging_ids0.vtk'), io='auto') refine = nm.zeros(mesh0.n_el, dtype=nm.uint8) refine[0:10] = 1 refine[5::10] = 1 domain, _, sub_cells = rh.refine(domain0, refine, subs=None, ret_sub_cells=True) domain.mesh.write(op.join(self.options.out_dir, 'test_refine_hanging_ids1.vtk'), io='auto') cmesh1 = domain.mesh.cmesh ii = nm.where(refine == 0)[0] conn0 = mesh0.get_conn('2_4') v0 = conn0[ii] conn1 = domain.mesh.get_conn('2_4') v1 = conn1[ii] ok = (v0 == v1).all() self.report('coarse cells positions preserved:', ok) cgs0 = cmesh0.cell_groups[ii] cgs1 = cmesh1.cell_groups[ii] _ok = (cgs0 == cgs1).all() self.report('coarse cells cell groups preserved:', _ok) ok = ok and _ok vgs0 = cmesh0.vertex_groups[v0] vgs1 = cmesh1.vertex_groups[v1] _ok = (vgs0 == vgs1).all() self.report('coarse cells vertex groups preserved:', _ok) ok = ok and _ok ii = nm.where(refine == 1)[0] cgs0 = cmesh0.cell_groups[ii] cgs1 = cmesh1.cell_groups[sub_cells[:, 1:]] _ok = (cgs0[:, None] == cgs1).all() self.report('refined cells cell groups preserved:', _ok) ok = ok and _ok return ok
def main(): parser = ArgumentParser(description=__doc__.rstrip(), formatter_class=RawDescriptionHelpFormatter) parser.add_argument('output_dir', help=helps['output_dir']) parser.add_argument('--dims', metavar='dims', action='store', dest='dims', default='1.0,1.0,1.0', help=helps['dims']) parser.add_argument('--shape', metavar='shape', action='store', dest='shape', default='11,11,11', help=helps['shape']) parser.add_argument('--centre', metavar='centre', action='store', dest='centre', default='0.0,0.0,0.0', help=helps['centre']) parser.add_argument('-2', '--2d', action='store_true', dest='is_2d', default=False, help=helps['2d']) parser.add_argument('--u-order', metavar='int', type=int, action='store', dest='order_u', default=1, help=helps['u-order']) parser.add_argument('--p-order', metavar='int', type=int, action='store', dest='order_p', default=1, help=helps['p-order']) parser.add_argument('--linearization', choices=['strip', 'adaptive'], action='store', dest='linearization', default='strip', help=helps['linearization']) parser.add_argument('--metis', action='store_true', dest='metis', default=False, help=helps['metis']) parser.add_argument('--save-inter-regions', action='store_true', dest='save_inter_regions', default=False, help=helps['save_inter_regions']) parser.add_argument('--stats', metavar='filename', action='store', dest='stats_filename', default=None, help=helps['stats_filename']) parser.add_argument('--new-stats', action='store_true', dest='new_stats', default=False, help=helps['new_stats']) parser.add_argument('--silent', action='store_true', dest='silent', default=False, help=helps['silent']) parser.add_argument('--clear', action='store_true', dest='clear', default=False, help=helps['clear']) options, petsc_opts = parser.parse_known_args() comm = pl.PETSc.COMM_WORLD output_dir = options.output_dir filename = os.path.join(output_dir, 'output_log_%02d.txt' % comm.rank) if comm.rank == 0: ensure_path(filename) comm.barrier() output.prefix = 'sfepy_%02d:' % comm.rank output.set_output(filename=filename, combined=options.silent == False) output('petsc options:', petsc_opts) mesh_filename = os.path.join(options.output_dir, 'para.h5') dim = 2 if options.is_2d else 3 dims = nm.array(eval(options.dims), dtype=nm.float64)[:dim] shape = nm.array(eval(options.shape), dtype=nm.int32)[:dim] centre = nm.array(eval(options.centre), dtype=nm.float64)[:dim] output('dimensions:', dims) output('shape: ', shape) output('centre: ', centre) if comm.rank == 0: from sfepy.mesh.mesh_generators import gen_block_mesh if options.clear: remove_files_patterns(output_dir, ['*.h5', '*.mesh', '*.txt'], ignores=['output_log_%02d.txt' % ii for ii in range(comm.size)], verbose=True) save_options(os.path.join(output_dir, 'options.txt'), [('options', vars(options))]) mesh = gen_block_mesh(dims, shape, centre, name='block-fem', verbose=True) mesh.write(mesh_filename, io='auto') comm.barrier() output('field u order:', options.order_u) output('field p order:', options.order_p) stats = solve_problem(mesh_filename, options, comm) output(stats) if options.stats_filename: from examples.diffusion.poisson_parallel_interactive import save_stats if comm.rank == 0: ensure_path(options.stats_filename) comm.barrier() pars = Struct(dim=dim, shape=shape, order=options.order_u) pl.call_in_rank_order( lambda rank, comm: save_stats(options.stats_filename, pars, stats, options.new_stats, rank, comm), comm )
def prepare_field_2D(approx_order): mesh = gen_block_mesh((1, 1), (4, 4), (.5, .5)) return prepare_dgfield(approx_order, mesh), mesh
def test_get_facet_idx1D(self): mesh = gen_block_mesh((1,), (4,), (.5,)) field, regions = prepare_dgfield(1, mesh) assert nm.all(field.get_bc_facet_idx(regions["left"]) == nm.array([[0, 0]])) assert nm.all(field.get_bc_facet_idx(regions["right"]) == nm.array([[2, 1]]))
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 ### c10, c01 = material_parameters m = Material( 'm', mu=2 * c10, kappa=2 * c01, ) ### 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) term_neohook = Term.new('dw_tl_he_neohook(m.mu, v, u)', integral, omega, m=m, v=v, u=u) term_mooney = Term.new('dw_tl_he_mooney_rivlin(m.kappa, v, u)', integral, omega, m=m, 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_neohook + term_mooney + 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': 5}, lin_solver=ls, status=nls_status) ### Problem ### pb = Problem('hyper', equations=equations) pb.set_bcs(ebcs=ebcs) pb.set_ics(ics=Conditions([])) tss = SimpleTimeSteppingSolver(ts, nls=nls, context=pb) pb.set_solver(tss) ### Solution ### axial_stress = [] axial_displacement = [] def stress_strain_fun(*args, **kwargs): return stress_strain(*args, order=order, global_stress=axial_stress, global_displacement=axial_displacement, **kwargs) pb.solve(save_results=True, post_process_hook=stress_strain_fun) if do_plot: plot_graphs(material_parameters, axial_stress, axial_displacement, undeformed_length=dims[0])
def test_get_facet_idx2D(self): mesh = gen_block_mesh((1, 1), (4, 4), (.5, .5)) field, regions = prepare_dgfield(1, mesh) assert nm.all(field.get_bc_facet_idx(regions["left"]) == nm.array([[0, 3], [1, 3], [2, 3]])) assert nm.all(field.get_bc_facet_idx(regions["top"]) == nm.array([[2, 2], [5, 2], [8, 2]]))
def test_preserve_coarse_entities(self): from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.discrete.fem import FEDomain import sfepy.discrete.fem.refine_hanging as rh dims = [1.5, 2.0] shape = [11, 11] centre = [0.0, 0.0] mesh0 = gen_block_mesh(dims, shape, centre, name="block") domain0 = FEDomain("d", mesh0) reg = domain0.create_region("surface", "vertices of surface", "facet", add_to_regions=False) cmesh0 = mesh0.cmesh cmesh0.vertex_groups[5::11] = 2 cmesh0.vertex_groups[reg.vertices] = 1 cmesh0.cell_groups[0] = 1 cmesh0.cell_groups[50:60] = 2 mesh0.write(op.join(self.options.out_dir, "test_refine_hanging_ids0.vtk"), io="auto") refine = nm.zeros(mesh0.n_el, dtype=nm.uint8) refine[0:10] = 1 refine[5::10] = 1 domain, _, sub_cells = rh.refine(domain0, refine, subs=None, ret_sub_cells=True) domain.mesh.write(op.join(self.options.out_dir, "test_refine_hanging_ids1.vtk"), io="auto") cmesh1 = domain.mesh.cmesh ii = nm.where(refine == 0)[0] conn0 = mesh0.get_conn("2_4") v0 = conn0[ii] conn1 = domain.mesh.get_conn("2_4") v1 = conn1[ii] ok = (v0 == v1).all() self.report("coarse cells positions preserved:", ok) cgs0 = cmesh0.cell_groups[ii] cgs1 = cmesh1.cell_groups[ii] _ok = (cgs0 == cgs1).all() self.report("coarse cells cell groups preserved:", _ok) ok = ok and _ok vgs0 = cmesh0.vertex_groups[v0] vgs1 = cmesh1.vertex_groups[v1] _ok = (vgs0 == vgs1).all() self.report("coarse cells vertex groups preserved:", _ok) ok = ok and _ok ii = nm.where(refine == 1)[0] cgs0 = cmesh0.cell_groups[ii] cgs1 = cmesh1.cell_groups[sub_cells[:, 1:]] _ok = (cgs0[:, None] == cgs1).all() self.report("refined cells cell groups preserved:", _ok) ok = ok and _ok return ok