예제 #1
0
    def test_write_read_meshes(self):
        """
        Try to write and then read all supported formats.
        """
        from sfepy.discrete.fem import Mesh
        from sfepy.discrete.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 six.iteritems(supported_formats):
            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)
예제 #2
0
    def test_write_read_meshes(self):
        """
        Try to write and then read all supported formats.
        """
        from sfepy.discrete.fem import Mesh
        from sfepy.discrete.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)
예제 #3
0
    def test_interpolation(self):
        from sfepy import data_dir
        from sfepy.discrete.fem import Mesh
        from sfepy.linalg import make_axis_rotation_matrix

        fname = in_dir(self.options.out_dir)

        meshes = {
            'tp' : Mesh.from_file(data_dir + '/meshes/3d/block.mesh'),
            'si' : Mesh.from_file(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
예제 #4
0
    def test_interpolation_two_meshes(self):
        from sfepy import data_dir
        from sfepy.discrete import Variables
        from sfepy.discrete.fem import Mesh, FEDomain, Field

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

        m2 = Mesh.from_file(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 = FEDomain('d1', m1)
        omega1 = d1.create_region('Omega', 'all')
        field1 = Field.from_args('scalar_tp',
                                 nm.float64, (1, 1),
                                 omega1,
                                 approx_order=1)
        ff1 = {field1.name: field1}

        d2 = FEDomain('d2', m2)
        omega2 = d2.create_region('Omega', 'all')
        field2 = Field.from_args('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
예제 #5
0
    def test_interpolation_two_meshes(self):
        from sfepy import data_dir
        from sfepy.discrete import Variables
        from sfepy.discrete.fem import Mesh, FEDomain, Field

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

        m2 = Mesh.from_file(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 = FEDomain('d1', m1)
        omega1 = d1.create_region('Omega', 'all')
        field1 = Field.from_args('scalar_tp', nm.float64, (1,1), omega1,
                                 approx_order=1)
        ff1 = {field1.name : field1}

        d2 = FEDomain('d2', m2)
        omega2 = d2.create_region('Omega', 'all')
        field2 = Field.from_args('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
예제 #6
0
    def test_write_read_meshes(self):
        """
        Try to write and then read all supported formats.
        """
        import numpy as nm
        from sfepy.discrete.fem import Mesh
        from sfepy.discrete.fem.meshio import supported_formats

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

        mesh0.cmesh.vertex_groups[:] =\
            nm.random.randint(1, 10, size=mesh0.cmesh.n_coor)

        mesh0.cmesh.cell_groups[:] =\
            nm.random.randint(1, 10, size=mesh0.cmesh.n_el)

        oks = []
        for name, (cls, suffix, flag) in six.iteritems(supported_formats):
            if 'w' not in flag: continue

            suffix = suffix[0]  # only the first of possible suffixes
            filename = op.join(self.options.out_dir, 'test_mesh_wr' + suffix)
            self.report('%s format: %s' % (suffix, filename))

            try:
                mesh0.write(filename, io='auto')

            except RuntimeError:
                if cls == 'meshio':
                    import traceback
                    self.report('-> cannot write "%s" format into "%s",'
                                ' skipping' % (name, filename))
                    tb = traceback.format_exc()
                    self.report('reason:\n', tb)
                    continue

                else:
                    raise

            else:
                mesh1 = Mesh.from_file(filename)

            ok = self._compare_meshes(mesh0, mesh1, flag)
            self.report('->', sum(ok) == len(ok))
            oks.extend(ok)

        return sum(oks) == len(oks)
예제 #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.discrete.fem import Mesh, FEDomain

    if level > 0:
        mesh = Mesh.from_file(filename)
        domain = FEDomain(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
예제 #8
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)
예제 #9
0
    def test_read_meshes(self):
        """Try to read all listed meshes."""
        from sfepy.discrete.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
예제 #10
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)
예제 #11
0
    def test_refine_3_8(self):
        mesh = Mesh.from_file(data_dir + '/meshes/elements/3_8_1.mesh')
        domain = refine(FEDomain('domain', mesh), self.options.out_dir, 1)

        ok = compare_mesh('3_8', domain.mesh.coors, domain.mesh.get_conn('3_8'))

        return ok
예제 #12
0
def main():
    parser = ArgumentParser(description=__doc__,
                            formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('mesh_dir')
    options = parser.parse_args()

    mesh_dir = options.mesh_dir

    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)
예제 #13
0
    def test_rcm(self):
        from sfepy import data_dir
        from sfepy.linalg import rcm, permute_in_place, save_sparse_txt
        from sfepy.discrete.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
예제 #14
0
def main():
    parser = ArgumentParser(description=__doc__,
                            formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('mesh_dir')
    options = parser.parse_args()

    mesh_dir = options.mesh_dir

    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)
예제 #15
0
파일: extract_edges.py 프로젝트: rc/sfepy
def main():
    parser = ArgumentParser(description=__doc__)
    parser.add_argument('--version', action='version', version='%(prog)s')
    parser.add_argument('--eps', action='store', dest='eps',
                        default=1e-12, help=helps['eps'])
    parser.add_argument('-o', '--filename-out',
                        action='store', dest='filename_out',
                        default=None, help=helps['filename-out'])
    parser.add_argument('filename')
    options = parser.parse_args()

    filename = options.filename

    mesh = Mesh.from_file(filename)
    mesh_out = extract_edges(mesh, eps=float(options.eps))
    mesh_out = merge_lines(mesh_out)

    filename_out = options.filename_out
    if filename_out is None:
        filename_out = edit_filename(filename, prefix='edge_', new_ext='.vtk')

    output('Outline mesh - vertices: %d, edges: %d, output filename: %s'
           % (mesh_out[0].shape[0], mesh_out[2][0].shape[0], filename_out))

    # hack to write '3_2' elements - edges
    io = VTKMeshIO(None)
    aux_mesh = Struct()
    aux_mesh._get_io_data = lambda: mesh_out
    aux_mesh.n_el = mesh_out[2][0].shape[0]
    io.write(filename_out, aux_mesh)
예제 #16
0
    def test_read_meshes(self):
        """Try to read all listed meshes."""
        from sfepy.discrete.fem import Mesh

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

            except Exception as exc:
                self.report(exc)
                self.report('read failed!')
                ok = False
                continue

            try:
                assert_(mesh.dim == (mesh.coors.shape[1]))
                assert_(mesh.n_nod == (mesh.coors.shape[0]))
                assert_(mesh.n_nod == (mesh.cmesh.vertex_groups.shape[0]))
                assert_(mesh.n_el == mesh.cmesh.num[mesh.cmesh.tdim])

            except ValueError as exc:
                self.report(exc)
                self.report('read assertion failed!')
                ok = False
                continue

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

        return ok
예제 #17
0
def main():
    parser = ArgumentParser(description=__doc__.rstrip(),
                            formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('filename', help=helps['filename'])
    parser.add_argument('-d', '--detailed',
                        action='store_true', dest='detailed',
                        default=False, help=helps['detailed'])
    options = parser.parse_args()

    mesh = Mesh.from_file(options.filename)

    output(mesh.cmesh)
    output('element types:', mesh.descs)
    output('nodal BCs:', sorted(mesh.nodal_bcs.keys()))

    bbox = mesh.get_bounding_box()
    output('bounding box: %s'
           % ', '.join('%s: [%s, %s]' % (name, bbox[0, ii], bbox[1, ii])
                       for ii, name in enumerate('xyz'[:mesh.dim])))

    output('centre:', mesh.coors.mean(0))

    if not options.detailed: return

    from sfepy.discrete.fem.geometry_element import create_geometry_elements
    gels = create_geometry_elements()
    mesh.cmesh.set_local_entities(gels)
    mesh.cmesh.setup_entities()

    for dim in range(1, mesh.cmesh.tdim + 1):
        volumes = mesh.cmesh.get_volumes(dim)
        output('volumes of %d %dD entities: min: %s mean: %s max: %s'
               % (mesh.cmesh.num[dim],
                  dim, volumes.min(), volumes.mean(), volumes.max()))
예제 #18
0
def prepare_variable(filename, n_components):
    from sfepy.discrete import FieldVariable
    from sfepy.discrete.fem import Mesh, FEDomain, Field

    mesh = Mesh.from_file(filename)

    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]))

    domain = FEDomain('domain', mesh)
    omega = domain.create_region('Omega', 'all')
    field = Field.from_args('field',
                            nm.float64,
                            n_components,
                            omega,
                            approx_order=2)

    u = FieldVariable('u',
                      'parameter',
                      field,
                      primary_var_name='(set-to-None)')
    u.set_from_mesh_vertices(data * nm.arange(1, n_components + 1)[None, :])

    return u
예제 #19
0
    def from_conf(conf, options):
        from sfepy.discrete import FieldVariable, Variables, Problem
        from sfepy.discrete.fem import Mesh, FEDomain, Field

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

        omega = domain.create_region('Omega', 'all')
        domain.create_region('Left', 'vertices in (x < -0.499)', 'facet')
        domain.create_region(
            'LeftStrip', 'vertices in (x < -0.499)'
            ' & (y > -0.199) & (y < 0.199)', 'facet')
        domain.create_region('LeftFix', 'r.Left -v r.LeftStrip', 'facet')
        domain.create_region('Right', 'vertices in (x > 0.499)', 'facet')
        domain.create_region(
            'RightStrip', 'vertices in (x > 0.499)'
            ' & (y > -0.199) & (y < 0.199)', 'facet')
        domain.create_region('RightFix', 'r.Right -v r.RightStrip', 'facet')

        fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2)
        u = FieldVariable('u', 'unknown', fu)

        fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2)
        p = FieldVariable('p', 'unknown', fp)

        pb = Problem('test', domain=domain, fields=[fu, fp], auto_conf=False)

        test = Test(problem=pb,
                    variables=Variables([u, p]),
                    conf=conf,
                    options=options)
        return test
예제 #20
0
    def from_conf(conf, options):
        from sfepy.discrete import Integral
        from sfepy.discrete.fem import Mesh, FEDomain

        domains = []
        for filename in filename_meshes:
            mesh = Mesh.from_file(filename)
            domain = FEDomain('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)
        qp_coors, qp_weights = integral.get_qp('3_8')
        custom_integral = Integral('i',
                                   coors=qp_coors,
                                   weights=qp_weights,
                                   order='custom')

        test = Test(domains=domains,
                    integral=integral,
                    custom_integral=custom_integral,
                    conf=conf,
                    options=options)
        return test
예제 #21
0
    def from_conf(conf, options):
        import sfepy
        from sfepy.discrete.fem import Mesh, Domain, Field
        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 = Field.from_args('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
예제 #22
0
    def test_spbox_2d(self):
        """
        Check position of a given vertex in the deformed mesh.
        """
        mesh = Mesh.from_file(data_dir + '/meshes/2d/square_tri1.mesh')
        spb = SplineBox([[-1, 1], [-1, 0.6]], mesh.coors, nsg=[2,1])
        spb.move_control_point(1, [0.1, -0.2])
        spb.move_control_point(2, [0.2, -0.3])
        spb.move_control_point(3, [0.0, -0.1])

        pt0 = mesh.coors[175,:].copy()
        mesh.cmesh.coors[:] = spb.evaluate()
        pt1 = mesh.coors[175,:]

        expected_distance = 0.165892726387
        actual_distance = nm.linalg.norm(pt0 - pt1)
        ok = nm.fabs(actual_distance - expected_distance)\
            / expected_distance < tolerance

        if not ok:
            self.report('expected distance:')
            self.report(expected_distance)
            self.report('actual distance:')
            self.report(actual_distance)

        return ok
예제 #23
0
    def test_spbox_2d(self):
        """
        Check position of a given vertex in the deformed mesh.
        """
        mesh = Mesh.from_file(data_dir + '/meshes/2d/square_tri1.mesh')
        spb = SplineBox([[-1, 1], [-1, 0.6]], mesh.coors, nsg=[2, 1])
        spb.move_control_point(1, [0.1, -0.2])
        spb.move_control_point(2, [0.2, -0.3])
        spb.move_control_point(3, [0.0, -0.1])

        pt0 = mesh.coors[175, :].copy()
        mesh.cmesh.coors[:] = spb.evaluate()
        pt1 = mesh.coors[175, :]

        expected_distance = 0.165892726387
        actual_distance = nm.linalg.norm(pt0 - pt1)
        ok = nm.fabs(actual_distance - expected_distance)\
            / expected_distance < tolerance

        if not ok:
            self.report('expected distance:')
            self.report(expected_distance)
            self.report('actual distance:')
            self.report(actual_distance)

        return ok
예제 #24
0
파일: utils.py 프로젝트: Nasrollah/sfepy
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.discrete.fem import Mesh, FEDomain

    if level > 0:
        mesh = Mesh.from_file(filename)
        domain = FEDomain(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
예제 #25
0
def main():
    parser = ArgumentParser(description=__doc__)
    parser.add_argument('--version', action='version', version='%(prog)s')
    parser.add_argument('filename')
    options = parser.parse_args()

    filename = options.filename

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

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

    entities_opts = [
        {'color' : 'k', 'label_global' : 12, 'label_local' : 8},
        {'color' : 'b', 'label_global' : 12, 'label_local' : 8},
        {'color' : 'g', 'label_global' : 12, 'label_local' : 8},
        {'color' : 'r', 'label_global' : 12},
    ]
    if dim == 2: entities_opts.pop(2)

    pc.plot_cmesh(None, domain.cmesh,
                  wireframe_opts = {'color' : 'k'},
                  entities_opts=entities_opts)

    plt.show()
예제 #26
0
    def from_conf(conf, options):
        import sfepy
        from sfepy.discrete.fem import Mesh, FEDomain, Field
        mesh = Mesh.from_file('meshes/2d/rectangle_tri.mesh',
                              prefix_dir=sfepy.data_dir)
        domain = FEDomain('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 = Field.from_args('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
예제 #27
0
    def test_rcm(self):
        from sfepy import data_dir
        from sfepy.linalg import rcm, permute_in_place, save_sparse_txt
        from sfepy.discrete.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
예제 #28
0
def main():
    parser = ArgumentParser(description=__doc__.rstrip(),
                            formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('filename', help=helps['filename'])
    parser.add_argument('-d', '--detailed',
                        action='store_true', dest='detailed',
                        default=False, help=helps['detailed'])
    options = parser.parse_args()

    mesh = Mesh.from_file(options.filename)

    output(mesh.cmesh)
    output('element types:', mesh.descs)
    output('nodal BCs:', sorted(mesh.nodal_bcs.keys()))

    bbox = mesh.get_bounding_box()
    output('bounding box:\n%s'
           % '\n'.join('%s: [%14.7e, %14.7e]' % (name, bbox[0, ii], bbox[1, ii])
                       for ii, name in enumerate('xyz'[:mesh.dim])))

    output('centre:           [%s]'
           % ', '.join('%14.7e' % ii for ii in 0.5 * (bbox[0] + bbox[1])))
    output('coordinates mean: [%s]'
           % ', '.join('%14.7e' % ii for ii in mesh.coors.mean(0)))

    if not options.detailed: return

    domain = FEDomain(mesh.name, mesh)

    for dim in range(1, mesh.cmesh.tdim + 1):
        volumes = mesh.cmesh.get_volumes(dim)
        output('volumes of %d %dD entities:\nmin: %.7e mean: %.7e median:'
               ' %.7e max: %.7e'
               % (mesh.cmesh.num[dim], dim, volumes.min(), volumes.mean(),
                  nm.median(volumes), volumes.max()))

    euler = lambda mesh: nm.dot(mesh.cmesh.num, [1, -1, 1, -1])
    ec = euler(mesh)
    output('Euler characteristic:', ec)

    graph = mesh.create_conn_graph(verbose=False)
    n_comp, _ = graph_components(graph.shape[0], graph.indptr, graph.indices)
    output('number of connected components:', n_comp)

    if mesh.dim > 1:
        region = domain.create_region('surf', 'vertices of surface', 'facet')
        surf_mesh = Mesh.from_region(region, mesh,
                                     localize=True, is_surface=True)
        FEDomain(surf_mesh.name, surf_mesh) # Calls CMesh.setup_entities().

        sec = euler(surf_mesh)
        output('surface Euler characteristic:', sec)
        if mesh.dim == 3:
            output('surface genus:', (2.0 - sec) / 2.0)

        surf_graph = surf_mesh.create_conn_graph(verbose=False)
        n_comp, _ = graph_components(surf_graph.shape[0],
                                     surf_graph.indptr, surf_graph.indices)
        output('number of connected surface components:', n_comp)
예제 #29
0
파일: test_cmesh.py 프로젝트: clazaro/sfepy
    def test_entity_volumes(self):
        import sfepy
        from sfepy.discrete.fem import Mesh, FEDomain
        from sfepy.discrete.common import Field
        from sfepy.discrete import Integral

        mesh = Mesh.from_file('meshes/3d/special/cross3d.mesh',
                              prefix_dir=sfepy.data_dir)
        domain = FEDomain('domain', mesh)

        omega = domain.create_region('Omega', 'all')
        gamma = domain.create_region('Gamma', 'vertices of surface', 'facet')
        top = domain.create_region('Top', 'cell 2')

        vfield = Field.from_args('v', nm.float64, 'scalar', omega,
                                 approx_order=1)
        sfield = Field.from_args('s', nm.float64, 'scalar', gamma,
                                 approx_order=1)

        integral = Integral('i', order=3)
        vgeo, _ = vfield.get_mapping(omega, integral, 'volume')
        domain.create_surface_group(gamma)
        sgeo, _ = sfield.get_mapping(gamma, integral, 'surface')

        evols = mesh.cmesh.get_volumes(1)
        fvols = mesh.cmesh.get_volumes(2) # Approximate for non-planar faces.
        cvols = mesh.cmesh.get_volumes(3)

        ok = True
        _ok = abs(cvols.sum() - vgeo.volume.sum()) < 1e-15
        self.report('total cell volume: %s (ok: %s)' % (cvols.sum(), _ok))
        ok = _ok and ok

        top_evols = nm.array([ 1.                ,  1.                ,
                               1.                ,  1.                ,
                               0.7211102550927979,  0.7211102550927979,
                               0.7211102550927979,  0.7211102550927979,
                               1.16619037896906  ,  1.16619037896906  ,
                               1.16619037896906  ,  1.16619037896906  ])

        _ok = nm.allclose(top_evols, evols[top.edges], rtol=0.0, atol=1e-15)
        self.report('total top cell edge length: %s (ok: %s)'
                    % (evols[top.edges].sum(), _ok))
        ok = _ok and ok

        i1 = [5, 6, 8, 9]
        i2 = nm.setdiff1d(nm.arange(len(gamma.faces)), i1)
        aux = fvols[gamma.faces] - sgeo.volume.ravel()

        _ok = nm.allclose(aux[i1], 0.10560208437556773, rtol=0.0, atol=1e-15)
        ok = _ok and ok
        self.report('non-planar faces diff: %s (ok: %s)' % (aux[i1], _ok))

        _ok = (nm.abs(aux[i2]) < 1e-15).all()
        self.report('max. planar faces diff: %s (ok: %s)'
                    % (nm.abs(aux[i2]).max(), _ok))
        ok = _ok and ok

        return ok
예제 #30
0
def solveLaplaceEquationTetrahedral(mesh, meshVTK, boundaryPoints,
                                    boundaryConditions):
    """
    mesh: path to a 3D mesh / sfepy mesh
    
    """
    if isinstance(mesh, str):
        mesh = Mesh.from_file(mesh)

    #Set domains
    domain = FEDomain('domain', mesh)
    omega = domain.create_region('Omega', 'all')
    boundary = domain.create_region(
        'gamma',
        'vertex  %s' % ','.join(map(str, range(meshVTK.GetNumberOfPoints()))),
        'facet')

    #set fields
    field = Field.from_args('fu', np.float64, 1, omega, approx_order=1)
    u = FieldVariable('u', 'unknown', field)
    v = FieldVariable('v', 'test', field, primary_var_name='u')
    m = Material('m', val=[1.])

    #Define element integrals
    integral = Integral('i', order=3)

    #Equations defining
    t1 = Term.new('dw_laplace( v, u )', integral, omega, v=v, u=u)
    eq = Equation('balance', t1)
    eqs = Equations([eq])

    heatBoundary = boundaryConditions
    points = boundaryPoints

    #Boundary conditions
    c = ClosestPointStupid(points, heatBoundary, meshVTK)

    def u_fun(ts, coors, bc=None, problem=None, c=c):
        c.distances = []
        v = np.zeros(len(coors))
        for i, p in enumerate(coors):
            v[i] = c.interpolate(p)
            #c.findClosestPoint(p)
        return v

    bc_fun = Function('u_fun', u_fun)
    fix1 = EssentialBC('fix_u', boundary, {'u.all': bc_fun})

    #Solve problem
    ls = ScipyDirect({})
    nls = Newton({}, lin_solver=ls)

    pb = Problem('heat', equations=eqs)
    pb.set_bcs(ebcs=Conditions([fix1]))

    pb.set_solver(nls)
    state = pb.solve(verbose=False, save_results=False)
    u = state.get_parts()['u']
    return u
예제 #31
0
    def test_refine_hexa(self):
        filename = data_dir + '/meshes/various_formats/abaqus_hex.inp'
        mesh = Mesh.from_file(filename)
        domain = FEDomain('domain', mesh)

        refine(domain, self.options.out_dir)

        return True
예제 #32
0
    def test_refine_3_8(self):
        mesh = Mesh.from_file(data_dir + '/meshes/elements/3_8_1.mesh')
        domain = refine(FEDomain('domain', mesh), self.options.out_dir, 1)

        ok = compare_mesh('3_8', domain.mesh.coors,
                          domain.mesh.get_conn('3_8'))

        return ok
예제 #33
0
    def test_refine_hexa(self):
        filename = data_dir + '/meshes/various_formats/abaqus_hex.inp'
        mesh = Mesh.from_file(filename)
        domain = FEDomain('domain', mesh)

        refine(domain, self.options.out_dir)

        return True
예제 #34
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", "vertices in x < %.10f" % (min_x + eps), "facet")
    gamma2 = domain.create_region("Gamma2", "vertices in x > %.10f" % (max_x - eps), "facet")

    field = Field.from_args("fu", nm.float64, "vector", omega, approx_order=2)

    u = FieldVariable("u", "unknown", field)
    v = FieldVariable("v", "test", field, 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 = Problem("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)
예제 #35
0
    def test_normals(self):
        """
        Check orientations of surface normals on the reference elements.
        """
        import sfepy
        from sfepy.discrete import Integral
        from sfepy.discrete.fem import Mesh, FEDomain
        from sfepy.discrete.fem.poly_spaces import PolySpace
        from sfepy.discrete.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 = FEDomain('domain', mesh)
            surface = domain.create_region('Surface', 'vertices of surface',
                                           'facet')
            domain.create_surface_group(surface)

            sd = domain.surface_groups[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
예제 #36
0
    def from_conf(conf, options):
        mesh = Mesh.from_file('meshes/2d/square_unit_tri.mesh',
                              prefix_dir=sfepy.data_dir)
        domain = FEDomain('domain', mesh)

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

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

        test = Test(conf=conf, options=options, omega=omega, field=field)
        return test
    def test_evaluate_at(self):
        from sfepy import data_dir
        from sfepy.discrete.fem import Mesh
        from sfepy.discrete import Variables
        from sfepy.discrete.fem import FEDomain, Field

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

        fields = {
            'scalar_tp': ((1, 1), 'Omega', 1),
            'vector_tp': ((3, 1), 'Omega', 1),
        }

        ok = True
        for field_name in ['scalar_tp', 'vector_tp']:
            d = FEDomain('d', meshes['tp'])
            d.create_region('Omega', 'all')

            f = fields[field_name]
            field = Field.from_args('f',
                                    nm.complex128,
                                    f[0],
                                    d.regions[f[1]],
                                    approx_order=f[2])
            ff = {field.name: field}

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

            bbox = d.get_mesh_bounding_box()
            t = nm.expand_dims(nm.linspace(0, 1, 100), 1)
            coors = nm.expand_dims(bbox[1] - bbox[0], 0) * t + bbox[0]

            data_r = datas[field_name]
            data_i = 2. / (1 + datas[field_name])

            u.set_from_mesh_vertices(data_r)
            vals_r = u.evaluate_at(coors)
            u.set_from_mesh_vertices(data_i)
            vals_i = u.evaluate_at(coors)
            u.set_from_mesh_vertices(data_r + data_i * 1j)
            vals = u.evaluate_at(coors)

            _ok = nm.allclose(vals_r + vals_i * 1j, vals, rtol=0.0, atol=1e-12)
            _ok = _ok and nm.abs(vals).sum() > 1
            self.report('evaluating complex field %s: %s' % (field_name, _ok))

            ok = ok and _ok

        return ok
예제 #38
0
    def from_conf(conf, options):
        mesh = Mesh.from_file('meshes/2d/square_unit_tri.mesh',
                              prefix_dir=sfepy.data_dir)
        domain = FEDomain('domain', mesh)

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

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

        test = Test(conf=conf, options=options, omega=omega, field=field)
        return test
예제 #39
0
    def test_normals(self):
        """
        Check orientations of surface normals on the reference elements.
        """
        import sfepy
        from sfepy.discrete import Integral
        from sfepy.discrete.fem import Mesh, FEDomain
        from sfepy.discrete.fem.poly_spaces import PolySpace
        from sfepy.discrete.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 = FEDomain('domain', mesh)
            surface = domain.create_region('Surface', 'vertices of surface',
                                           'facet')
            domain.create_surface_group(surface)

            sd = domain.surface_groups[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
예제 #40
0
    def test_evaluate_at(self):
        from sfepy import data_dir
        from sfepy.discrete.fem import Mesh
        from sfepy.discrete import Variables
        from sfepy.discrete.fem import FEDomain, Field

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

        fields = {
            'scalar_tp' : ((1,1), 'Omega', 1),
            'vector_tp' : ((3,1), 'Omega', 1),
        }

        ok = True
        for field_name in ['scalar_tp', 'vector_tp']:
            d = FEDomain('d', meshes['tp'])
            d.create_region('Omega', 'all')

            f = fields[field_name]
            field = Field.from_args('f', nm.complex128, f[0],
                                    d.regions[f[1]],
                                    approx_order=f[2])
            ff = {field.name : field}

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

            bbox = d.get_mesh_bounding_box()
            t = nm.expand_dims(nm.linspace(0, 1, 100), 1)
            coors = nm.expand_dims(bbox[1] - bbox[0], 0) * t + bbox[0]

            data_r = datas[field_name]
            data_i = 2. / (1 + datas[field_name])

            u.set_from_mesh_vertices(data_r)
            vals_r = u.evaluate_at(coors)
            u.set_from_mesh_vertices(data_i)
            vals_i = u.evaluate_at(coors)
            u.set_from_mesh_vertices(data_r + data_i * 1j)
            vals = u.evaluate_at(coors)

            _ok = nm.allclose(vals_r + vals_i * 1j, vals, rtol=0.0, atol=1e-12)
            _ok = _ok and nm.abs(vals).sum() > 1
            self.report('evaluating complex field %s: %s' % (field_name, _ok))

            ok = ok and _ok

        return ok
예제 #41
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 = FEDomain('domain', mesh)
    output(domain.cmesh)
    domain.cmesh.cprint(1)
    dim = domain.cmesh.dim

    entities_opts = [
        {
            'color': 'k',
            'label_global': 12,
            'label_local': 8
        },
        {
            'color': 'b',
            'label_global': 12,
            'label_local': 8
        },
        {
            'color': 'g',
            'label_global': 12,
            'label_local': 8
        },
        {
            'color': 'r',
            'label_global': 12
        },
    ]
    if dim == 2: entities_opts.pop(2)

    pc.plot_cmesh(None,
                  domain.cmesh,
                  wireframe_opts={'color': 'k'},
                  entities_opts=entities_opts)

    plt.show()
예제 #42
0
    def test_invariance(self):
        from sfepy import data_dir
        from sfepy.discrete.fem import Mesh

        meshes = {
            'tp' : Mesh.from_file(data_dir + '/meshes/3d/block.mesh'),
            'si' : Mesh.from_file(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
예제 #43
0
    def test_projection_tri_quad(self):
        from sfepy.discrete.projections import make_l2_projection

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

        coors = self.field.get_coor()
        vals = nm.sin(2.0 * nm.pi * coors[:, 0] * coors[:, 1])
        source.set_data(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 = FEDomain('domain', mesh)

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

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

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

        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
예제 #44
0
    def test_invariance_qp(self):
        from sfepy import data_dir
        from sfepy.discrete import Variables, Integral
        from sfepy.discrete.fem import Mesh, FEDomain, Field
        from sfepy.terms import Term
        from sfepy.discrete.common.mappings import get_physical_qps

        mesh = Mesh.from_file(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 = FEDomain('domain', mesh)
        omega = domain.create_region('Omega', 'all')
        field = Field.from_args('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.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
예제 #45
0
def prepare_variable(filename, n_components):
    from sfepy.discrete import FieldVariable
    from sfepy.discrete.fem import Mesh, FEDomain, Field

    mesh = Mesh.from_file(filename)

    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])

    domain = FEDomain("domain", mesh)
    omega = domain.create_region("Omega", "all")
    field = Field.from_args("field", nm.float64, n_components, omega, approx_order=2)

    u = FieldVariable("u", "parameter", field, primary_var_name="(set-to-None)")
    u.set_from_mesh_vertices(data * nm.arange(1, n_components + 1)[None, :])

    return u
예제 #46
0
def main():
    parser = ArgumentParser(description=__doc__.rstrip(),
                            formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('filename', help=helps['filename'])
    options = parser.parse_args()

    mesh = Mesh.from_file(options.filename)

    output(mesh.cmesh)
    output('element types:', mesh.descs)
    output('nodal BCs:', mesh.nodal_bcs)

    bbox = mesh.get_bounding_box()
    output('bounding box: %s'
           % ', '.join('%s: [%s, %s]' % (name, bbox[0, ii], bbox[1, ii])
                       for ii, name in enumerate('xyz'[:mesh.dim])))

    output('centre:', mesh.coors.mean(0))
예제 #47
0
def main():
    parser = ArgumentParser(description=__doc__.rstrip(),
                            formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('filename', help=helps['filename'])
    options = parser.parse_args()

    mesh = Mesh.from_file(options.filename)

    output(mesh.cmesh)
    output('element types:', mesh.descs)
    output('nodal BCs:', mesh.nodal_bcs)

    bbox = mesh.get_bounding_box()
    output('bounding box: %s'
           % ', '.join('%s: [%s, %s]' % (name, bbox[0, ii], bbox[1, ii])
                       for ii, name in enumerate('xyz'[:mesh.dim])))

    output('centre:', mesh.coors.mean(0))
예제 #48
0
    def test_projection_tri_quad(self):
        from sfepy.discrete.projections import make_l2_projection

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

        coors = self.field.get_coor()
        vals = nm.sin(2.0 * nm.pi * coors[:,0] * coors[:,1])
        source.set_data(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 = FEDomain('domain', mesh)

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


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

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

        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
예제 #49
0
def extendScalarField(tetraMeshPath,
                      meshVTK=None,
                      threshold=None,
                      meshNameType='_withScalarField',
                      recompute=False):
    """
    Given two meshes, one superficial and another tetrahedral, extends all the scalar fields in the superficial mesh to the superficial using Laplace equation (Heat equation)

    TODO: vectorise the sfepy problem for speedup!

    """
    writePath = appendBeforeFileType(tetraMeshPath,
                                     meshNameType).replace('.1', '')
    if recompute or not os.path.exists(writePath):
        mesh = Mesh.from_file(tetraMeshPath)
        #horrible way, but could not write fields on ply files...
        if isinstance(meshVTK, str):
            meshVTK = utilities.read_poly(meshVTK)
        #Poly
        reader = vtk.vtkUnstructuredGridReader()
        reader.SetFileName(tetraMeshPath)
        reader.Update()
        v = reader.GetOutput()

        for i in range(meshVTK.GetPointData().GetNumberOfArrays()):
            heatBoundary = numpy_support.vtk_to_numpy(
                meshVTK.GetPointData().GetArray(i))
            points = utilities.vtk_to_numpy(meshVTK, flatten=False)

            u = solveLaplaceEquationTetrahedral(mesh, meshVTK, points,
                                                heatBoundary)
            array = numpy_support.numpy_to_vtk(u)
            array.SetName(meshVTK.GetPointData().GetArray(i).GetName())
            v.GetPointData().AddArray(array)

        #Write poly
        utilities.writeUnstructuredGridVTK(writePath, v)
    else:
        v = utilities.readUnstructuredGridVTK(writePath)
    #Do the split
    if threshold is not None:
        return writePath, computeVolumes(v, threshold, path=writePath)
    else:
        return writePath
예제 #50
0
    def from_conf(conf, options):
        from sfepy.discrete import Integral
        from sfepy.discrete.fem import Mesh, FEDomain

        domains = []
        for filename in filename_meshes:
            mesh = Mesh.from_file(filename)
            domain = FEDomain('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
예제 #51
0
    def test_spregion2d(self):
        """
        Check position of a given vertex in the deformed mesh.
        """
        line_l = nm.array([[-1, 1], [-1, .5], [-1, 0], [-1, -.5]])
        line_r = nm.array([[0, -.2], [.1, .2], [.3, .6], [.4, 1]])
        sp_l = BSpline(3, is_cyclic=False)
        sp_l.approximate(line_l, ncp=4)
        kn_lr = sp_l.get_knot_vector()
        sp_r = BSpline(3, is_cyclic=False)
        sp_r.approximate(line_r, knots=kn_lr)

        line_b = nm.array([[-1, -.5], [-.8, -.6], [-.5, -.4], [-.2, -.2],
                           [0, -.2]])
        line_t = nm.array([[.4, 1], [0, 1], [-.2, 1], [-.6, 1], [-1, 1]])
        sp_b = BSpline(3, is_cyclic=False)
        sp_b.approximate(line_b, ncp=5)
        kn_bt = sp_b.get_knot_vector()
        sp_t = BSpline(3, is_cyclic=False)
        sp_t.approximate(line_t, knots=kn_bt)

        mesh = Mesh.from_file(data_dir + '/meshes/2d/square_tri1.mesh')
        spb = SplineRegion2D([sp_b, sp_r, sp_t, sp_l], mesh.coors)
        spb.move_control_point(5, [-.2, .1])
        spb.move_control_point(10, [-.3, .2])
        spb.move_control_point(15, [-.1, .2])

        pt0 = mesh.coors[145, :].copy()
        mesh.cmesh.coors[:] = spb.evaluate()
        pt1 = mesh.coors[145, :]

        expected_distance = 0.0908306614584
        actual_distance = nm.linalg.norm(pt0 - pt1)
        ok = nm.fabs(actual_distance - expected_distance)\
            / expected_distance < tolerance

        if not ok:
            self.report('expected distance:')
            self.report(expected_distance)
            self.report('actual distance:')
            self.report(actual_distance)

        return ok
예제 #52
0
    def from_conf( conf, options ):
        from sfepy import data_dir
        from sfepy.discrete.fem import Mesh, FEDomain
        from sfepy.discrete import Functions

        mesh = Mesh.from_file(data_dir
                              + '/meshes/various_formats/abaqus_tet.inp')
        mesh.nodal_bcs['set0'] = [0, 7]
        domain = FEDomain('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
예제 #53
0
파일: sinbc.py 프로젝트: qilicun/sfepy
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
예제 #54
0
    def test_spregion2d(self):
        """
        Check position of a given vertex in the deformed mesh.
        """
        line_l = nm.array([[-1, 1], [-1, .5], [-1, 0], [-1, -.5]])
        line_r = nm.array([[0, -.2], [.1, .2], [.3, .6], [.4, 1]])
        sp_l = BSpline(3, is_cyclic=False)
        sp_l.approximate(line_l, ncp=4)
        kn_lr = sp_l.get_knot_vector()
        sp_r = BSpline(3, is_cyclic=False)
        sp_r.approximate(line_r, knots=kn_lr)

        line_b = nm.array([[-1, -.5], [-.8, -.6], [-.5, -.4], [-.2, -.2],
                           [0, -.2]])
        line_t = nm.array([[.4, 1], [0, 1], [-.2, 1], [-.6, 1], [-1, 1]])
        sp_b = BSpline(3, is_cyclic=False)
        sp_b.approximate(line_b, ncp=5)
        kn_bt = sp_b.get_knot_vector()
        sp_t = BSpline(3, is_cyclic=False)
        sp_t.approximate(line_t, knots=kn_bt)

        mesh = Mesh.from_file(data_dir + '/meshes/2d/square_tri1.mesh')
        spb = SplineRegion2D([sp_b, sp_r, sp_t, sp_l], mesh.coors)
        spb.move_control_point(5, [-.2, .1])
        spb.move_control_point(10, [-.3, .2])
        spb.move_control_point(15, [-.1, .2])

        pt0 = mesh.coors[145,:].copy()
        mesh.cmesh.coors[:] = spb.evaluate()
        pt1 = mesh.coors[145,:]

        expected_distance = 0.0908306614584
        actual_distance = nm.linalg.norm(pt0 - pt1)
        ok = nm.fabs(actual_distance - expected_distance)\
            / expected_distance < tolerance

        if not ok:
            self.report('expected distance:')
            self.report(expected_distance)
            self.report('actual distance:')
            self.report(actual_distance)

        return ok
예제 #55
0
    def test_spbox_field(self):
        """
        'Field' vs. 'coors'.
        """
        mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh')
        coors = mesh.coors.copy()
        bbox = nm.vstack((nm.amin(coors, 0), nm.amax(coors, 0))).T

        coors_1 = coors.copy()

        alpha = coors[:, 0]
        spbox = SplineBox(bbox, coors, nsg=[1, 2], field=alpha)
        dv1 = spbox.evaluate_derivative(6, 1)
        spbox.move_control_point(6, -0.2)
        c1 = spbox.evaluate()
        coors_1[:, 0] = c1[:, 0]

        alpha = coors[:, 1]
        spbox = SplineBox(bbox, coors, nsg=[1, 2], field=alpha)
        dv2 = spbox.evaluate_derivative(6, 1)
        spbox.move_control_point(6, 0.2)
        c2 = spbox.evaluate()
        coors_1[:, 1] = c2[:, 0]

        spbox = SplineBox(bbox, coors, nsg=[1, 2])
        dv = spbox.evaluate_derivative(6, [1, 1])
        spbox.move_control_point(6, [-0.2, 0.2])
        coors_2 = spbox.evaluate()

        rel_coor_dist = nm.linalg.norm(coors_2 - coors_1)\
            / nm.linalg.norm(coors_2)
        ok = rel_coor_dist < tolerance
        rel_dvel_dist = nm.linalg.norm(dv - nm.hstack([dv1, dv2]))\
            / nm.linalg.norm(dv)
        ok = ok and rel_dvel_dist < tolerance

        if not ok:
            self.report('modified coordinates do not match, relative error:')
            self.report(rel_coor_dist)
            self.report('derivatives do not match, relative error:')
            self.report(rel_dvel_dist)

        return ok
예제 #56
0
파일: sinbc.py 프로젝트: zitkat/sfepy
def mesh_hook(mesh, mode):
    """
    Load and refine a mesh here.
    """
    if mode == 'read':
        mesh = Mesh.from_file(base_mesh)
        domain = FEDomain(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