Beispiel #1
0
    def test_write_read_meshes(self):
        """
        Try to write and then read all supported formats.
        """
        from sfepy.fem import Mesh
        from sfepy.fem.meshio import supported_formats, supported_capabilities

        conf_dir = op.dirname(__file__)
        mesh0 = Mesh.from_file(data_dir
                               + '/meshes/various_formats/small3d.mesh',
                               prefix_dir=conf_dir)

        oks = []
        for suffix, format_ in supported_formats.iteritems():
            if isinstance(format_, tuple):
                continue
            if 'w' not in supported_capabilities[format_]: continue

            filename = op.join(self.options.out_dir, 'test_mesh_wr' + suffix)
            self.report('%s format: %s' % (suffix, filename))

            mesh0.write(filename, io='auto')
            mesh1 = Mesh.from_file(filename)

            oks.extend(self._compare_meshes(mesh0, mesh1))

        return sum(oks) == len(oks)
Beispiel #2
0
    def test_write_read_meshes(self):
        """
        Try to write and then read all supported formats.
        """
        from sfepy.fem import Mesh
        from sfepy.fem.meshio import supported_formats, supported_capabilities

        conf_dir = op.dirname(__file__)
        mesh0 = Mesh.from_file(data_dir +
                               '/meshes/various_formats/small3d.mesh',
                               prefix_dir=conf_dir)

        oks = []
        for suffix, format_ in supported_formats.iteritems():
            if isinstance(format_, tuple):
                continue
            if 'w' not in supported_capabilities[format_]: continue

            filename = op.join(self.options.out_dir, 'test_mesh_wr' + suffix)
            self.report('%s format: %s' % (suffix, filename))

            mesh0.write(filename, io='auto')
            mesh1 = Mesh.from_file(filename)

            oks.extend(self._compare_meshes(mesh0, mesh1))

        return sum(oks) == len(oks)
Beispiel #3
0
    def from_conf(conf, options):
        import sfepy
        from sfepy.fem import Mesh, Domain, H1NodalVolumeField
        mesh = Mesh.from_file('meshes/2d/rectangle_tri.mesh',
                              prefix_dir=sfepy.data_dir)
        domain = Domain('domain', mesh)
        dim = domain.shape.dim

        min_x, max_x = domain.get_mesh_bounding_box()[:, 0]
        eps = 1e-8 * (max_x - min_x)

        omega = domain.create_region('Omega', 'all')
        gamma1 = domain.create_region('Gamma1',
                                      'vertices in x < %.10f' % (min_x + eps),
                                      'facet')
        gamma2 = domain.create_region('Gamma2',
                                      'vertices in x > %.10f' % (max_x - eps),
                                      'facet')

        field = H1NodalVolumeField('fu',
                                   nm.float64,
                                   'vector',
                                   omega,
                                   approx_order=2)

        test = Test(conf=conf,
                    options=options,
                    dim=dim,
                    omega=omega,
                    gamma1=gamma1,
                    gamma2=gamma2,
                    field=field)
        return test
Beispiel #4
0
def main():
    parser = OptionParser(usage=usage)
    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.print_help()
        sys.exit(1)

    mesh_dir = args[0]

    mesh_files = []
    for (dirpath, dirnames, filenames) in os.walk(mesh_dir):
        for ii in filenames:
            _, ext = os.path.splitext(ii)
            if ext.lower() in ['.mesh', '.vtk']:
                mesh_files.append(dirpath + os.path.sep + ii)

    for ii in mesh_files:
        base, ext = os.path.splitext(ii)
        fname_out = base + '.png'
        if ext == '.mesh':
            fname_in = 'aux.vtk'
            mesh = Mesh.from_file(ii)
            mesh.write(fname_in, io='auto')

        else:
            fname_in = ii

        print('writing %s...' % fname_out)
        gen_shot(fname_in, fname_out)
Beispiel #5
0
def refine_mesh(filename, level):
    """
    Uniformly refine `level`-times a mesh given by `filename`.

    The refined mesh is saved to a file with name constructed from base
    name of `filename` and `level`-times appended `'_r'` suffix.

    Parameters
    ----------
    filename : str
        The mesh file name.
    level : int
        The refinement level.
    """
    import os
    from sfepy.base.base import output
    from sfepy.fem import Mesh, Domain

    if level > 0:
        mesh = Mesh.from_file(filename)
        domain = Domain(mesh.name, mesh)
        for ii in range(level):
            output('refine %d...' % ii)
            domain = domain.refine()
            output('... %d nodes %d elements'
                   % (domain.shape.n_nod, domain.shape.n_el))

        suffix = os.path.splitext(filename)[1]
        filename = domain.name + suffix

        domain.mesh.write(filename, io='auto')

    return filename
Beispiel #6
0
    def test_read_meshes(self):
        """Try to read all listed meshes."""
        from sfepy.fem import Mesh

        conf_dir = op.dirname(__file__)
        meshes = {}
        for ii, filename in enumerate(filename_meshes):
            self.report('%d. mesh: %s' % (ii + 1, filename))
            mesh = Mesh.from_file(filename, prefix_dir=conf_dir)

            assert_(mesh.dim == (mesh.coors.shape[1]))
            assert_(mesh.n_nod == (mesh.coors.shape[0]))
            assert_(mesh.n_nod == (mesh.ngroups.shape[0]))
            assert_(mesh.n_el == sum(mesh.n_els))
            for ig, conn in enumerate(mesh.conns):
                assert_(conn.shape[0] == len(mesh.mat_ids[ig]))
                assert_(conn.shape[0] == mesh.n_els[ig])
                assert_(conn.shape[1] == mesh.n_e_ps[ig])

            self.report('read ok')
            meshes[filename] = mesh

        self.meshes = meshes

        return True
Beispiel #7
0
    def test_read_meshes( self ):
        """Try to read all listed meshes."""
        from sfepy.fem import Mesh

        conf_dir = op.dirname(__file__)
        meshes = {}
        for ii, filename in enumerate( filename_meshes ):
            self.report( '%d. mesh: %s' % (ii + 1, filename) )
            mesh = Mesh.from_file(filename, prefix_dir=conf_dir)

            assert_(mesh.dim == (mesh.coors.shape[1]))
            assert_(mesh.n_nod == (mesh.coors.shape[0]))
            assert_(mesh.n_nod == (mesh.ngroups.shape[0]))
            assert_(mesh.n_el == sum(mesh.n_els))
            for ig, conn in enumerate( mesh.conns ):
                assert_(conn.shape[0] == len(mesh.mat_ids[ig]))
                assert_(conn.shape[0] == mesh.n_els[ig])
                assert_(conn.shape[1] == mesh.n_e_ps[ig])
                
            self.report( 'read ok' )
            meshes[filename] = mesh

        self.meshes = meshes

        return True
Beispiel #8
0
    def from_conf(conf, options):
        import sfepy
        from sfepy.fem import Mesh, Domain, H1NodalVolumeField
        mesh = Mesh.from_file('meshes/2d/rectangle_tri.mesh',
                              prefix_dir=sfepy.data_dir)
        domain = Domain('domain', mesh)
        dim = domain.shape.dim

        min_x, max_x = domain.get_mesh_bounding_box()[:,0]
        eps = 1e-8 * (max_x - min_x)

        omega = domain.create_region('Omega', 'all')
        gamma1 = domain.create_region('Gamma1',
                                      'vertices in x < %.10f' % (min_x + eps),
                                      'facet')
        gamma2 = domain.create_region('Gamma2',
                                      'vertices in x > %.10f' % (max_x - eps),
                                      'facet')

        field = H1NodalVolumeField('fu', nm.float64, 'vector', omega,
                                   approx_order=2)

        test = Test(conf=conf, options=options, dim=dim,
                    omega=omega, gamma1=gamma1, gamma2=gamma2,
                    field=field)
        return test
    def test_rcm(self):
        from sfepy import data_dir
        from sfepy.linalg import rcm, permute_in_place, save_sparse_txt
        from sfepy.fem import Mesh

        filename = data_dir + '/meshes/2d/special/square_triquad.mesh'

        self.report('testing reversed Cuthill-McKee permutation')

        conf_dir = op.dirname(__file__)
        mesh = Mesh.from_file(filename, prefix_dir=conf_dir)

        graph = mesh.create_conn_graph()
        graph0 = graph.copy()

        save_sparse_txt(op.join(self.options.out_dir, 'test_rcm_graph_orig'),
                        graph, fmt='%d %d %d\n')

        perm = rcm(graph)

        permute_in_place(graph, perm)
        save_sparse_txt(op.join(self.options.out_dir, 'test_rcm_graph_rcm'),
                        graph, fmt='%d %d %d\n')
        
        assert_((graph0.indptr != graph.indptr).any())
        assert_((graph0.indices != graph.indices).any())

        permute_in_place(graph, perm, inverse=True)
        save_sparse_txt(op.join(self.options.out_dir, 'test_rcm_graph_rcm_inv'),
                        graph, fmt='%d %d %d\n')

        assert_((graph0.indptr == graph.indptr).all())
        assert_((graph0.indices == graph.indices).all())

        return True
Beispiel #10
0
def refine_mesh(filename, level):
    """
    Uniformly refine `level`-times a mesh given by `filename`.

    The refined mesh is saved to a file with name constructed from base
    name of `filename` and `level`-times appended `'_r'` suffix.

    Parameters
    ----------
    filename : str
        The mesh file name.
    level : int
        The refinement level.
    """
    import os
    from sfepy.base.base import output
    from sfepy.fem import Mesh, Domain

    if level > 0:
        mesh = Mesh.from_file(filename)
        domain = Domain(mesh.name, mesh)
        for ii in range(level):
            output('refine %d...' % ii)
            domain = domain.refine()
            output('... %d nodes %d elements'
                   % (domain.shape.n_nod, domain.shape.n_el))

        suffix = os.path.splitext(filename)[1]
        filename = domain.name + suffix

        domain.mesh.write(filename, io='auto')

    return filename
Beispiel #11
0
    def from_conf(conf, options):
        mesh = Mesh.from_file("meshes/2d/square_unit_tri.mesh", prefix_dir=sfepy.data_dir)
        domain = Domain("domain", mesh)

        omega = domain.create_region("Omega", "all")

        field = H1NodalVolumeField("linear", nm.float64, "scalar", omega, approx_order=1)

        test = Test(conf=conf, options=options, omega=omega, field=field)
        return test
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()

    mesh = Mesh.from_file(data_dir + "/meshes/2d/rectangle_tri.mesh")
    domain = Domain("domain", mesh)

    min_x, max_x = domain.get_mesh_bounding_box()[:, 0]
    eps = 1e-8 * (max_x - min_x)
    omega = domain.create_region("Omega", "all")
    gamma1 = domain.create_region("Gamma1", "nodes in x < %.10f" % (min_x + eps))
    gamma2 = domain.create_region("Gamma2", "nodes in x > %.10f" % (max_x - eps))

    field = Field("fu", nm.float64, "vector", omega, space="H1", poly_space_base="lagrange", approx_order=2)

    u = FieldVariable("u", "unknown", field, mesh.dim)
    v = FieldVariable("v", "test", field, mesh.dim, primary_var_name="u")

    m = Material("m", lam=1.0, mu=1.0)
    f = Material("f", val=[[0.02], [0.01]])

    integral = Integral("i", order=3)

    t1 = Term.new("dw_lin_elastic_iso(m.lam, m.mu, v, u)", integral, omega, m=m, v=v, u=u)
    t2 = Term.new("dw_volume_lvf(f.val, v)", integral, omega, f=f, v=v)
    eq = Equation("balance", t1 + t2)
    eqs = Equations([eq])

    fix_u = EssentialBC("fix_u", gamma1, {"u.all": 0.0})

    bc_fun = Function("shift_u_fun", shift_u_fun, extra_args={"shift": 0.01})
    shift_u = EssentialBC("shift_u", gamma2, {"u.0": bc_fun})

    ls = ScipyDirect({})

    nls_status = IndexedStruct()
    nls = Newton({}, lin_solver=ls, status=nls_status)

    pb = ProblemDefinition("elasticity", equations=eqs, nls=nls, ls=ls)
    pb.save_regions_as_groups("regions")

    pb.time_update(ebcs=Conditions([fix_u, shift_u]))

    vec = pb.solve()
    print nls_status

    pb.save_state("linear_elasticity.vtk", vec)

    if options.show:
        view = Viewer("linear_elasticity.vtk")
        view(vector_mode="warp_norm", rel_scaling=2, is_scalar_bar=True, is_wireframe=True)
Beispiel #13
0
    def from_conf(conf, options):
        mesh = Mesh.from_file('meshes/2d/square_unit_tri.mesh',
                              prefix_dir=sfepy.data_dir)
        domain = Domain('domain', mesh)

        omega = domain.create_region('Omega', 'all')

        field = Field('linear', nm.float64, 'scalar', omega,
                      space='H1', poly_space_base='lagrange', approx_order=1)

        test = Test(conf=conf, options=options, omega=omega, field=field)
        return test
Beispiel #14
0
    def from_conf(conf, options):
        mesh = Mesh.from_file('meshes/2d/square_unit_tri.mesh',
                              prefix_dir=sfepy.data_dir)
        domain = Domain('domain', mesh)

        omega = domain.create_region('Omega', 'all')

        field = H1NodalVolumeField('linear', nm.float64, 'scalar', omega,
                                   approx_order=1)

        test = Test(conf=conf, options=options, omega=omega, field=field)
        return test
Beispiel #15
0
def main():
    parser = OptionParser(usage=usage)
    parser.add_option("-s", "--scale", metavar='scale',
                      action="store", dest="scale",
                      default=None, help=help['scale'])
    parser.add_option("-f", "--format", metavar='format',
                      action="store", type='string', dest="format",
                      default=None, help=help['format'])
    parser.add_option("-l", "--list", action="store_true", 
                      dest="list", help=help['list'])
    (options, args) = parser.parse_args()

    if options.list:
        output_writable_meshes()
        sys.exit(0)

    if len(args) != 2:
        parser.print_help()
        sys.exit(1)
    
    scale = options.scale
    if scale is not None:
        try:
            try:
                scale = float(scale)
            except ValueError:
                scale = [float(ii) for ii in scale.split(',')]
            scale = nm.array(scale, dtype=nm.float64, ndmin=1)
        except:
            output('bad scale! (%s)' % scale)
            parser.print_help()
            sys.exit(1)
        
    filename_in, filename_out = args
    
    mesh = Mesh.from_file(filename_in)

    if scale is not None:
        if len(scale) == 1:
            tr = nm.eye(mesh.dim, dtype=nm.float64) * scale
        elif len(scale) == mesh.dim:
            tr = nm.diag(scale)
        else:
            raise ValueError('bad scale! (%s)' % scale)
        mesh.transform_coors(tr)

    io = MeshIO.for_format(filename_out, format=options.format,
                           writable=True)

    output('writing %s...' % filename_out)
    mesh.write(filename_out, io=io)
    output('...done')
Beispiel #16
0
    def test_normals(self):
        """
        Check orientations of surface normals on the reference elements.
        """
        import sfepy
        from sfepy.fem import Mesh, Domain, Integral
        from sfepy.fem.poly_spaces import PolySpace
        from sfepy.fem.mappings import SurfaceMapping
        from sfepy.linalg import normalize_vectors

        ok = True

        for geom in ['2_3', '2_4', '3_4', '3_8']:
            mesh = Mesh.from_file('meshes/elements/%s_1.mesh' % geom,
                                  prefix_dir=sfepy.data_dir)
            domain = Domain('domain', mesh)
            surface = domain.create_region('Surface', 'vertices of surface',
                                           'facet')
            domain.create_surface_group(surface)

            sd = domain.surface_groups[0][surface.name]

            coors = domain.get_mesh_coors()
            gel = domain.geom_els[geom].surface_facet
            ps = PolySpace.any_from_args('aux', gel, 1)

            mapping = SurfaceMapping(coors, sd.get_connectivity(), ps)

            integral = Integral('i', order=1)
            vals, weights = integral.get_qp(gel.name)

            # Evaluate just in the first quadrature point...
            geo = mapping.get_mapping(vals[:1], weights[:1])

            expected = expected_normals[geom].copy()
            normalize_vectors(expected)

            _ok = nm.allclose(expected,
                              geo.normal[:, 0, :, 0],
                              rtol=0.0,
                              atol=1e-14)
            self.report('%s: %s' % (geom, _ok))

            if not _ok:
                self.report('expected:')
                self.report(expected)
                self.report('actual:')
                self.report(geo.normal[:, 0, :, 0])

            ok = ok and _ok

        return ok
Beispiel #17
0
    def test_read_meshes( self ):
        """Try to read all listed meshes."""
        from sfepy.fem import Mesh

        meshes = {}
        for ii, filename in enumerate( filename_meshes ):
            self.report( '%d. mesh: %s' % (ii + 1, filename) )
            mesh = Mesh.from_file( filename )
            self.report( 'read ok' )
            meshes[filename] = mesh

        self.meshes = meshes

        return True
Beispiel #18
0
    def test_normals(self):
        """
        Check orientations of surface normals on the reference elements.
        """
        import sfepy
        from sfepy.fem import Mesh, Domain, Integral
        from sfepy.fem.poly_spaces import PolySpace
        from sfepy.fem.mappings import SurfaceMapping
        from sfepy.linalg import normalize_vectors

        ok = True

        for geom in ['2_3', '2_4', '3_4', '3_8']:
            mesh = Mesh.from_file('meshes/elements/%s_1.mesh' % geom,
                                  prefix_dir=sfepy.data_dir)
            domain = Domain('domain', mesh)
            surface = domain.create_region('Surface', 'nodes of surface')
            domain.create_surface_group(surface)

            sd = domain.surface_groups[0][surface.name]

            coors = domain.get_mesh_coors()
            gel = domain.geom_els[geom].surface_facet
            ps = PolySpace.any_from_args('aux', gel, 1)

            mapping = SurfaceMapping(coors, sd.get_connectivity(), ps)

            integral = Integral('i', order=1)
            vals, weights = integral.get_qp(gel.name)

            # Evaluate just in the first quadrature point...
            geo = mapping.get_mapping(vals[:1], weights[:1])

            expected = expected_normals[geom].copy()
            normalize_vectors(expected)

            _ok = nm.allclose(expected, geo.normal[:, 0, :, 0],
                              rtol=0.0, atol=1e-14)
            self.report('%s: %s' % (geom, _ok))

            if not _ok:
                self.report('expected:')
                self.report(expected)
                self.report('actual:')
                self.report(geo.normal[:, 0, :, 0])

            ok = ok and _ok

        return ok
Beispiel #19
0
def mesh():
    if len(sys.argv) == 3:
        geom_filename = sys.argv[1]
        vtk_filename = sys.argv[2]
    else:
        print "Usage: %s <gmsh_filename> <mesh_filename>" % sys.argv[0]
        return

    os.system("gmsh -0 %s -o tmp/x.geo" % geom_filename)
    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(vtk_filename, io="auto")
Beispiel #20
0
    def test_projection_tri_quad(self):
        from sfepy.fem.projections import make_l2_projection

        source = FieldVariable('us', 'unknown', self.field, 1)

        coors = self.field.get_coor()
        vals = nm.sin(2.0 * nm.pi * coors[:, 0] * coors[:, 1])
        source.data_from_any(vals)

        name = op.join(self.options.out_dir,
                       'test_projection_tri_quad_source.vtk')
        source.save_as_mesh(name)

        mesh = Mesh.from_file('meshes/2d/square_quad.mesh',
                              prefix_dir=sfepy.data_dir)
        domain = Domain('domain', mesh)

        omega = domain.create_region('Omega', 'all')

        field = H1NodalVolumeField('bilinear',
                                   nm.float64,
                                   'scalar',
                                   omega,
                                   approx_order=1)

        target = FieldVariable('ut', 'unknown', field, 1)

        make_l2_projection(target, source)

        name = op.join(self.options.out_dir,
                       'test_projection_tri_quad_target.vtk')
        target.save_as_mesh(name)

        bbox = self.field.domain.get_mesh_bounding_box()
        x = nm.linspace(bbox[0, 0] + 0.001, bbox[1, 0] - 0.001, 20)
        y = nm.linspace(bbox[0, 1] + 0.001, bbox[1, 1] - 0.001, 20)

        xx, yy = nm.meshgrid(x, y)
        test_coors = nm.c_[xx.ravel(), yy.ravel()].copy()

        vec1 = source.evaluate_at(test_coors)
        vec2 = target.evaluate_at(test_coors)

        ok = (nm.abs(vec1 - vec2) < 0.01).all()

        return ok
Beispiel #21
0
    def from_conf(conf, options):
        from sfepy.fem import Mesh, Domain, Integral

        domains = []
        for filename in filename_meshes:
            mesh = Mesh.from_file(filename)
            domain = Domain('domain_%s' % mesh.name.replace(data_dir, ''),
                            mesh)
            domain.create_region('Omega', 'all')
            domain.create_region('Gamma', 'vertices of surface', 'facet')

            domains.append(domain)

        integral = Integral('i', order=3)

        test = Test(domains=domains, integral=integral,
                    conf=conf, options=options)
        return test
Beispiel #22
0
    def test_projection_tri_quad(self):
        from sfepy.fem.projections import make_l2_projection

        source = FieldVariable('us', 'unknown', self.field, 1)

        coors = self.field.get_coor()
        vals = nm.sin(2.0 * nm.pi * coors[:,0] * coors[:,1])
        source.data_from_any(vals)

        name = op.join(self.options.out_dir,
                       'test_projection_tri_quad_source.vtk')
        source.save_as_mesh(name)

        mesh = Mesh.from_file('meshes/2d/square_quad.mesh',
                              prefix_dir=sfepy.data_dir)
        domain = Domain('domain', mesh)

        omega = domain.create_region('Omega', 'all')


        field = Field('bilinear', nm.float64, 'scalar', omega,
                      space='H1', poly_space_base='lagrange', approx_order=1)

        target = FieldVariable('ut', 'unknown', field, 1)

        make_l2_projection(target, source)

        name = op.join(self.options.out_dir,
                       'test_projection_tri_quad_target.vtk')
        target.save_as_mesh(name)

        bbox = self.field.domain.get_mesh_bounding_box()
        x = nm.linspace(bbox[0, 0] + 0.001, bbox[1, 0] - 0.001, 20)
        y = nm.linspace(bbox[0, 1] + 0.001, bbox[1, 1] - 0.001, 20)

        xx, yy = nm.meshgrid(x, y)
        test_coors = nm.c_[xx.ravel(), yy.ravel()].copy()

        vec1 = source.evaluate_at(test_coors)
        vec2 = target.evaluate_at(test_coors)

        ok = (nm.abs(vec1 - vec2) < 0.01).all()

        return ok
Beispiel #23
0
def mesh_hook(mesh, mode):
    """
    Load and refine a mesh here.
    """
    if mode == 'read':
        mesh = Mesh.from_file(base_mesh)
        domain = Domain(mesh.name, mesh)
        for ii in range(3):
            output('refine %d...' % ii)
            domain = domain.refine()
            output('... %d nodes %d elements' %
                   (domain.shape.n_nod, domain.shape.n_el))

        domain.mesh.name = '2_4_2_refined'

        return domain.mesh

    elif mode == 'write':
        pass
Beispiel #24
0
    def from_conf(conf, options):
        from sfepy.fem import Mesh, Domain, Integral

        domains = []
        for filename in filename_meshes:
            mesh = Mesh.from_file(filename)
            domain = Domain('domain_%s' % mesh.name.replace(data_dir, ''),
                            mesh)
            domain.create_region('Omega', 'all')
            domain.create_region('Gamma', 'nodes of surface')

            domains.append(domain)

        integrals = {'Omega' : Integral('iv', kind='v', order=3),
                     'Gamma' : Integral('is', kind='s', order=3)}

        test = Test(domains=domains, integrals=integrals,
                    conf=conf, options=options)
        return test
Beispiel #25
0
def mesh_hook(mesh, mode):
    """
    Load and refine a mesh here.
    """
    if mode == 'read':
        mesh = Mesh.from_file(base_mesh)
        domain = Domain(mesh.name, mesh)
        for ii in range(3):
            output('refine %d...' % ii)
            domain = domain.refine()
            output('... %d nodes %d elements'
                   % (domain.shape.n_nod, domain.shape.n_el))

        domain.mesh.name = '2_4_2_refined'

        return domain.mesh

    elif mode == 'write':
        pass
Beispiel #26
0
def mesh():
    if len( sys.argv ) == 3:
        geom_filename = sys.argv[1]
        vtk_filename = sys.argv[2]
    if len( sys.argv ) == 2:
        geom_filename = sys.argv[1]
        vtk_filename = "tmp/t.1.vtk"
    else:
        geom_filename = "database/box.geo"
        vtk_filename = "tmp/t.1.vtk"

    os.system( "gmsh -0 %s -o tmp/x.geo" % geom_filename )
    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( vtk_filename, io = "auto" )
    def from_conf(conf, options):
        from sfepy.fem import Mesh, Domain, Integral

        domains = []
        for filename in filename_meshes:
            mesh = Mesh.from_file(filename)
            domain = Domain('domain_%s' % mesh.name.replace(data_dir, ''),
                            mesh)
            domain.create_region('Omega', 'all')
            domain.create_region('Gamma', 'vertices of surface', 'facet')

            domains.append(domain)

        integral = Integral('i', order=3)

        test = Test(domains=domains,
                    integral=integral,
                    conf=conf,
                    options=options)
        return test
Beispiel #28
0
    def test_rcm(self):
        from sfepy import data_dir
        from sfepy.linalg import rcm, permute_in_place, save_sparse_txt
        from sfepy.fem import Mesh

        filename = data_dir + '/meshes/2d/special/square_triquad.mesh'

        self.report('testing reversed Cuthill-McKee permutation')

        conf_dir = op.dirname(__file__)
        mesh = Mesh.from_file(filename, prefix_dir=conf_dir)

        graph = mesh.create_conn_graph()
        graph0 = graph.copy()

        save_sparse_txt(op.join(self.options.out_dir, 'test_rcm_graph_orig'),
                        graph,
                        fmt='%d %d %d\n')

        perm = rcm(graph)

        permute_in_place(graph, perm)
        save_sparse_txt(op.join(self.options.out_dir, 'test_rcm_graph_rcm'),
                        graph,
                        fmt='%d %d %d\n')

        assert_((graph0.indptr != graph.indptr).any())
        assert_((graph0.indices != graph.indices).any())

        permute_in_place(graph, perm, inverse=True)
        save_sparse_txt(op.join(self.options.out_dir,
                                'test_rcm_graph_rcm_inv'),
                        graph,
                        fmt='%d %d %d\n')

        assert_((graph0.indptr == graph.indptr).all())
        assert_((graph0.indices == graph.indices).all())

        return True
Beispiel #29
0
def main():
    parser = OptionParser(usage=usage, version='%prog')
    options, args = parser.parse_args()

    if len(args) == 1:
        filename = args[0]
    else:
        parser.print_help(),
        return

    mesh = Mesh.from_file(filename)
    output('Mesh:')
    output('  dimension: %d, vertices: %d, elements: %d' %
           (mesh.dim, mesh.n_nod, mesh.n_el))

    domain = Domain('domain', mesh)
    output(domain.cmesh)
    domain.cmesh.cprint(1)
    dim = domain.cmesh.dim

    ax = pc.plot_wireframe(None, domain.cmesh)

    ax = pc.plot_entities(ax, domain.cmesh, 0, 'k')
    ax = pc.label_global_entities(ax, domain.cmesh, 0, 'k', 12)
    ax = pc.label_local_entities(ax, domain.cmesh, 0, 'k', 8)

    ax = pc.plot_entities(ax, domain.cmesh, 1, 'b')
    ax = pc.label_global_entities(ax, domain.cmesh, 1, 'b', 12)
    ax = pc.label_local_entities(ax, domain.cmesh, 1, 'b', 8)

    if dim == 3:
        ax = pc.plot_entities(ax, domain.cmesh, 2, 'g')
        ax = pc.label_global_entities(ax, domain.cmesh, 2, 'g', 12)
        ax = pc.label_local_entities(ax, domain.cmesh, 2, 'g', 8)

    ax = pc.plot_entities(ax, domain.cmesh, dim, 'r')
    ax = pc.label_global_entities(ax, domain.cmesh, dim, 'r', 12)

    pc.plt.show()
Beispiel #30
0
def main():
    parser = OptionParser(usage=usage, version='%prog')
    options, args = parser.parse_args()

    if len(args) == 1:
        filename = args[0]
    else:
        parser.print_help(),
        return

    mesh = Mesh.from_file(filename)
    output('Mesh:')
    output('  dimension: %d, vertices: %d, elements: %d'
           % (mesh.dim, mesh.n_nod, mesh.n_el))

    domain = Domain('domain', mesh)
    output(domain.cmesh)
    domain.cmesh.cprint(1)
    dim = domain.cmesh.dim

    ax = pc.plot_wireframe(None, domain.cmesh)

    ax = pc.plot_entities(ax, domain.cmesh, 0, 'k')
    ax = pc.label_global_entities(ax, domain.cmesh, 0, 'k', 12)
    ax = pc.label_local_entities(ax, domain.cmesh, 0, 'k', 8)

    ax = pc.plot_entities(ax, domain.cmesh, 1, 'b')
    ax = pc.label_global_entities(ax, domain.cmesh, 1, 'b', 12)
    ax = pc.label_local_entities(ax, domain.cmesh, 1, 'b', 8)

    if dim == 3:
        ax = pc.plot_entities(ax, domain.cmesh, 2, 'g')
        ax = pc.label_global_entities(ax, domain.cmesh, 2, 'g', 12)
        ax = pc.label_local_entities(ax, domain.cmesh, 2, 'g', 8)

    ax = pc.plot_entities(ax, domain.cmesh, dim, 'r')
    ax = pc.label_global_entities(ax, domain.cmesh, dim, 'r', 12)

    pc.plt.show()
Beispiel #31
0
    def test_projection_tri_quad(self):
        from sfepy.fem.projections import make_l2_projection

        source = FieldVariable("us", "unknown", self.field, 1)

        coors = self.field.get_coor()
        vals = nm.sin(2.0 * nm.pi * coors[:, 0] * coors[:, 1])
        source.data_from_any(vals)

        name = op.join(self.options.out_dir, "test_projection_tri_quad_source.vtk")
        source.save_as_mesh(name)

        mesh = Mesh.from_file("meshes/2d/square_quad.mesh", prefix_dir=sfepy.data_dir)
        domain = Domain("domain", mesh)

        omega = domain.create_region("Omega", "all")

        field = H1NodalVolumeField("bilinear", nm.float64, "scalar", omega, approx_order=1)

        target = FieldVariable("ut", "unknown", field, 1)

        make_l2_projection(target, source)

        name = op.join(self.options.out_dir, "test_projection_tri_quad_target.vtk")
        target.save_as_mesh(name)

        bbox = self.field.domain.get_mesh_bounding_box()
        x = nm.linspace(bbox[0, 0] + 0.001, bbox[1, 0] - 0.001, 20)
        y = nm.linspace(bbox[0, 1] + 0.001, bbox[1, 1] - 0.001, 20)

        xx, yy = nm.meshgrid(x, y)
        test_coors = nm.c_[xx.ravel(), yy.ravel()].copy()

        vec1 = source.evaluate_at(test_coors)
        vec2 = target.evaluate_at(test_coors)

        ok = (nm.abs(vec1 - vec2) < 0.01).all()

        return ok
Beispiel #32
0
def main():
    parser = OptionParser(usage=usage, version='%prog')
    parser.add_option('-b',
                      '--basis',
                      metavar='name',
                      action='store',
                      dest='basis',
                      default='lagrange',
                      help=help['basis'])
    parser.add_option('-d',
                      '--derivative',
                      metavar='d',
                      type=int,
                      action='store',
                      dest='derivative',
                      default=0,
                      help=help['derivative'])
    parser.add_option('-n',
                      '--max-order',
                      metavar='order',
                      type=int,
                      action='store',
                      dest='max_order',
                      default=2,
                      help=help['max_order'])
    parser.add_option('-g',
                      '--geometry',
                      metavar='name',
                      action='store',
                      dest='geometry',
                      default='2_4',
                      help=help['geometry'])
    parser.add_option('-m',
                      '--mesh',
                      metavar='mesh',
                      action='store',
                      dest='mesh',
                      default=None,
                      help=help['mesh'])
    parser.add_option('',
                      '--permutations',
                      metavar='permutations',
                      action='store',
                      dest='permutations',
                      default=None,
                      help=help['permutations'])
    parser.add_option('',
                      '--dofs',
                      metavar='dofs',
                      action='store',
                      dest='dofs',
                      default=None,
                      help=help['dofs'])
    parser.add_option('-l',
                      '--lin-options',
                      metavar='options',
                      action='store',
                      dest='lin_options',
                      default='min_level=2,max_level=5,eps=1e-3',
                      help=help['lin_options'])
    parser.add_option('',
                      '--plot-dofs',
                      action='store_true',
                      dest='plot_dofs',
                      default=False,
                      help=help['plot_dofs'])
    options, args = parser.parse_args()

    if len(args) == 1:
        output_dir = args[0]
    else:
        parser.print_help(),
        return

    output('polynomial space:', options.basis)
    output('max. order:', options.max_order)

    lin = Struct(kind='adaptive', min_level=2, max_level=5, eps=1e-3)
    for opt in options.lin_options.split(','):
        key, val = opt.split('=')
        setattr(lin, key, eval(val))

    if options.mesh is None:
        dim, n_ep = int(options.geometry[0]), int(options.geometry[2])
        output('reference element geometry:')
        output('  dimension: %d, vertices: %d' % (dim, n_ep))

        gel = GeometryElement(options.geometry)
        gps = PolySpace.any_from_args(None, gel, 1, base=options.basis)
        ps = PolySpace.any_from_args(None,
                                     gel,
                                     options.max_order,
                                     base=options.basis)

        n_digit, _format = get_print_info(ps.n_nod, fill='0')
        name_template = os.path.join(output_dir, 'bf_%s.vtk' % _format)
        for ip in get_dofs(options.dofs, ps.n_nod):
            output('shape function %d...' % ip)

            def eval_dofs(iels, rx):
                if options.derivative == 0:
                    bf = ps.eval_base(rx).squeeze()
                    rvals = bf[None, :, ip:ip + 1]

                else:
                    bfg = ps.eval_base(rx, diff=True)
                    rvals = bfg[None, ..., ip]

                return rvals

            def eval_coors(iels, rx):
                bf = gps.eval_base(rx).squeeze()
                coors = nm.dot(bf, gel.coors)[None, ...]
                return coors

            (level, coors, conn, vdofs,
             mat_ids) = create_output(eval_dofs,
                                      eval_coors,
                                      1,
                                      ps,
                                      min_level=lin.min_level,
                                      max_level=lin.max_level,
                                      eps=lin.eps)
            out = {
                'bf':
                Struct(name='output_data',
                       mode='vertex',
                       data=vdofs,
                       var_name='bf',
                       dofs=None)
            }

            mesh = Mesh.from_data('bf_mesh', coors, None, [conn], [mat_ids],
                                  [options.geometry])

            name = name_template % ip
            ensure_path(name)
            mesh.write(name, out=out)

            output('...done (%s)' % name)

    else:
        mesh = Mesh.from_file(options.mesh)
        output('mesh geometry:')
        output('  dimension: %d, vertices: %d, elements: %d' %
               (mesh.dim, mesh.n_nod, mesh.n_el))

        if options.permutations:
            if options.permutations == 'all':
                from sfepy.linalg import cycle
                gel = GeometryElement(mesh.descs[0])
                n_perms = gel.get_conn_permutations().shape[0]
                all_permutations = [ii for ii in cycle(mesh.n_el * [n_perms])]

            else:
                all_permutations = [
                    int(ii) for ii in options.permutations.split(',')
                ]
                all_permutations = nm.array(all_permutations)
                np = len(all_permutations)
                all_permutations.shape = (np / mesh.n_el, mesh.n_el)

            output('using connectivity permutations:\n', all_permutations)

        else:
            all_permutations = [None]

        for ip, permutations in enumerate(all_permutations):
            if permutations is None:
                suffix = ''

            else:
                suffix = '_' + '_'.join('%d' % ii for ii in permutations)

            save_basis_on_mesh(mesh, options, output_dir, lin, permutations,
                               suffix)
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()

    mesh = Mesh.from_file(data_dir + '/meshes/2d/rectangle_tri.mesh')
    domain = Domain('domain', mesh)

    min_x, max_x = domain.get_mesh_bounding_box()[:,0]
    eps = 1e-8 * (max_x - min_x)
    omega = domain.create_region('Omega', 'all')
    gamma1 = domain.create_region('Gamma1',
                                  'nodes in x < %.10f' % (min_x + eps))
    gamma2 = domain.create_region('Gamma2',
                                  'nodes in x > %.10f' % (max_x - eps))

    field = Field('fu', nm.float64, 'vector', omega,
                  space='H1', poly_space_base='lagrange', approx_order=2)

    u = FieldVariable('u', 'unknown', field, mesh.dim)
    v = FieldVariable('v', 'test', field, mesh.dim, primary_var_name='u')

    m = Material('m', lam=1.0, mu=1.0)
    f = Material('f', val=[[0.02], [0.01]])

    integral = Integral('i', order=3)

    t1 = Term.new('dw_lin_elastic_iso(m.lam, m.mu, v, u)',
         integral, omega, m=m, v=v, u=u)
    t2 = Term.new('dw_volume_lvf(f.val, v)', integral, omega, f=f, v=v)
    eq = Equation('balance', t1 + t2)
    eqs = Equations([eq])

    fix_u = EssentialBC('fix_u', gamma1, {'u.all' : 0.0})

    bc_fun = Function('shift_u_fun', shift_u_fun, extra_args={'shift' : 0.01})
    shift_u = EssentialBC('shift_u', gamma2, {'u.0' : bc_fun})

    ls = ScipyDirect({})

    nls_status = IndexedStruct()
    nls = Newton({}, lin_solver=ls, status=nls_status)

    pb = ProblemDefinition('elasticity', equations=eqs, nls=nls, ls=ls)
    pb.save_regions_as_groups('regions')

    pb.time_update(ebcs=Conditions([fix_u, shift_u]))

    vec = pb.solve()
    print nls_status

    pb.save_state('linear_elasticity.vtk', vec)

    if options.show:
        view = Viewer('linear_elasticity.vtk')
        view(vector_mode='warp_norm', rel_scaling=2,
             is_scalar_bar=True, is_wireframe=True)
Beispiel #34
0
def main():
    parser = OptionParser(usage=usage, version='%prog')
    parser.add_option('-b',
                      '--basis',
                      metavar='name',
                      action='store',
                      dest='basis',
                      default='lagrange',
                      help=help['basis'])
    parser.add_option('-d',
                      '--derivative',
                      metavar='d',
                      type=int,
                      action='store',
                      dest='derivative',
                      default=0,
                      help=help['derivative'])
    parser.add_option('-n',
                      '--max-order',
                      metavar='order',
                      type=int,
                      action='store',
                      dest='max_order',
                      default=2,
                      help=help['max_order'])
    parser.add_option('-g',
                      '--geometry',
                      metavar='name',
                      action='store',
                      dest='geometry',
                      default='2_4',
                      help=help['geometry'])
    parser.add_option('-m',
                      '--mesh',
                      metavar='mesh',
                      action='store',
                      dest='mesh',
                      default=None,
                      help=help['mesh'])
    parser.add_option('',
                      '--permutations',
                      metavar='permutations',
                      action='store',
                      dest='permutations',
                      default=None,
                      help=help['permutations'])
    parser.add_option('',
                      '--dofs',
                      metavar='dofs',
                      action='store',
                      dest='dofs',
                      default=None,
                      help=help['dofs'])
    parser.add_option('-l',
                      '--lin-options',
                      metavar='options',
                      action='store',
                      dest='lin_options',
                      default='min_level=2,max_level=5,eps=1e-3',
                      help=help['lin_options'])
    parser.add_option('',
                      '--plot-dofs',
                      action='store_true',
                      dest='plot_dofs',
                      default=False,
                      help=help['plot_dofs'])
    options, args = parser.parse_args()

    if len(args) == 1:
        output_dir = args[0]
    else:
        parser.print_help(),
        return

    output('polynomial space:', options.basis)
    output('max. order:', options.max_order)

    lin = Struct(kind='adaptive', min_level=2, max_level=5, eps=1e-3)
    for opt in options.lin_options.split(','):
        key, val = opt.split('=')
        setattr(lin, key, eval(val))

    if options.mesh is None:
        dim, n_ep = int(options.geometry[0]), int(options.geometry[2])
        output('reference element geometry:')
        output('  dimension: %d, vertices: %d' % (dim, n_ep))

        gel = GeometryElement(options.geometry)
        gps = PolySpace.any_from_args(None, gel, 1, base=options.basis)
        ps = PolySpace.any_from_args(None,
                                     gel,
                                     options.max_order,
                                     base=options.basis)

        n_digit, _format = get_print_info(ps.n_nod, fill='0')
        name_template = os.path.join(output_dir, 'bf_%s.vtk' % _format)
        for ip in get_dofs(options.dofs, ps.n_nod):
            output('shape function %d...' % ip)

            def eval_dofs(iels, rx):
                if options.derivative == 0:
                    bf = ps.eval_base(rx).squeeze()
                    rvals = bf[None, :, ip:ip + 1]

                else:
                    bfg = ps.eval_base(rx, diff=True)
                    rvals = bfg[None, ..., ip]

                return rvals

            def eval_coors(iels, rx):
                bf = gps.eval_base(rx).squeeze()
                coors = nm.dot(bf, gel.coors)[None, ...]
                return coors

            (level, coors, conn, vdofs,
             mat_ids) = create_output(eval_dofs,
                                      eval_coors,
                                      1,
                                      ps,
                                      min_level=lin.min_level,
                                      max_level=lin.max_level,
                                      eps=lin.eps)
            out = {
                'bf':
                Struct(name='output_data',
                       mode='vertex',
                       data=vdofs,
                       var_name='bf',
                       dofs=None)
            }

            mesh = Mesh.from_data('bf_mesh', coors, None, [conn], [mat_ids],
                                  [options.geometry])

            name = name_template % ip
            mesh.write(name, out=out)

            output('...done (%s)' % name)

    else:
        mesh = Mesh.from_file(options.mesh)
        output('mesh geometry:')
        output('  dimension: %d, vertices: %d, elements: %d' %
               (mesh.dim, mesh.n_nod, mesh.n_el))

        domain = Domain('domain', mesh)

        if options.permutations:
            permutations = [int(ii) for ii in options.permutations.split(',')]
            output('using connectivity permutations:', permutations)
            for group in domain.iter_groups():
                perms = group.gel.get_conn_permutations()[permutations]
                offsets = nm.arange(group.shape.n_el) * group.shape.n_ep

                group.conn[:] = group.conn.take(perms + offsets[:, None])

            domain.setup_facets()

        omega = domain.create_region('Omega', 'all')
        field = Field.from_args('f',
                                nm.float64,
                                shape=1,
                                region=omega,
                                approx_order=options.max_order,
                                poly_space_base=options.basis)
        var = FieldVariable('u', 'unknown', field, 1)

        if options.plot_dofs:
            import sfepy.postprocess.plot_dofs as pd
            group = domain.groups[0]
            ax = pd.plot_mesh(None, mesh.coors, mesh.conns[0], group.gel.edges)
            ax = pd.plot_global_dofs(ax, field.get_coor(), field.aps[0].econn)
            ax = pd.plot_local_dofs(ax, field.get_coor(), field.aps[0].econn)
            if options.dofs is not None:
                ax = pd.plot_nodes(ax, field.get_coor(), field.aps[0].econn,
                                   field.aps[0].interp.poly_spaces['v'].nodes,
                                   get_dofs(options.dofs, var.n_dof))
            pd.plt.show()

        output('dofs: %d' % var.n_dof)

        vec = nm.empty(var.n_dof, dtype=var.dtype)
        n_digit, _format = get_print_info(var.n_dof, fill='0')
        name_template = os.path.join(output_dir, 'dof_%s.vtk' % _format)
        for ip in get_dofs(options.dofs, var.n_dof):
            output('dof %d...' % ip)

            vec.fill(0.0)
            vec[ip] = 1.0

            var.set_data(vec)

            if options.derivative == 0:
                out = var.create_output(vec, linearization=lin)

            else:
                out = create_expression_output('ev_grad.ie.Elements(u)',
                                               'u',
                                               'f', {'f': field},
                                               None,
                                               Variables([var]),
                                               mode='qp',
                                               verbose=False,
                                               min_level=lin.min_level,
                                               max_level=lin.max_level,
                                               eps=lin.eps)

            name = name_template % ip
            out['u'].mesh.write(name, out=out)

            output('...done (%s)' % name)
Beispiel #35
0
    def read_common(self, filename):
        self.io = MeshIO.any_from_filename(filename)
        self.step_range = (0, self.io.read_last_step())

        self.mesh = mesh = Mesh.from_file(filename)
        self.n_nod, self.dim = self.mesh.coors.shape
Beispiel #36
0
def main():
    parser = OptionParser(usage=usage, version='%prog')
    parser.add_option('-b', '--basis', metavar='name',
                      action='store', dest='basis',
                      default='lagrange', help=help['basis'])
    parser.add_option('-d', '--derivative', metavar='d', type=int,
                      action='store', dest='derivative',
                      default=0, help=help['derivative'])
    parser.add_option('-n', '--max-order', metavar='order', type=int,
                      action='store', dest='max_order',
                      default=2, help=help['max_order'])
    parser.add_option('-g', '--geometry', metavar='name',
                      action='store', dest='geometry',
                      default='2_4', help=help['geometry'])
    parser.add_option('-m', '--mesh', metavar='mesh',
                      action='store', dest='mesh',
                      default=None, help=help['mesh'])
    parser.add_option('', '--permutations', metavar='permutations',
                      action='store', dest='permutations',
                      default=None, help=help['permutations'])
    parser.add_option('', '--dofs', metavar='dofs',
                      action='store', dest='dofs',
                      default=None, help=help['dofs'])
    parser.add_option('-l', '--lin-options', metavar='options',
                      action='store', dest='lin_options',
                      default='min_level=2,max_level=5,eps=1e-3',
                      help=help['lin_options'])
    parser.add_option('', '--plot-dofs',
                      action='store_true', dest='plot_dofs',
                      default=False, help=help['plot_dofs'])
    options, args = parser.parse_args()

    if len(args) == 1:
        output_dir = args[0]
    else:
        parser.print_help(),
        return

    output('polynomial space:', options.basis)
    output('max. order:', options.max_order)

    lin = Struct(kind='adaptive', min_level=2, max_level=5, eps=1e-3)
    for opt in options.lin_options.split(','):
        key, val = opt.split('=')
        setattr(lin, key, eval(val))

    if options.mesh is None:
        dim, n_ep = int(options.geometry[0]), int(options.geometry[2])
        output('reference element geometry:')
        output('  dimension: %d, vertices: %d' % (dim, n_ep))

        gel = GeometryElement(options.geometry)
        gps = PolySpace.any_from_args(None, gel, 1,
                                      base=options.basis)
        ps = PolySpace.any_from_args(None, gel, options.max_order,
                                     base=options.basis)

        n_digit, _format = get_print_info(ps.n_nod, fill='0')
        name_template = os.path.join(output_dir, 'bf_%s.vtk' % _format)
        for ip in get_dofs(options.dofs, ps.n_nod):
            output('shape function %d...' % ip)

            def eval_dofs(iels, rx):
                if options.derivative == 0:
                    bf = ps.eval_base(rx).squeeze()
                    rvals = bf[None, :, ip:ip+1]

                else:
                    bfg = ps.eval_base(rx, diff=True)
                    rvals = bfg[None, ..., ip]

                return rvals

            def eval_coors(iels, rx):
                bf = gps.eval_base(rx).squeeze()
                coors = nm.dot(bf, gel.coors)[None, ...]
                return coors

            (level, coors, conn,
             vdofs, mat_ids) = create_output(eval_dofs, eval_coors, 1,
                                             ps, min_level=lin.min_level,
                                             max_level=lin.max_level,
                                             eps=lin.eps)
            out = {
                'bf' : Struct(name='output_data',
                              mode='vertex', data=vdofs,
                              var_name='bf', dofs=None)
            }

            mesh = Mesh.from_data('bf_mesh', coors, None, [conn], [mat_ids],
                                  [options.geometry])

            name = name_template % ip
            mesh.write(name, out=out)

            output('...done (%s)' % name)

    else:
        mesh = Mesh.from_file(options.mesh)
        output('mesh geometry:')
        output('  dimension: %d, vertices: %d, elements: %d'
               % (mesh.dim, mesh.n_nod, mesh.n_el))

        domain = Domain('domain', mesh)

        if options.permutations:
            permutations = [int(ii) for ii in options.permutations.split(',')]
            output('using connectivity permutations:', permutations)
            for group in domain.iter_groups():
                perms = group.gel.get_conn_permutations()[permutations]
                offsets = nm.arange(group.shape.n_el) * group.shape.n_ep

                group.conn[:] = group.conn.take(perms + offsets[:, None])

            domain.setup_facets()

        omega = domain.create_region('Omega', 'all')
        field = Field.from_args('f', nm.float64, shape=1, region=omega,
                                approx_order=options.max_order,
                                poly_space_base=options.basis)
        var = FieldVariable('u', 'unknown', field, 1)

        if options.plot_dofs:
            import sfepy.postprocess.plot_dofs as pd
            group = domain.groups[0]
            ax = pd.plot_mesh(None, mesh.coors, mesh.conns[0], group.gel.edges)
            ax = pd.plot_global_dofs(ax, field.get_coor(), field.aps[0].econn)
            ax = pd.plot_local_dofs(ax, field.get_coor(), field.aps[0].econn)
            pd.plt.show()

        output('dofs: %d' % var.n_dof)

        vec = nm.empty(var.n_dof, dtype=var.dtype)
        n_digit, _format = get_print_info(var.n_dof, fill='0')
        name_template = os.path.join(output_dir, 'dof_%s.vtk' % _format)
        for ip in get_dofs(options.dofs, var.n_dof):
            output('dof %d...' % ip)

            vec.fill(0.0)
            vec[ip] = 1.0

            var.data_from_any(vec)

            if options.derivative == 0:
                out = var.create_output(vec, linearization=lin)

            else:
                out = create_expression_output('ev_grad.ie.Elements(u)',
                                               'u', 'f', {'f' : field}, None,
                                               Variables([var]),
                                               mode='qp', verbose=False,
                                               min_level=lin.min_level,
                                               max_level=lin.max_level,
                                               eps=lin.eps)

            name = name_template % ip
            out['u'].mesh.write(name, out=out)

            output('...done (%s)' % name)
Beispiel #37
0
    def read_common(self, filename):
        self.io = MeshIO.any_from_filename(filename)
        self.step_range = (0, self.io.read_last_step())

        self.mesh = mesh = Mesh.from_file(filename)
        self.n_nod, self.dim = self.mesh.coors.shape
Beispiel #38
0
def main():
    parser = OptionParser(usage=usage, version="%prog " + sfepy.__version__)
    parser.add_option("-m",
                      "--mesh",
                      action="store_true",
                      dest="save_mesh",
                      default=True,
                      help="save surface mesh [default: %default]")
    parser.add_option("-n",
                      "--no-surface",
                      action="store_true",
                      dest="no_surface",
                      default=False,
                      help="do not output surface [default: %default]")
    (options, args) = parser.parse_args()

    if (len(args) == 2):
        filename_in = args[0]
        filename_out = args[1]
    else:
        parser.print_help(),
        return

    if (filename_in == '-'):
        file_in = sys.stdin
    else:
        file_in = open(filename_in, "r")

    mesh = Mesh.from_file(filename_in)

    if (filename_in != '-'):
        file_in.close()

    domain = Domain('domain', mesh)
    domain.setup_groups()

    if domain.has_faces():
        domain.fix_element_orientation()
        domain.setup_facets(create_edges=False)

        lst, surf_faces = domain.surface_faces()

        surf_mesh = Mesh.from_surface(surf_faces, mesh)

        if options.save_mesh:
            aux = edit_filename(filename_in, prefix='surf_', new_ext='.mesh')
            surf_mesh.write(aux, io='auto')

        if options.no_surface:
            return

        gr_s = surface_graph(surf_faces, mesh.n_nod)
        ##         import sfepy.base.plotutils as plu
        ##         plu.spy( gr_s )
        ##         plu.pylab.show()

        n_comp, comps = surface_components(gr_s, surf_faces)
        #        print 'components:', n_comp

        ccs, comps = comps, nm.zeros((0, 1), nm.int32)
        for cc in ccs:
            comps = nm.concatenate((comps, cc[:, nm.newaxis]), 0)

        out = nm.concatenate((lst, comps), 1)

        if (filename_out == '-'):
            file_out = sys.stdout
        else:
            file_out = open(filename_out, "w")
        for row in out:
            file_out.write('%d %d %d %d\n' % (row[0], row[1], row[2], row[3]))
        if (filename_out != '-'):
            file_out.close()
Beispiel #39
0
def main():
    parser = OptionParser(usage = usage, version = "%prog " + sfepy.__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];
        auto_mesh_name = False
        
    elif len( args ) == 0:
        auto_mesh_name = True

        if options.oscillator:
            filename_in = fix_path("examples/quantum/oscillator.py")

        elif options.well:
            filename_in = fix_path("examples/quantum/well.py")

        elif options.hydrogen:
            filename_in = fix_path("examples/quantum/hydrogen.py")

        elif options.boron:
            filename_in = fix_path("examples/quantum/boron.py")

        elif options.mesh:
            output('generating mesh...')
            try:
                os.makedirs("tmp")
            except OSError, e:
                if e.errno != 17: # [Errno 17] File exists
                    raise
            if options.dim2:
                output("dimension: 2")
                gp = fix_path('meshes/quantum/square.geo')
                os.system("cp %s tmp/mesh.geo" % gp)
                os.system("gmsh -2 tmp/mesh.geo -format mesh")
                mtv = fix_path('script/mesh_to_vtk.py')
                os.system("%s tmp/mesh.mesh tmp/mesh.vtk" % mtv)
            else:
                output("dimension: 3")
                import sfepy.geom as geom
                from sfepy.fem.mesh import Mesh
                try:
                    from site_cfg import tetgen_path
                except ImportError:
                    tetgen_path = '/usr/bin/tetgen'
                gp = fix_path('meshes/quantum/box.geo')
                os.system("gmsh -0 %s -o tmp/x.geo" % gp)
                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")
            output("...mesh written to tmp/mesh.vtk")
            return

        elif options.dft:
            output('the --dft option requires input file') 
            return

        else:
            parser.print_help()
            return
Beispiel #40
0
    def test_cmesh_counts(self):
        from sfepy.fem import Mesh
        from sfepy.fem.geometry_element import create_geometry_elements
        from sfepy.fem.extmods.cmesh import CMesh, get_cmem_usage

        gels = create_geometry_elements()

        ok = True

        for filename in self.filename_meshes:
            basename = os.path.basename(filename)
            enum, esizes = expected[basename]

            self.report('mesh: %s' % basename)

            mesh = Mesh.from_file(filename)
            cmesh = CMesh.from_mesh(mesh)
            cmesh.set_local_entities(gels)

            cmesh.setup_entities()

            self.report('dim:', cmesh.dim)
            self.report('n_cell: %d, n_face: %d, n_edge: %d, n_vertex: %d' %
                        tuple(cmesh.num))

            _ok = (enum == cmesh.num).all()
            if not _ok:
                self.report('%s == %s failed!' % (enum, cmesh.num))
            ok = ok and _ok

            dim = cmesh.dim
            for ir in range(dim + 1):
                for ic in range(dim + 1):
                    cmesh.setup_connectivity(ir, ic)
                    mem_usage1 = get_cmem_usage()[0]

                    if (ir == dim) and (ic == 0):
                        continue

                    cmesh.free_connectivity(ir, ic)
                    mem_usage2 = get_cmem_usage()[0]

                    cmesh.setup_connectivity(ir, ic)
                    mem_usage3 = get_cmem_usage()[0]

                    conn = cmesh.get_conn(ir, ic)

                    self.report('(%d, %d) : (%d, %d)'
                                % (ir, ic, conn.num, conn.n_incident))
                    sizes = nm.array([conn.num, conn.n_incident])

                    _ok = (esizes[ir, ic] == sizes).all()
                    if not _ok:
                        self.report('%s == %s failed!' % (esizes, sizes))
                    ok = ok and _ok

                    _ok1 = mem_usage3 == mem_usage1
                    _ok2 = mem_usage3 > mem_usage2
                    if not (_ok1 and _ok2):
                        self.report('unexpected memory usage! (%s)'
                                    % (mem_usage1, mem_usage2, mem_usage3))
                    ok = ok and (_ok1 and _ok2)

        return ok
def main():
    parser = OptionParser(usage=usage, version='%prog')
    parser.add_option('-b',
                      '--basis',
                      metavar='name',
                      action='store',
                      dest='basis',
                      default='lagrange',
                      help=help['basis'])
    parser.add_option('-n',
                      '--max-order',
                      metavar='order',
                      type=int,
                      action='store',
                      dest='max_order',
                      default=10,
                      help=help['max_order'])
    parser.add_option('-m',
                      '--matrix',
                      metavar='type',
                      action='store',
                      dest='matrix_type',
                      default='laplace',
                      help=help['matrix_type'])
    parser.add_option('-g',
                      '--geometry',
                      metavar='name',
                      action='store',
                      dest='geometry',
                      default='2_4',
                      help=help['geometry'])
    options, args = parser.parse_args()

    dim, n_ep = int(options.geometry[0]), int(options.geometry[2])
    output('reference element geometry:')
    output('  dimension: %d, vertices: %d' % (dim, n_ep))

    n_c = {'laplace': 1, 'elasticity': dim}[options.matrix_type]

    output('matrix type:', options.matrix_type)
    output('number of variable components:', n_c)

    output('polynomial space:', options.basis)

    output('max. order:', options.max_order)

    mesh = Mesh.from_file(data_dir +
                          '/meshes/elements/%s_1.mesh' % options.geometry)
    domain = Domain('domain', mesh)
    omega = domain.create_region('Omega', 'all')

    orders = nm.arange(1, options.max_order + 1, dtype=nm.int)
    conds = []

    order_fix = 0 if options.geometry in ['2_4', '3_8'] else 1

    for order in orders:
        output('order:', order, '...')

        field = Field.from_args('fu',
                                nm.float64,
                                n_c,
                                omega,
                                approx_order=order,
                                space='H1',
                                poly_space_base=options.basis)

        to = field.approx_order
        quad_order = 2 * (max(to - order_fix, 0))
        output('quadrature order:', quad_order)

        integral = Integral('i', order=quad_order)
        qp, _ = integral.get_qp(options.geometry)
        output('number of quadrature points:', qp.shape[0])

        u = FieldVariable('u', 'unknown', field, n_c)
        v = FieldVariable('v', 'test', field, n_c, primary_var_name='u')

        m = Material('m', lam=1.0, mu=1.0)

        if options.matrix_type == 'laplace':
            term = Term.new('dw_laplace(m.mu, v, u)',
                            integral,
                            omega,
                            m=m,
                            v=v,
                            u=u)
            n_zero = 1

        else:
            assert_(options.matrix_type == 'elasticity')
            term = Term.new('dw_lin_elastic_iso(m.lam, m.mu, v, u)',
                            integral,
                            omega,
                            m=m,
                            v=v,
                            u=u)
            n_zero = (dim + 1) * dim / 2

        term.setup()

        output('assembling...')
        tt = time.clock()
        mtx, iels = term.evaluate(mode='weak', diff_var='u')
        output('...done in %.2f s' % (time.clock() - tt))
        mtx = mtx[0][0, 0]

        try:
            assert_(nm.max(nm.abs(mtx - mtx.T)) < 1e-10)

        except:
            from sfepy.base.base import debug
            debug()

        output('matrix shape:', mtx.shape)

        eigs = eig(mtx, method='eig.sgscipy', eigenvectors=False)
        eigs.sort()

        # Zero 'true' zeros.
        eigs[:n_zero] = 0.0

        ii = nm.where(eigs < 0.0)[0]
        if len(ii):
            output('matrix is not positive semi-definite!')

        ii = nm.where(eigs[n_zero:] < 1e-12)[0]
        if len(ii):
            output('matrix has more than %d zero eigenvalues!' % n_zero)

        output('smallest eigs:\n', eigs[:10])

        ii = nm.where(eigs > 0.0)[0]
        emin, emax = eigs[ii[[0, -1]]]

        output('min:', emin, 'max:', emax)

        cond = emax / emin
        conds.append(cond)

        output('condition number:', cond)

        output('...done')

    plt.figure(1)
    plt.semilogy(orders, conds)
    plt.xticks(orders, orders)
    plt.xlabel('polynomial order')
    plt.ylabel('condition number')
    plt.grid()

    plt.figure(2)
    plt.loglog(orders, conds)
    plt.xticks(orders, orders)
    plt.xlabel('polynomial order')
    plt.ylabel('condition number')
    plt.grid()

    plt.show()
Beispiel #42
0
def main():
    parser = OptionParser( usage = usage, version = "%prog " + version )
    parser.add_option( "-m", "--mesh",
                       action = "store_true", dest = "save_mesh",
                       default = True,
                       help = "save surface mesh [default: %default]" )
    parser.add_option( "-n", "--no-surface",
                       action = "store_true", dest = "no_surface",
                       default = False,
                       help = "do not output surface [default: %default]" )
    (options, args) = parser.parse_args()

    if (len( args ) == 2):
        filename_in = args[0];
        filename_out = args[1];
    else:
        parser.print_help(),
        return

    if (filename_in == '-'):
        file_in = sys.stdin
    else:
        file_in = open( filename_in, "r" ); 

    mesh = Mesh.from_file( filename_in )

    if (filename_in != '-'):
        file_in.close()

    domain = Domain.from_mesh( mesh, op.join( init_sfepy.install_dir, 'eldesc' ) )
    domain.setup_groups()

    if domain.has_faces():
        domain.fix_element_orientation()
        domain.setup_neighbour_lists( create_edge_list = False )

        lst, surf_faces = domain.surface_faces()

        surf_mesh = Mesh.from_surface( surf_faces, mesh )

        if options.save_mesh:
            base, ext = op.splitext( op.basename( filename_in ) )
            surf_mesh.write( "surf_" + base + '.mesh', io = 'auto' )

        if options.no_surface:
            return

        n_nod = mesh.nod0.shape[0]
        gr_s = surface_graph( surf_faces, n_nod )
##         import sfepy.base.plotutils as plu
##         plu.spy( gr_s )
##         plu.pylab.show()

        n_comp, comps = surface_components( gr_s, surf_faces )
#        print 'components:', n_comp

        ccs, comps = comps, nm.zeros( (0,1), nm.int32 )
        for cc in ccs:
            comps = nm.concatenate( (comps, cc[:,nm.newaxis]), 0 )

        out = nm.concatenate( (lst, comps), 1 )

        if (filename_out == '-'):
            file_out = sys.stdout
        else:
            file_out = open( filename_out, "w" ); 
        for row in out:
            file_out.write( '%d %d %d %d\n' % (row[0], row[1], row[2], row[3]) )
        if (filename_out != '-'):
            file_out.close()
Beispiel #43
0
def _gen_common_data(orders, gels, report):
    import sfepy
    from sfepy.base.base import Struct
    from sfepy.linalg import combine
    from sfepy.fem import Mesh, Domain, Field, FieldVariable, Integral
    from sfepy.fem.global_interp import get_ref_coors

    bases = ([ii for ii in combine([['2_4', '3_8'],
                                    ['lagrange', 'lobatto']])]
             + [ii for ii in combine([['2_3', '3_4'],
                                      ['lagrange']])])
    for geom, poly_space_base in bases:
        report('geometry: %s, base: %s' % (geom, poly_space_base))

        order = orders[geom]
        integral = Integral('i', order=order)

        aux = '' if geom in ['2_4', '3_8'] else 'z'
        mesh0 = Mesh.from_file('meshes/elements/%s_2%s.mesh' % (geom, aux),
                               prefix_dir=sfepy.data_dir)
        gel = gels[geom]

        perms = gel.get_conn_permutations()

        qps, qp_weights = integral.get_qp(gel.surface_facet.name)
        zz = nm.zeros_like(qps[:, :1])
        qps = nm.hstack(([qps] + [zz]))

        shift = shifts[geom]
        rcoors = nm.ascontiguousarray(qps
                                      + shift[:1, :] - shift[1:, :])
        ccoors = nm.ascontiguousarray(qps
                                      + shift[:1, :] + shift[1:, :])

        for ir, pr in enumerate(perms):
            for ic, pc in enumerate(perms):
                report('ir: %d, ic: %d' % (ir, ic))
                report('pr: %s, pc: %s' % (pr, pc))

                mesh = mesh0.copy()
                conn = mesh.conns[0]
                conn[0, :] = conn[0, pr]
                conn[1, :] = conn[1, pc]

                cache = Struct(mesh=mesh)

                domain = Domain('domain', mesh)
                omega = domain.create_region('Omega', 'all')
                region = domain.create_region('Facet', rsels[geom], 'facet')
                field = Field.from_args('f', nm.float64, shape=1,
                                        region=omega, approx_order=order,
                                        poly_space_base=poly_space_base)
                var = FieldVariable('u', 'unknown', field, 1)
                report('# dofs: %d' % var.n_dof)

                vec = nm.empty(var.n_dof, dtype=var.dtype)

                ap = field.aps[0]
                ps = ap.interp.poly_spaces['v']

                dofs = field.get_dofs_in_region_group(region, 0,
                                                      merge=False)
                edofs, fdofs = nm.unique(dofs[1]), nm.unique(dofs[2])

                rrc, rcells, rstatus = get_ref_coors(field, rcoors,
                                                     cache=cache)
                crc, ccells, cstatus = get_ref_coors(field, ccoors,
                                                     cache=cache)
                assert_((rstatus == 0).all() and (cstatus == 0).all())

                yield (geom, poly_space_base, qp_weights, mesh, ir, ic,
                       ap, ps, rrc, rcells[0, 1], crc, ccells[0, 1],
                       vec, edofs, fdofs)
Beispiel #44
0
def _gen_common_data(order, gels, report):
    import sfepy
    from sfepy.base.base import Struct
    from sfepy.linalg import combine
    from sfepy.fem import Mesh, Domain, Field, FieldVariable, Integral
    from sfepy.fem.global_interp import get_ref_coors

    integral = Integral('i', order=order)

    for geom, poly_space_base in combine([['2_4', '3_8'],
                                          ['lagrange', 'lobatto']]):
        report('geometry: %s, base: %s' % (geom, poly_space_base))

        mesh0 = Mesh.from_file('meshes/elements/%s_2.mesh' % geom,
                               prefix_dir=sfepy.data_dir)
        gel = gels[geom]

        perms = gel.get_conn_permutations()

        qps, qp_weights = integral.get_qp(gel.surface_facet.name)
        zz = nm.zeros_like(qps[:, :1])
        qps = nm.hstack(([qps] + [zz]))

        rot = rots[geom]
        if rot is not None:
            pass

        shift = shifts[geom]
        rcoors = nm.ascontiguousarray(qps
                                      + shift[:1, :] - shift[1:, :])
        ccoors = nm.ascontiguousarray(qps
                                      + shift[:1, :] + shift[1:, :])

        for ir, pr in enumerate(perms):
            for ic, pc in enumerate(perms):
                report('ir: %d, ic: %d' % (ir, ic))

                mesh = mesh0.copy()
                conn = mesh.conns[0]
                conn[0, :] = conn[0, pr]
                conn[1, :] = conn[1, pc]

                cache = Struct(mesh=mesh)

                domain = Domain('domain', mesh)
                omega = domain.create_region('Omega', 'all')
                region = domain.create_region('Facet', rsels[geom])
                field = Field.from_args('f', nm.float64, shape=1,
                                        region=omega, approx_order=order,
                                        poly_space_base=poly_space_base)
                var = FieldVariable('u', 'unknown', field, 1)
                report('# dofs: %d' % var.n_dof)

                vec = nm.empty(var.n_dof, dtype=var.dtype)

                ap = field.aps[0]
                ps = ap.interp.poly_spaces['v']

                dofs = field.get_dofs_in_region_group(region, 0,
                                                      merge=False)
                edofs, fdofs = nm.unique(dofs[1]), nm.unique(dofs[2])

                rrc, rcells, rstatus = get_ref_coors(field, rcoors,
                                                     cache=cache)
                crc, ccells, cstatus = get_ref_coors(field, ccoors,
                                                     cache=cache)

                yield (geom, poly_space_base, qp_weights, mesh, ir, ic,
                       ap, ps, rrc, crc, vec, edofs, fdofs)
Beispiel #45
0
def main():
    parser = OptionParser(usage=usage, version='%prog')
    parser.add_option('-b', '--basis', metavar='name',
                      action='store', dest='basis',
                      default='lagrange', help=help['basis'])
    parser.add_option('-d', '--derivative', metavar='d', type=int,
                      action='store', dest='derivative',
                      default=0, help=help['derivative'])
    parser.add_option('-n', '--max-order', metavar='order', type=int,
                      action='store', dest='max_order',
                      default=2, help=help['max_order'])
    parser.add_option('-g', '--geometry', metavar='name',
                      action='store', dest='geometry',
                      default='2_4', help=help['geometry'])
    parser.add_option('-m', '--mesh', metavar='mesh',
                      action='store', dest='mesh',
                      default=None, help=help['mesh'])
    parser.add_option('', '--permutations', metavar='permutations',
                      action='store', dest='permutations',
                      default=None, help=help['permutations'])
    parser.add_option('', '--dofs', metavar='dofs',
                      action='store', dest='dofs',
                      default=None, help=help['dofs'])
    parser.add_option('-l', '--lin-options', metavar='options',
                      action='store', dest='lin_options',
                      default='min_level=2,max_level=5,eps=1e-3',
                      help=help['lin_options'])
    parser.add_option('', '--plot-dofs',
                      action='store_true', dest='plot_dofs',
                      default=False, help=help['plot_dofs'])
    options, args = parser.parse_args()

    if len(args) == 1:
        output_dir = args[0]
    else:
        parser.print_help(),
        return

    output('polynomial space:', options.basis)
    output('max. order:', options.max_order)

    lin = Struct(kind='adaptive', min_level=2, max_level=5, eps=1e-3)
    for opt in options.lin_options.split(','):
        key, val = opt.split('=')
        setattr(lin, key, eval(val))

    if options.mesh is None:
        dim, n_ep = int(options.geometry[0]), int(options.geometry[2])
        output('reference element geometry:')
        output('  dimension: %d, vertices: %d' % (dim, n_ep))

        gel = GeometryElement(options.geometry)
        gps = PolySpace.any_from_args(None, gel, 1,
                                      base=options.basis)
        ps = PolySpace.any_from_args(None, gel, options.max_order,
                                     base=options.basis)

        n_digit, _format = get_print_info(ps.n_nod, fill='0')
        name_template = os.path.join(output_dir, 'bf_%s.vtk' % _format)
        for ip in get_dofs(options.dofs, ps.n_nod):
            output('shape function %d...' % ip)

            def eval_dofs(iels, rx):
                if options.derivative == 0:
                    bf = ps.eval_base(rx).squeeze()
                    rvals = bf[None, :, ip:ip+1]

                else:
                    bfg = ps.eval_base(rx, diff=True)
                    rvals = bfg[None, ..., ip]

                return rvals

            def eval_coors(iels, rx):
                bf = gps.eval_base(rx).squeeze()
                coors = nm.dot(bf, gel.coors)[None, ...]
                return coors

            (level, coors, conn,
             vdofs, mat_ids) = create_output(eval_dofs, eval_coors, 1,
                                             ps, min_level=lin.min_level,
                                             max_level=lin.max_level,
                                             eps=lin.eps)
            out = {
                'bf' : Struct(name='output_data',
                              mode='vertex', data=vdofs,
                              var_name='bf', dofs=None)
            }

            mesh = Mesh.from_data('bf_mesh', coors, None, [conn], [mat_ids],
                                  [options.geometry])

            name = name_template % ip
            ensure_path(name)
            mesh.write(name, out=out)

            output('...done (%s)' % name)

    else:
        mesh = Mesh.from_file(options.mesh)
        output('mesh geometry:')
        output('  dimension: %d, vertices: %d, elements: %d'
               % (mesh.dim, mesh.n_nod, mesh.n_el))

        if options.permutations:
            if options.permutations == 'all':
                from sfepy.linalg import cycle
                gel = GeometryElement(mesh.descs[0])
                n_perms = gel.get_conn_permutations().shape[0]
                all_permutations = [ii for ii in cycle(mesh.n_el * [n_perms])]

            else:
                all_permutations = [int(ii)
                                    for ii in options.permutations.split(',')]
                all_permutations = nm.array(all_permutations)
                np = len(all_permutations)
                all_permutations.shape = (np / mesh.n_el, mesh.n_el)

            output('using connectivity permutations:\n', all_permutations)

        else:
            all_permutations = [None]

        for ip, permutations in enumerate(all_permutations):
            if permutations is None:
                suffix = ''

            else:
                suffix = '_' + '_'.join('%d' % ii for ii in permutations)

            save_basis_on_mesh(mesh, options, output_dir, lin, permutations,
                               suffix)
Beispiel #46
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()

    mesh = Mesh.from_file(data_dir + '/meshes/2d/rectangle_tri.mesh')
    domain = Domain('domain', mesh)

    min_x, max_x = domain.get_mesh_bounding_box()[:, 0]
    eps = 1e-8 * (max_x - min_x)
    omega = domain.create_region('Omega', 'all')
    gamma1 = domain.create_region('Gamma1',
                                  'nodes in x < %.10f' % (min_x + eps))
    gamma2 = domain.create_region('Gamma2',
                                  'nodes in x > %.10f' % (max_x - eps))

    field = H1NodalVolumeField('fu',
                               nm.float64,
                               'vector',
                               omega,
                               approx_order=2)

    u = FieldVariable('u', 'unknown', field, mesh.dim)
    v = FieldVariable('v', 'test', field, mesh.dim, primary_var_name='u')

    m = Material('m', lam=1.0, mu=1.0)
    f = Material('f', val=[[0.02], [0.01]])

    integral = Integral('i', order=3)

    t1 = Term.new('dw_lin_elastic_iso(m.lam, m.mu, v, u)',
                  integral,
                  omega,
                  m=m,
                  v=v,
                  u=u)
    t2 = Term.new('dw_volume_lvf(f.val, v)', integral, omega, f=f, v=v)
    eq = Equation('balance', t1 + t2)
    eqs = Equations([eq])

    fix_u = EssentialBC('fix_u', gamma1, {'u.all': 0.0})

    bc_fun = Function('shift_u_fun', shift_u_fun, extra_args={'shift': 0.01})
    shift_u = EssentialBC('shift_u', gamma2, {'u.0': bc_fun})

    ls = ScipyDirect({})

    nls_status = IndexedStruct()
    nls = Newton({}, lin_solver=ls, status=nls_status)

    pb = ProblemDefinition('elasticity', equations=eqs, nls=nls, ls=ls)
    pb.save_regions_as_groups('regions')

    pb.time_update(ebcs=Conditions([fix_u, shift_u]))

    vec = pb.solve()
    print nls_status

    pb.save_state('linear_elasticity.vtk', vec)

    if options.show:
        view = Viewer('linear_elasticity.vtk')
        view(vector_mode='warp_norm',
             rel_scaling=2,
             is_scalar_bar=True,
             is_wireframe=True)
Beispiel #47
0
def main():
    parser = OptionParser(usage=usage)
    parser.add_option('-s', '--scale', metavar='scale',
                      action='store', dest='scale',
                      default=None, help=help['scale'])
    parser.add_option('-r', '--refine', metavar='level',
                      action='store', type=int, dest='refine',
                      default=0, help=help['refine'])
    parser.add_option('-f', '--format', metavar='format',
                      action='store', type='string', dest='format',
                      default=None, help=help['format'])
    parser.add_option('-l', '--list', action='store_true',
                      dest='list', help=help['list'])
    (options, args) = parser.parse_args()

    if options.list:
        output_writable_meshes()
        sys.exit(0)

    if len(args) != 2:
        parser.print_help()
        sys.exit(1)

    scale = options.scale
    if scale is not None:
        try:
            try:
                scale = float(scale)
            except ValueError:
                scale = [float(ii) for ii in scale.split(',')]
            scale = nm.array(scale, dtype=nm.float64, ndmin=1)
        except:
            output('bad scale! (%s)' % scale)
            parser.print_help()
            sys.exit(1)

    filename_in, filename_out = args

    mesh = Mesh.from_file(filename_in)

    if scale is not None:
        if len(scale) == 1:
            tr = nm.eye(mesh.dim, dtype=nm.float64) * scale
        elif len(scale) == mesh.dim:
            tr = nm.diag(scale)
        else:
            raise ValueError('bad scale! (%s)' % scale)
        mesh.transform_coors(tr)

    if options.refine > 0:
        domain = Domain(mesh.name, mesh)
        output('initial mesh: %d nodes %d elements'
               % (domain.shape.n_nod, domain.shape.n_el))

        for ii in range(options.refine):
            output('refine %d...' % ii)
            domain = domain.refine()
            output('... %d nodes %d elements'
                   % (domain.shape.n_nod, domain.shape.n_el))

        mesh = domain.mesh

    io = MeshIO.for_format(filename_out, format=options.format,
                           writable=True)

    output('writing %s...' % filename_out)
    mesh.write(filename_out, io=io)
    output('...done')
Beispiel #48
0
def main():
    parser = OptionParser(usage=usage)
    parser.add_option("-s", "--scale", metavar="scale", action="store", dest="scale", default=None, help=help["scale"])
    parser.add_option(
        "-f",
        "--format",
        metavar="format",
        action="store",
        type="string",
        dest="format",
        default=None,
        help=help["format"],
    )
    parser.add_option("-l", "--list", action="store_true", dest="list", help=help["list"])
    (options, args) = parser.parse_args()

    if options.list:
        output_writable_meshes()
        sys.exit(0)

    if len(args) != 2:
        parser.print_help()
        sys.exit(1)

    scale = options.scale
    if scale is not None:
        try:
            try:
                scale = float(scale)
            except ValueError:
                scale = [float(ii) for ii in scale.split(",")]
            scale = nm.array(scale, dtype=nm.float64, ndmin=1)
        except:
            output("bad scale! (%s)" % scale)
            parser.print_help()
            sys.exit(1)

    filename_in, filename_out = args

    mesh = Mesh.from_file(filename_in)

    if scale is not None:
        if len(scale) == 1:
            tr = nm.eye(mesh.dim, dtype=nm.float64) * scale
        elif len(scale) == mesh.dim:
            tr = nm.diag(scale)
        else:
            raise ValueError("bad scale! (%s)" % scale)
        mesh.transform_coors(tr)

    io = "auto"
    if options.format:
        try:
            io = io_table[options.format](filename_out)
        except KeyError:
            output("unknown output mesh format! (%s)" % options.format)
            output_writable_meshes()
            sys.exit(1)

        if "w" not in supported_capabilities[options.format]:
            output("write support not implemented for output mesh format! (%s)" % options.format)
            output_writable_meshes()
            sys.exit(1)

    output("writing %s..." % filename_out)
    mesh.write(filename_out, io=io)
    output("...done")
Beispiel #49
0
def meshgen_from_goem(geo, a=None, quadratic=False, verbose=True,
                      refine=False, polyfilename='./meshgen.poly',
                      out='mesh', **kwargs):
    """
    Runs mesh generator - tetgen for 3D or triangle for 2D meshes.

    Parameters
    ----------
    geo : geometry
        geometry description
    a : int, optional
        a maximum area/volume constraint
    quadratic : bool, optional
        set True for quadratic elements
    verbose : bool, optional
        detailed information
    refine : bool, optional
        refines mesh

    Returns
    -------
    mesh : mesh
        triangular or tetrahedral mesh
    """

    import os.path as op
    import pexpect

    # write geometry to poly file
    geo.to_poly_file(polyfilename)

    if not refine:
        params = "-Apq"
    else:
        params = "-Arq"
    if verbose:
        params = params + " -Q"
    if a != None and not refine:
        params = params + " -a%f" % (a)
    if refine:
        params = params + " -a"
    if quadratic:
        params = params + " -o2"
    params = params + " %s" % (polyfilename)

    meshgen_call = {2: 'triangle', 3: 'tetgen'}
    cmd = "%s %s" % (meshgen_call[geo.dim], params)
    if verbose: print "Generating mesh using", cmd
    if geo.dim == 2:
        p=pexpect.run(cmd, timeout=None)
        bname, ext = op.splitext(polyfilename)
        mesh = Mesh.from_file(bname + '.1.node')
        mesh.write(bname + '.' + out)
    if geo.dim == 3:
        p=pexpect.spawn(cmd, timeout=None)
        if not refine:
            p.expect("Opening %s." % (polyfilename))
        else:
            p.expect("Opening %s.node.\r\n" % (polyfilename))
            p.expect("Opening %s.ele.\r\n" % (polyfilename))
            p.expect("Opening %s.face.\r\n" % (polyfilename))
            p.expect("Opening %s.vol." % (polyfilename))
        assert p.before == ""
        p.expect(pexpect.EOF)
        if p.before != "\r\n":
            print p.before
            raise "Error when running mesh generator (see above for output): %s" % cmd
import numpy as np

from sfepy.fem import (Mesh, Domain, Field,
                       FieldVariable,
                       Material, Integral,
                       Equation, Equations,
                       ProblemDefinition)
from sfepy.terms import Term
from sfepy.fem.conditions import Conditions, EssentialBC
from sfepy.solvers.ls import ScipyDirect
from sfepy.solvers.nls import Newton
from sfepy.postprocess import Viewer

mesh = Mesh.from_file('meshes/2d/square_tri2.mesh')
domain = Domain('domain', mesh)

omega = domain.create_region('Omega', 'all')
left = domain.create_region('Left',
                            'vertices in x < -0.999',
                            'facet')
right = domain.create_region('Right',
                             'vertices in x > 0.999',
                             'facet')
bottom = domain.create_region('Bottom',
                              'vertices in y < -0.999',
                              'facet')
top = domain.create_region('Top',
                           'vertices in y > 0.999',
                           'facet')

domain.save_regions_as_groups('regions.vtk')
Beispiel #51
0
    def test_linearization(self):
        from sfepy.base.base import Struct
        from sfepy.fem import Mesh, Domain, H1NodalVolumeField
        from sfepy import data_dir

        geometries = ['2_3', '2_4', '3_4', '3_8']
        approx_orders = [1, 2]
        funs = [nm.cos, nm.sin, lambda x: x]

        ok = True
        for geometry in geometries:
            name = os.path.join(data_dir,
                                'meshes/elements/%s_1.mesh' % geometry)
            mesh = Mesh.from_file(name)

            domain = Domain('', mesh)
            domain = domain.refine()

            domain.mesh.write(self.join('linearizer-%s-0.mesh' % geometry))

            omega = domain.create_region('Omega', 'all')

            for approx_order in approx_orders:
                for dpn in [1, mesh.dim]:
                    self.report('geometry: %s, approx. order: %d, dpn: %d' %
                                (geometry, approx_order, dpn))

                    field = H1NodalVolumeField('fu',
                                               nm.float64,
                                               dpn,
                                               omega,
                                               approx_order=approx_order)

                    cc = field.get_coor()
                    dofs = nm.zeros((field.n_nod, dpn), dtype=nm.float64)

                    for ic in range(dpn):
                        dofs[:, ic] = funs[ic](3 * (cc[:, 0] * cc[:, 1]))

                    vmesh, vdofs, levels = field.linearize(dofs,
                                                           min_level=0,
                                                           max_level=3,
                                                           eps=1e-2)
                    level = levels[0]

                    if approx_order == 1:
                        _ok = level == 0

                    else:
                        _ok = level > 0
                    self.report('max. refinement level: %d: %s' % (level, _ok))

                    ok = ok and _ok

                    rdofs = nm.zeros((vmesh.n_nod, dpn), dtype=nm.float64)
                    cc = vmesh.coors
                    for ic in range(dpn):
                        rdofs[:, ic] = funs[ic](3 * (cc[:, 0] * cc[:, 1]))

                    _ok = nm.allclose(rdofs, vdofs, rtol=0.0, atol=0.03)
                    self.report('interpolation: %s' % _ok)
                    ok = ok and _ok

                    out = {
                        'u':
                        Struct(name='output_data',
                               mode='vertex',
                               data=vdofs,
                               var_name='u',
                               dofs=None)
                    }

                    name = self.join('linearizer-%s-%d-%d' %
                                     (geometry, approx_order, dpn))

                    vmesh.write(name + '.mesh')
                    vmesh.write(name + '.vtk', out=out)

        return ok
def main():
    parser = OptionParser(usage=usage, version="%prog")
    parser.add_option(
        "-b", "--basis", metavar="name", action="store", dest="basis", default="lagrange", help=help["basis"]
    )
    parser.add_option(
        "-n",
        "--max-order",
        metavar="order",
        type=int,
        action="store",
        dest="max_order",
        default=10,
        help=help["max_order"],
    )
    parser.add_option(
        "-m",
        "--matrix",
        metavar="type",
        action="store",
        dest="matrix_type",
        default="laplace",
        help=help["matrix_type"],
    )
    parser.add_option(
        "-g", "--geometry", metavar="name", action="store", dest="geometry", default="2_4", help=help["geometry"]
    )
    options, args = parser.parse_args()

    dim, n_ep = int(options.geometry[0]), int(options.geometry[2])
    output("reference element geometry:")
    output("  dimension: %d, vertices: %d" % (dim, n_ep))

    n_c = {"laplace": 1, "elasticity": dim}[options.matrix_type]

    output("matrix type:", options.matrix_type)
    output("number of variable components:", n_c)

    output("polynomial space:", options.basis)

    output("max. order:", options.max_order)

    mesh = Mesh.from_file(data_dir + "/meshes/elements/%s_1.mesh" % options.geometry)
    domain = Domain("domain", mesh)
    omega = domain.create_region("Omega", "all")

    orders = nm.arange(1, options.max_order + 1, dtype=nm.int)
    conds = []

    order_fix = 0 if options.geometry in ["2_4", "3_8"] else 1

    for order in orders:
        output("order:", order, "...")

        field = Field.from_args(
            "fu", nm.float64, n_c, omega, approx_order=order, space="H1", poly_space_base=options.basis
        )

        to = field.approx_order
        quad_order = 2 * (max(to - order_fix, 0))
        output("quadrature order:", quad_order)

        integral = Integral("i", order=quad_order)
        qp, _ = integral.get_qp(options.geometry)
        output("number of quadrature points:", qp.shape[0])

        u = FieldVariable("u", "unknown", field, n_c)
        v = FieldVariable("v", "test", field, n_c, primary_var_name="u")

        m = Material("m", lam=1.0, mu=1.0)

        if options.matrix_type == "laplace":
            term = Term.new("dw_laplace(m.mu, v, u)", integral, omega, m=m, v=v, u=u)
            n_zero = 1

        else:
            assert_(options.matrix_type == "elasticity")
            term = Term.new("dw_lin_elastic_iso(m.lam, m.mu, v, u)", integral, omega, m=m, v=v, u=u)
            n_zero = (dim + 1) * dim / 2

        term.setup()

        output("assembling...")
        tt = time.clock()
        mtx, iels = term.evaluate(mode="weak", diff_var="u")
        output("...done in %.2f s" % (time.clock() - tt))
        mtx = mtx[0][0, 0]

        try:
            assert_(nm.max(nm.abs(mtx - mtx.T)) < 1e-10)

        except:
            from sfepy.base.base import debug

            debug()

        output("matrix shape:", mtx.shape)

        eigs = eig(mtx, method="eig.sgscipy", eigenvectors=False)
        eigs.sort()

        # Zero 'true' zeros.
        eigs[:n_zero] = 0.0

        ii = nm.where(eigs < 0.0)[0]
        if len(ii):
            output("matrix is not positive semi-definite!")

        ii = nm.where(eigs[n_zero:] < 1e-12)[0]
        if len(ii):
            output("matrix has more than %d zero eigenvalues!" % n_zero)

        output("smallest eigs:\n", eigs[:10])

        ii = nm.where(eigs > 0.0)[0]
        emin, emax = eigs[ii[[0, -1]]]

        output("min:", emin, "max:", emax)

        cond = emax / emin
        conds.append(cond)

        output("condition number:", cond)

        output("...done")

    plt.figure(1)
    plt.semilogy(orders, conds)
    plt.xticks(orders, orders)
    plt.xlabel("polynomial order")
    plt.ylabel("condition number")
    plt.grid()

    plt.figure(2)
    plt.loglog(orders, conds)
    plt.xticks(orders, orders)
    plt.xlabel("polynomial order")
    plt.ylabel("condition number")
    plt.grid()

    plt.show()
Beispiel #53
0
def main():
    parser = OptionParser(usage=usage)
    parser.add_option('-s',
                      '--scale',
                      metavar='scale',
                      action='store',
                      dest='scale',
                      default=None,
                      help=help['scale'])
    parser.add_option('-c',
                      '--center',
                      metavar='center',
                      action='store',
                      dest='center',
                      default=None,
                      help=help['center'])
    parser.add_option('-r',
                      '--refine',
                      metavar='level',
                      action='store',
                      type=int,
                      dest='refine',
                      default=0,
                      help=help['refine'])
    parser.add_option('-f',
                      '--format',
                      metavar='format',
                      action='store',
                      type='string',
                      dest='format',
                      default=None,
                      help=help['format'])
    parser.add_option('-l',
                      '--list',
                      action='store_true',
                      dest='list',
                      help=help['list'])
    (options, args) = parser.parse_args()

    if options.list:
        output_writable_meshes()
        sys.exit(0)

    if len(args) != 2:
        parser.print_help()
        sys.exit(1)

    scale = _parse_val_or_vec(options.scale, 'scale', parser)
    center = _parse_val_or_vec(options.center, 'center', parser)

    filename_in, filename_out = args

    mesh = Mesh.from_file(filename_in)

    if scale is not None:
        if len(scale) == 1:
            tr = nm.eye(mesh.dim, dtype=nm.float64) * scale
        elif len(scale) == mesh.dim:
            tr = nm.diag(scale)
        else:
            raise ValueError('bad scale! (%s)' % scale)
        mesh.transform_coors(tr)

    if center is not None:
        cc = 0.5 * mesh.get_bounding_box().sum(0)
        shift = center - cc
        tr = nm.c_[nm.eye(mesh.dim, dtype=nm.float64), shift[:, None]]
        mesh.transform_coors(tr)

    if options.refine > 0:
        domain = Domain(mesh.name, mesh)
        output('initial mesh: %d nodes %d elements' %
               (domain.shape.n_nod, domain.shape.n_el))

        for ii in range(options.refine):
            output('refine %d...' % ii)
            domain = domain.refine()
            output('... %d nodes %d elements' %
                   (domain.shape.n_nod, domain.shape.n_el))

        mesh = domain.mesh

    io = MeshIO.for_format(filename_out, format=options.format, writable=True)

    output('writing %s...' % filename_out)
    mesh.write(filename_out, io=io)
    output('...done')