Example #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)
Example #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)
Example #3
0
    def test_interpolation_two_meshes(self):
        from sfepy import data_dir
        from sfepy.fem import Mesh, Domain, H1NodalVolumeField, Variables

        m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh')

        m2 = Mesh('target mesh',
                  data_dir + '/meshes/3d/cube_medium_tetra.mesh')
        m2.coors *= 2.0

        bbox = m1.get_bounding_box()
        dd = bbox[1, :] - bbox[0, :]
        data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \
               * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1])

        variables1 = {
            'u': ('unknown field', 'scalar_tp', 0),
            'v': ('test field', 'scalar_tp', 'u'),
        }

        variables2 = {
            'u': ('unknown field', 'scalar_si', 0),
            'v': ('test field', 'scalar_si', 'u'),
        }

        d1 = Domain('d1', m1)
        omega1 = d1.create_region('Omega', 'all')
        field1 = H1NodalVolumeField('scalar_tp',
                                    nm.float64, (1, 1),
                                    omega1,
                                    approx_order=1)
        ff1 = {field1.name: field1}

        d2 = Domain('d2', m2)
        omega2 = d2.create_region('Omega', 'all')
        field2 = H1NodalVolumeField('scalar_si',
                                    nm.float64, (1, 1),
                                    omega2,
                                    approx_order=0)
        ff2 = {field2.name: field2}

        vv1 = Variables.from_conf(transform_variables(variables1), ff1)
        u1 = vv1['u']
        u1.set_from_mesh_vertices(data)

        vv2 = Variables.from_conf(transform_variables(variables2), ff2)
        u2 = vv2['u']

        # Performs interpolation, if other field differs from self.field
        # or, in particular, is defined on a different mesh.
        u2.set_from_other(u1, strategy='interpolation', close_limit=0.1)

        fname = in_dir(self.options.out_dir)
        u1.save_as_mesh(fname('test_mesh_interp_block_scalar.vtk'))
        u2.save_as_mesh(fname('test_mesh_interp_cube_scalar.vtk'))

        return True
Example #4
0
    def test_interpolation_two_meshes(self):
        from sfepy import data_dir
        from sfepy.fem import Mesh, Domain, H1NodalVolumeField, Variables

        m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh')

        m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh')
        m2.coors *= 2.0

        bbox = m1.get_bounding_box()
        dd = bbox[1,:] - bbox[0,:]
        data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \
               * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1])

        variables1 = {
            'u'       : ('unknown field', 'scalar_tp', 0),
            'v'       : ('test field',    'scalar_tp', 'u'),
        }

        variables2 = {
            'u'       : ('unknown field', 'scalar_si', 0),
            'v'       : ('test field',    'scalar_si', 'u'),
        }

        d1 = Domain('d1', m1)
        omega1 = d1.create_region('Omega', 'all')
        field1 = H1NodalVolumeField('scalar_tp', nm.float64, (1,1), omega1,
                                    approx_order=1)
        ff1 = {field1.name : field1}

        d2 = Domain('d2', m2)
        omega2 = d2.create_region('Omega', 'all')
        field2 = H1NodalVolumeField('scalar_si', nm.float64, (1,1), omega2,
                                    approx_order=0)
        ff2 = {field2.name : field2}

        vv1 = Variables.from_conf(transform_variables(variables1), ff1)
        u1 = vv1['u']
        u1.set_from_mesh_vertices(data)

        vv2 = Variables.from_conf(transform_variables(variables2), ff2)
        u2 = vv2['u']

        # Performs interpolation, if other field differs from self.field
        # or, in particular, is defined on a different mesh.
        u2.set_from_other(u1, strategy='interpolation', close_limit=0.1)

        fname = in_dir(self.options.out_dir)
        u1.save_as_mesh(fname('test_mesh_interp_block_scalar.vtk'))
        u2.save_as_mesh(fname('test_mesh_interp_cube_scalar.vtk'))

        return True
Example #5
0
    def test_invariance_qp(self):
        from sfepy import data_dir
        from sfepy.fem import (Mesh, Domain, H1NodalVolumeField, Variables,
                               Integral)
        from sfepy.terms import Term
        from sfepy.fem.mappings import get_physical_qps

        mesh = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh')

        bbox = mesh.get_bounding_box()
        dd = bbox[1, :] - bbox[0, :]
        data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / dd[0]) \
               * nm.cos(4.0 * nm.pi * mesh.coors[:,1:2] / dd[1])

        variables = {
            'u': ('unknown field', 'scalar_tp', 0),
            'v': ('test field', 'scalar_tp', 'u'),
        }

        domain = Domain('domain', mesh)
        omega = domain.create_region('Omega', 'all')
        field = H1NodalVolumeField('scalar_tp',
                                   nm.float64,
                                   1,
                                   omega,
                                   approx_order=1)
        ff = {field.name: field}

        vv = Variables.from_conf(transform_variables(variables), ff)
        u = vv['u']
        u.set_from_mesh_vertices(data)

        integral = Integral('i', order=2)
        term = Term.new('ev_volume_integrate(u)', integral, omega, u=u)
        term.setup()
        val1, _ = term.evaluate(mode='qp')
        val1 = val1.ravel()

        qps = get_physical_qps(omega, integral)
        coors = qps.get_merged_values()

        val2 = u.evaluate_at(coors).ravel()

        self.report('max. difference:', nm.abs(val1 - val2).max())
        ok = nm.allclose(val1, val2, rtol=0.0, atol=1e-12)
        self.report('invariance in qp: %s' % ok)

        return ok
Example #6
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
Example #7
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
Example #8
0
    def save_axes(self, filename):
        coors = []
        conns = []
        mat_ids = []
        offset = 0
        for ig, dual_surface in self.dual_surfaces.iteritems():
            cc = nm.r_[dual_surface.edge_centre_coors, dual_surface.dual_coors]
            coors.append(cc)

            conn = dual_surface.conn.copy() + offset
            conn[:, 1:] += dual_surface.edge_centre_coors.shape[0]
            conns.append(conn)

            mat_id = nm.empty((conn.shape[0], ), dtype=nm.int32)
            mat_id[:] = ig
            mat_ids.append(mat_id)

            offset += cc.shape[0]

        coors = nm.concatenate(coors, axis=0)

        out = {}
        for ig, dual_surface in self.dual_surfaces.iteritems():
            eto = edge_data_to_output
            out['en_%d' % ig] = eto(coors, conns[ig], dual_surface.e_sort,
                                    dual_surface.edge_normals)
            out['ed_%d' % ig] = eto(coors, conns[ig], dual_surface.e_sort,
                                    dual_surface.edge_dirs)
            out['eo_%d' % ig] = eto(coors, conns[ig], dual_surface.e_sort,
                                    dual_surface.edge_ortho)

        dual_mesh = Mesh.from_data('dual_mesh_vectors', coors, None, conns,
                                   mat_ids, ['2_4'] * len(conns))
        dual_mesh.write(filename, io='auto', out=out)
Example #9
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
Example #10
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
Example #11
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
Example #12
0
    def save_axes(self, filename):
        coors = []
        conns = []
        mat_ids = []
        offset = 0
        for ig, dual_surface in self.dual_surfaces.iteritems():
            cc = nm.r_[dual_surface.edge_centre_coors,
                       dual_surface.dual_coors]
            coors.append(cc)

            conn = dual_surface.conn.copy() + offset
            conn[:,1:] += dual_surface.edge_centre_coors.shape[0]
            conns.append(conn)
            
            mat_id = nm.empty((conn.shape[0],), dtype=nm.int32)
            mat_id[:] = ig
            mat_ids.append(mat_id)

            offset += cc.shape[0]

        coors = nm.concatenate(coors, axis=0)

        out = {}
        for ig, dual_surface in self.dual_surfaces.iteritems():
            eto = edge_data_to_output
            out['en_%d' % ig] = eto(coors, conns[ig], dual_surface.e_sort,
                                    dual_surface.edge_normals)
            out['ed_%d' % ig] = eto(coors, conns[ig], dual_surface.e_sort,
                                    dual_surface.edge_dirs)
            out['eo_%d' % ig] = eto(coors, conns[ig], dual_surface.e_sort,
                                    dual_surface.edge_ortho)

        dual_mesh = Mesh.from_data('dual_mesh_vectors', coors, None, conns,
                                   mat_ids, ['2_4'] * len(conns))
        dual_mesh.write(filename, io='auto', out=out)
Example #13
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)
Example #14
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
Example #15
0
def main():
    parser = OptionParser(usage=usage, version="%prog")

    options, args = parser.parse_args()

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

    mesh = Mesh('mesh', mesh_filename)
    print mesh

    domain = Domain('domain', mesh)
    print domain

    reg = domain.create_region('Surface',
                               'nodes of surface',
                               {'can_cells' : True})

    dual_mesh = DualMesh(reg)
    dual_mesh.save('dual_mesh.mesh',)
    dual_mesh.save_axes('axes.vtk',)

    print dual_mesh
Example #16
0
    def test_refine_3_8(self):
        mesh = Mesh('3_8', data_dir + '/meshes/elements/3_8_1.mesh')
        domain = refine(Domain('domain', mesh), self.options.out_dir, 1)

        ok = compare_mesh('3_8', domain.mesh.coors, domain.mesh.conns[0])

        return ok
Example #17
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
Example #18
0
def refine_3_8(mesh_in, ed, fa):
    """
    Refines hexahedral mesh by cutting cutting each edge in half and
    making 8 new finer hexahedrons out of one coarser one.
    """
    # Unique edge centres.
    e_coors, e_uid = ed.get_coors()
    e_centres = 0.5 * nm.sum(e_coors, axis=1)

    # Unique face centres.
    f_coors, f_uid = fa.get_coors()
    f_centres = 0.25 * nm.sum(f_coors, axis=1)

    # Unique element centres.
    coors = mesh_in.get_element_coors()
    centres = 0.125 * nm.sum(coors, axis=1)

    # New coordinates after the original ones.
    coors = nm.r_[mesh_in.coors, e_centres, f_centres, centres]

    o1 = mesh_in.n_nod
    o2 = o1 + e_centres.shape[0]
    o3 = o2 + f_centres.shape[0]

    st = nm.vstack

    conns = []
    mat_ids = []
    for ig, conn in enumerate(mesh_in.conns):
        e_indx = ed.indx[ig]
        f_indx = fa.indx[ig]
        off = mesh_in.el_offsets[ig]
        n_el = conn.shape[0]

        e_nodes = ed.uid_i[e_indx].reshape((n_el, 12)) + o1
        f_nodes = fa.uid_i[f_indx].reshape((n_el, 6)) + o2
        nodes = nm.arange(n_el) + off + o3

        c = nm.c_[conn, e_nodes, f_nodes, nodes].T

        new_conn = st([
            c[0], c[8], c[20], c[11], c[16], c[22], c[26], c[21], c[1], c[9],
            c[20], c[8], c[17], c[24], c[26], c[22], c[2], c[10], c[20], c[9],
            c[18], c[25], c[26], c[24], c[3], c[11], c[20], c[10], c[19],
            c[21], c[26], c[25], c[4], c[15], c[23], c[12], c[16], c[21],
            c[26], c[22], c[5], c[12], c[23], c[13], c[17], c[22], c[26],
            c[24], c[6], c[13], c[23], c[14], c[18], c[24], c[26], c[25], c[7],
            c[14], c[23], c[15], c[19], c[25], c[26], c[21]
        ]).T
        new_conn = new_conn.reshape((8 * n_el, 8))
        conns.append(new_conn)

        new_mat_id = mesh_in.mat_ids[ig].repeat(8)
        mat_ids.append(new_mat_id)

    mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, conns, mat_ids,
                          mesh_in.descs)

    return mesh
Example #19
0
    def test_refine_hexa(self):
        mesh = Mesh('mesh_hexa',
                    data_dir + '/meshes/various_formats/abaqus_hex.inp')
        domain = Domain('domain', mesh)

        refine(domain, self.options.out_dir)

        return True
Example #20
0
def refine_3_8(mesh_in, ed, fa):
    """
    Refines hexahedral mesh by cutting cutting each edge in half and
    making 8 new finer hexahedrons out of one coarser one.
    """
    # Unique edge centres.
    e_coors, e_uid = ed.get_coors()
    e_centres = 0.5 * nm.sum(e_coors, axis=1)

    # Unique face centres.
    f_coors, f_uid = fa.get_coors()
    f_centres = 0.25 * nm.sum(f_coors, axis=1)

    # Unique element centres.
    coors = mesh_in.get_element_coors()
    centres = 0.125 * nm.sum(coors, axis=1)

    # New coordinates after the original ones.
    coors = nm.r_[mesh_in.coors, e_centres, f_centres, centres]

    o1 = mesh_in.n_nod
    o2 = o1 + e_centres.shape[0]
    o3 = o2 + f_centres.shape[0]

    st = nm.vstack

    conns = []
    mat_ids = []
    for ig, conn in enumerate(mesh_in.conns):
        e_indx = ed.indx[ig]
        f_indx = fa.indx[ig]
        off = mesh_in.el_offsets[ig]
        n_el  = conn.shape[0]

        e_nodes = ed.uid_i[e_indx].reshape((n_el, 12)) + o1
        f_nodes = fa.uid_i[f_indx].reshape((n_el, 6)) + o2
        nodes = nm.arange(n_el) + off + o3

        c = nm.c_[conn, e_nodes, f_nodes, nodes].T

        new_conn = st([c[0], c[8], c[20], c[11], c[16], c[22], c[26], c[21],
                       c[1], c[9], c[20], c[8], c[17], c[24], c[26], c[22],
                       c[2], c[10], c[20], c[9], c[18], c[25], c[26], c[24],
                       c[3], c[11], c[20], c[10], c[19], c[21], c[26], c[25],
                       c[4], c[15], c[23], c[12], c[16], c[21], c[26], c[22],
                       c[5], c[12], c[23], c[13], c[17], c[22], c[26], c[24],
                       c[6], c[13], c[23], c[14], c[18], c[24], c[26], c[25],
                       c[7], c[14], c[23], c[15], c[19], c[25], c[26], c[21]]).T
        new_conn = new_conn.reshape((8 * n_el, 8))
        conns.append(new_conn)

        new_mat_id = mesh_in.mat_ids[ig].repeat(8)
        mat_ids.append(new_mat_id)

    mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, conns,
                          mat_ids, mesh_in.descs )

    return mesh
Example #21
0
    def test_invariance_qp(self):
        from sfepy import data_dir
        from sfepy.fem import (Mesh, Domain, H1NodalVolumeField,
                               Variables, Integral)
        from sfepy.terms import Term
        from sfepy.fem.mappings import get_physical_qps

        mesh = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh')

        bbox = mesh.get_bounding_box()
        dd = bbox[1,:] - bbox[0,:]
        data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / dd[0]) \
               * nm.cos(4.0 * nm.pi * mesh.coors[:,1:2] / dd[1])

        variables = {
            'u'       : ('unknown field', 'scalar_tp', 0),
            'v'       : ('test field',    'scalar_tp', 'u'),
        }

        domain = Domain('domain', mesh)
        omega = domain.create_region('Omega', 'all')
        field = H1NodalVolumeField('scalar_tp', nm.float64, 1, omega,
                                   approx_order=1)
        ff = {field.name : field}

        vv = Variables.from_conf(transform_variables(variables), ff)
        u = vv['u']
        u.set_from_mesh_vertices(data)

        integral = Integral('i', order=2)
        term = Term.new('ev_volume_integrate(u)', integral, omega, u=u)
        term.setup()
        val1, _ = term.evaluate(mode='qp')
        val1 = val1.ravel()

        qps = get_physical_qps(omega, integral)
        coors = qps.get_merged_values()

        val2 = u.evaluate_at(coors).ravel()

        self.report('max. difference:', nm.abs(val1 - val2).max())
        ok = nm.allclose(val1, val2, rtol=0.0, atol=1e-12)
        self.report('invariance in qp: %s' % ok)

        return ok
Example #22
0
    def from_conf( conf, options ):
        from sfepy import data_dir
        from sfepy.fem import Mesh, Domain, Functions

        mesh = Mesh('test mesh',
                    data_dir + '/meshes/various_formats/abaqus_tet.inp')
        mesh.nodal_bcs['set0'] = [0, 7]
        domain = Domain('test domain', mesh)

        conf_functions = {
            'get_vertices' : (get_vertices,),
            'get_cells' : (get_cells,),
        }
        functions = Functions.from_conf(transform_functions(conf_functions))

        test = Test(conf=conf, options=options,
                    domain=domain, functions=functions)
        return test
Example #23
0
def refine_3_4(mesh_in, cmesh):
    """
    Refines tetrahedra by cutting each edge in half and making 8 new
    finer tetrahedra out of one coarser one. Old nodal coordinates come
    first in `coors`, then the new ones. The new tetrahedra are similar
    to the old one, no degeneration is supposed to occur as at most 3
    congruence classes of tetrahedra appear, even when re-applied
    iteratively (provided that `conns` are not modified between two
    applications - ordering of vertices in tetrahedra matters not only
    for positivity of volumes).

    References:

    - Juergen Bey: Simplicial grid refinement: on Freudenthal s algorithm and 
      the optimal number of congruence classes, Numer.Math. 85 (2000), 
      no. 1, 1--29, or
    - Juergen Bey: Tetrahedral grid refinement, Computing 55 (1995), 
      no. 4, 355--378, or
      http://citeseer.ist.psu.edu/bey95tetrahedral.html
    """
    # Unique edge centres.
    e_centres = cmesh.get_centroids(cmesh.dim - 2)

    # New coordinates after the original ones.
    coors = nm.r_[mesh_in.coors, e_centres]

    o1 = mesh_in.n_nod

    cc = cmesh.get_conn(cmesh.dim, cmesh.dim - 2)
    offs = cc.offsets

    conns = []
    mat_ids = []
    for ig, conn in enumerate(mesh_in.conns):
        off0, off1 = mesh_in.el_offsets[ig:ig + 2]
        n_el = conn.shape[0]

        e_nodes = cc.indices[offs[off0]:offs[off1]].reshape((n_el, 6)) + o1

        c = nm.c_[conn, e_nodes].T

        new_conn = nm.vstack([
            c[0], c[4], c[6], c[7], c[4], c[1], c[5], c[8], c[6], c[5], c[2],
            c[9], c[7], c[8], c[9], c[3], c[4], c[6], c[7], c[8], c[4], c[6],
            c[8], c[5], c[6], c[7], c[8], c[9], c[6], c[5], c[9], c[8]
        ]).T
        new_conn = new_conn.reshape((8 * n_el, 4))
        conns.append(new_conn)

        new_mat_id = mesh_in.mat_ids[ig].repeat(8)
        mat_ids.append(new_mat_id)

    mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, conns, mat_ids,
                          mesh_in.descs)

    return mesh
Example #24
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
Example #25
0
def refine_3_4(mesh_in, ed):
    """
    Refines tetrahedra by cutting each edge in half and making 8 new
    finer tetrahedra out of one coarser one. Old nodal coordinates come
    first in `coors`, then the new ones. The new tetrahedra are similar
    to the old one, no degeneration is supposed to occur as at most 3
    congruence classes of tetrahedra appear, even when re-applied
    iteratively (provided that `conns` are not modified between two
    applications - ordering of vertices in tetrahedra matters not only
    for positivity of volumes).

    References:

    - Juergen Bey: Simplicial grid refinement: on Freudenthal s algorithm and 
      the optimal number of congruence classes, Numer.Math. 85 (2000), 
      no. 1, 1--29, or
    - Juergen Bey: Tetrahedral grid refinement, Computing 55 (1995), 
      no. 4, 355--378, or
      http://citeseer.ist.psu.edu/bey95tetrahedral.html
    """
    # Unique edge centres.
    e_coors, e_uid = ed.get_coors()
    e_centres = 0.5 * nm.sum(e_coors, axis=1)

    # New coordinates after the original ones.
    coors = nm.r_[mesh_in.coors, e_centres]

    conns = []
    mat_ids = []
    for ig, conn in enumerate(mesh_in.conns):
        indx = ed.indx[ig]
        n_el  = conn.shape[0]

        e_nodes = ed.uid_i[indx].reshape((n_el, 6)) + mesh_in.n_nod

        c = nm.c_[conn, e_nodes].T

        new_conn = nm.vstack([c[0], c[4], c[6], c[7],
                              c[4], c[1], c[5], c[8],
                              c[6], c[5], c[2], c[9],
                              c[7], c[8], c[9], c[3],
                              c[4], c[6], c[7], c[8],
                              c[4], c[6], c[8], c[5],
                              c[6], c[7], c[8], c[9],
                              c[6], c[5], c[9], c[8]]).T
        new_conn = new_conn.reshape((8 * n_el, 4))
        conns.append(new_conn)

        new_mat_id = mesh_in.mat_ids[ig].repeat(8)
        mat_ids.append(new_mat_id)

    mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, conns,
                          mat_ids, mesh_in.descs )

    return mesh
Example #26
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 = 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)
Example #27
0
    def from_conf(conf, options):
        from sfepy import data_dir
        from sfepy.fem import Mesh, Domain, Functions

        mesh = Mesh('test mesh',
                    data_dir + '/meshes/various_formats/abaqus_tet.inp')
        mesh.nodal_bcs['set0'] = [0, 7]
        domain = Domain('test domain', mesh)

        conf_functions = {
            'get_nodes': (get_nodes, ),
            'get_elements': (get_elements, ),
        }
        functions = Functions.from_conf(transform_functions(conf_functions))

        test = Test(conf=conf,
                    options=options,
                    domain=domain,
                    functions=functions)
        return test
Example #28
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
Example #29
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
Example #30
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
Example #31
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')
Example #32
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
Example #33
0
    def test_interpolation(self):
        from sfepy import data_dir
        from sfepy.fem import Mesh
        from sfepy.linalg import make_axis_rotation_matrix

        fname = in_dir(self.options.out_dir)

        meshes = {
            'tp': Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'),
            'si': Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'),
        }

        datas = gen_datas(meshes)

        for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']:
            m1 = meshes[field_name[-2:]]

            for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)):
                self.report('%s: %d. angle: %f' % (field_name, ia, angle))
                shift = [0.0, 0.0, 0.0]
                mtx = make_axis_rotation_matrix([0, 1, 0], angle)

                m2 = m1.copy('rotated mesh')
                m2.transform_coors(mtx)

                data = datas[field_name]
                u1, u2 = do_interpolation(m2, m1, data, field_name)

                if ia == 0:
                    u1.save_as_mesh(
                        fname('test_mesh_interp_%s_u1.vtk' % field_name))

                u2.save_as_mesh(
                    fname('test_mesh_interp_%s_u2.%03d.vtk' %
                          (field_name, ia)))

        return True
Example #34
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
Example #35
0
    def test_invariance(self):
        from sfepy import data_dir
        from sfepy.fem import Mesh

        meshes = {
            'tp': Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'),
            'si': Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'),
        }
        datas = gen_datas(meshes)

        ok = True
        for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']:
            m1 = meshes[field_name[-2:]]

            data = datas[field_name]
            u1, u2 = do_interpolation(m1, m1, data, field_name, force=True)

            self.report('max. difference:', nm.abs(u1() - u2()).max())
            _ok = nm.allclose(u1(), u2(), rtol=0.0, atol=1e-12)
            self.report('invariance for %s field: %s' % (field_name, _ok))

            ok = ok and _ok

        return ok
Example #36
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")
Example #37
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
Example #38
0
def refine_2_4(mesh_in, cmesh):
    """
    Refines mesh out of quadrilaterals by cutting cutting each edge in
    half and making 4 new finer quadrilaterals out of one coarser one.
    """
    # Unique edge centres.
    e_centres = cmesh.get_centroids(cmesh.dim - 1)

    # Unique element centres.
    centres = cmesh.get_centroids(cmesh.dim)

    # New coordinates after the original ones.
    coors = nm.r_[mesh_in.coors, e_centres, centres]

    o1 = mesh_in.n_nod
    o2 = o1 + e_centres.shape[0]

    cc = cmesh.get_conn(cmesh.dim, cmesh.dim - 1)
    offs = cc.offsets

    conns = []
    mat_ids = []
    for ig, conn in enumerate(mesh_in.conns):
        off0, off1 = mesh_in.el_offsets[ig:ig + 2]
        n_el = conn.shape[0]

        e_nodes = cc.indices[offs[off0]:offs[off1]].reshape((n_el, 4)) + o1
        nodes = nm.arange(n_el) + off0 + o2

        c = nm.c_[conn, e_nodes, nodes].T

        new_conn = nm.vstack([
            c[0], c[4], c[8], c[7], c[1], c[5], c[8], c[4], c[2], c[6], c[8],
            c[5], c[3], c[7], c[8], c[6]
        ]).T
        new_conn = new_conn.reshape((4 * n_el, 4))
        conns.append(new_conn)

        new_mat_id = mesh_in.mat_ids[ig].repeat(4)
        mat_ids.append(new_mat_id)

    mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, conns, mat_ids,
                          mesh_in.descs)

    return mesh
Example #39
0
def refine_2_4(mesh_in, ed):
    """
    Refines mesh out of quadrilaterals by cutting cutting each edge in
    half and making 4 new finer quadrilaterals out of one coarser one.
    """
    # Unique edge centres.
    e_coors, e_uid = ed.get_coors()
    e_centres = 0.5 * nm.sum(e_coors, axis=1)

    # Unique element centres.
    coors = mesh_in.get_element_coors()
    centres = 0.25 * nm.sum(coors, axis=1)

    # New coordinates after the original ones.
    coors = nm.r_[mesh_in.coors, e_centres, centres]

    o1 = mesh_in.n_nod
    o2 = o1 + e_centres.shape[0]

    conns = []
    mat_ids = []
    for ig, conn in enumerate(mesh_in.conns):
        e_indx = ed.indx[ig]
        off = mesh_in.el_offsets[ig]
        n_el = conn.shape[0]

        e_nodes = ed.uid_i[e_indx].reshape((n_el, 4)) + o1
        nodes = nm.arange(n_el) + off + o2

        c = nm.c_[conn, e_nodes, nodes].T

        new_conn = nm.vstack([
            c[0], c[4], c[8], c[7], c[1], c[5], c[8], c[4], c[2], c[6], c[8],
            c[5], c[3], c[7], c[8], c[6]
        ]).T
        new_conn = new_conn.reshape((4 * n_el, 4))
        conns.append(new_conn)

        new_mat_id = mesh_in.mat_ids[ig].repeat(4)
        mat_ids.append(new_mat_id)

    mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, conns, mat_ids,
                          mesh_in.descs)

    return mesh
Example #40
0
def refine_2_4(mesh_in, ed):
    """
    Refines mesh out of quadrilaterals by cutting cutting each edge in
    half and making 4 new finer quadrilaterals out of one coarser one.
    """
    # Unique edge centres.
    e_coors, e_uid = ed.get_coors()
    e_centres = 0.5 * nm.sum(e_coors, axis=1)

    # Unique element centres.
    coors = mesh_in.get_element_coors()
    centres = 0.25 * nm.sum(coors, axis=1)

    # New coordinates after the original ones.
    coors = nm.r_[mesh_in.coors, e_centres, centres]

    o1 = mesh_in.n_nod
    o2 = o1 + e_centres.shape[0]

    conns = []
    mat_ids = []
    for ig, conn in enumerate(mesh_in.conns):
        e_indx = ed.indx[ig]
        off = mesh_in.el_offsets[ig]
        n_el  = conn.shape[0]

        e_nodes = ed.uid_i[e_indx].reshape((n_el, 4)) + o1
        nodes = nm.arange(n_el) + off + o2

        c = nm.c_[conn, e_nodes, nodes].T

        new_conn = nm.vstack([c[0], c[4], c[8], c[7],
                              c[1], c[5], c[8], c[4],
                              c[2], c[6], c[8], c[5],
                              c[3], c[7], c[8], c[6]]).T
        new_conn = new_conn.reshape((4 * n_el, 4))
        conns.append(new_conn)

        new_mat_id = mesh_in.mat_ids[ig].repeat(4)
        mat_ids.append(new_mat_id)

    mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, conns,
                          mat_ids, mesh_in.descs )

    return mesh
Example #41
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
Example #42
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
Example #43
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
Example #44
0
def refine_2_4(mesh_in, cmesh):
    """
    Refines mesh out of quadrilaterals by cutting cutting each edge in
    half and making 4 new finer quadrilaterals out of one coarser one.
    """
    # Unique edge centres.
    e_centres = cmesh.get_centroids(cmesh.dim - 1)

    # Unique element centres.
    centres = cmesh.get_centroids(cmesh.dim)

    # New coordinates after the original ones.
    coors = nm.r_[mesh_in.coors, e_centres, centres]

    o1 = mesh_in.n_nod
    o2 = o1 + e_centres.shape[0]

    cc = cmesh.get_conn(cmesh.dim, cmesh.dim - 1)
    offs = cc.offsets

    conns = []
    mat_ids = []
    for ig, conn in enumerate(mesh_in.conns):
        off0, off1 = mesh_in.el_offsets[ig : ig + 2]
        n_el = conn.shape[0]

        e_nodes = cc.indices[offs[off0] : offs[off1]].reshape((n_el, 4)) + o1
        nodes = nm.arange(n_el) + off0 + o2

        c = nm.c_[conn, e_nodes, nodes].T

        new_conn = nm.vstack(
            [c[0], c[4], c[8], c[7], c[1], c[5], c[8], c[4], c[2], c[6], c[8], c[5], c[3], c[7], c[8], c[6]]
        ).T
        new_conn = new_conn.reshape((4 * n_el, 4))
        conns.append(new_conn)

        new_mat_id = mesh_in.mat_ids[ig].repeat(4)
        mat_ids.append(new_mat_id)

    mesh = Mesh.from_data(mesh_in.name + "_r", coors, None, conns, mat_ids, mesh_in.descs)

    return mesh
Example #45
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
Example #46
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
Example #47
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
Example #49
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()
Example #50
0
    def save(self, filename):
        coors = []
        conns = []
        mat_ids = []
        offset = 0
        for ig, dual_surface in self.dual_surfaces.iteritems():
            cc = dual_surface.dual_coors
            coors.append(cc)

            conn = dual_surface.conn[:, 1:].copy() + offset
            conns.append(conn)

            mat_id = nm.empty((conn.shape[0],), dtype=nm.int32)
            mat_id[:] = ig
            mat_ids.append(mat_id)

            offset += cc.shape[0]

        coors = nm.concatenate(coors, axis=0)

        dual_mesh = Mesh.from_data("dual_mesh", coors, None, conns, mat_ids, ["2_3"] * len(conns))
        dual_mesh.write(filename, io="auto")
Example #51
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
Example #52
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
Example #53
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()
Example #54
0
    def save(self, filename):
        coors = []
        conns = []
        mat_ids = []
        offset = 0
        for ig, dual_surface in self.dual_surfaces.iteritems():
            cc = dual_surface.dual_coors
            coors.append(cc)

            conn = dual_surface.conn[:, 1:].copy() + offset
            conns.append(conn)

            mat_id = nm.empty((conn.shape[0], ), dtype=nm.int32)
            mat_id[:] = ig
            mat_ids.append(mat_id)

            offset += cc.shape[0]

        coors = nm.concatenate(coors, axis=0)

        dual_mesh = Mesh.from_data('dual_mesh', coors, None, conns, mat_ids,
                                   ['2_3'] * len(conns))
        dual_mesh.write(filename, io='auto')
Example #55
0
def refine_2_3(mesh_in, ed):
    """
    Refines mesh out of triangles by cutting cutting each edge in half
    and making 4 new finer triangles out of one coarser one.
    """
    # Unique edge centres.
    e_coors, e_uid = ed.get_coors()
    e_centres = 0.5 * nm.sum(e_coors, axis=1)

    # New coordinates after the original ones.
    coors = nm.r_[mesh_in.coors, e_centres]

    conns = []
    mat_ids = []
    for ig, conn in enumerate(mesh_in.conns):
        indx = ed.indx[ig]
        n_el  = conn.shape[0]

        e_nodes = ed.uid_i[indx].reshape((n_el, 3)) + mesh_in.n_nod

        c = nm.c_[conn, e_nodes].T

        new_conn = nm.vstack([c[0], c[3], c[5],
                              c[3], c[4], c[5],
                              c[1], c[4], c[3],
                              c[2], c[5], c[4]]).T
        new_conn = new_conn.reshape((4 * n_el, 3))
        conns.append(new_conn)

        new_mat_id = mesh_in.mat_ids[ig].repeat(4)
        mat_ids.append(new_mat_id)

    mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, conns,
                          mat_ids, mesh_in.descs )

    return mesh
Example #56
0
def refine_2_3(mesh_in, ed):
    """
    Refines mesh out of triangles by cutting cutting each edge in half
    and making 4 new finer triangles out of one coarser one.
    """
    # Unique edge centres.
    e_coors, e_uid = ed.get_coors()
    e_centres = 0.5 * nm.sum(e_coors, axis=1)

    # New coordinates after the original ones.
    coors = nm.r_[mesh_in.coors, e_centres]

    conns = []
    mat_ids = []
    for ig, conn in enumerate(mesh_in.conns):
        indx = ed.indx[ig]
        n_el = conn.shape[0]

        e_nodes = ed.uid_i[indx].reshape((n_el, 3)) + mesh_in.n_nod

        c = nm.c_[conn, e_nodes].T

        new_conn = nm.vstack([
            c[0], c[3], c[5], c[3], c[4], c[5], c[1], c[4], c[3], c[2], c[5],
            c[4]
        ]).T
        new_conn = new_conn.reshape((4 * n_el, 3))
        conns.append(new_conn)

        new_mat_id = mesh_in.mat_ids[ig].repeat(4)
        mat_ids.append(new_mat_id)

    mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, conns, mat_ids,
                          mesh_in.descs)

    return mesh
Example #57
0
    def from_conf(conf, options):
        mesh = Mesh('mesh_tetra',
                    data_dir + '/meshes/various_formats/small3d.mesh')
        domain = Domain('domain', mesh)

        return Test(conf=conf, options=options, domain=domain)
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()
Example #59
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)