Exemplo n.º 1
0
    def __call__(self, evt, basename, overwrite=True):
        if not self.visualize:
            return

        if self.dim == 1:
            u = self.actx.to_numpy(flatten(evt.state_component))

            filename = "%s.png" % basename
            if not overwrite and os.path.exists(filename):
                from meshmode import FileExistsError
                raise FileExistsError("output file '%s' already exists" %
                                      filename)

            ax = self.fig.gca()
            ax.plot(self.x, u, "-")
            ax.plot(self.x, u, "k.")
            if self.ylim is not None:
                ax.set_ylim(self.ylim)

            ax.set_xlabel("$x$")
            ax.set_ylabel("$u$")
            ax.set_title(f"t = {evt.t:.2f}")

            self.fig.savefig(filename)
            self.fig.clf()
        else:
            self.vis.write_vtk_file("%s.vtu" % basename,
                                    [("u", evt.state_component)],
                                    overwrite=overwrite)
Exemplo n.º 2
0
    def __call__(self, evt, basename, overwrite=True):
        if not self.visualize:
            return

        if self.ambient_dim == 2:
            u = self.actx.to_numpy(flatten(evt.state_component))

            filename = "%s.png" % basename
            if not overwrite and os.path.exists(filename):
                from meshmode import FileExistsError
                raise FileExistsError("output file '%s' already exists" %
                                      filename)

            ax = self.fig.gca()
            ax.grid()
            ax.plot(self.x, u, "-")
            ax.plot(self.x, u, "k.")
            ax.set_xlabel(r"$\theta$")
            ax.set_ylabel("$u$")
            ax.set_title(f"t = {evt.t:.2f}")

            self.fig.savefig(filename)
            self.fig.clf()
        elif self.ambient_dim == 3:
            self.vis.write_vtk_file("%s.vtu" % basename,
                                    [("u", evt.state_component)],
                                    overwrite=overwrite)
        else:
            raise ValueError("unsupported dimension")
Exemplo n.º 3
0
    def __call__(self, evt, basename, overwrite=True):
        if not self.visualize:
            return

        if self.dim == 1:
            u = evt.state_component.get(self.queue)

            filename = "%s.png" % basename
            if not overwrite and os.path.exists(filename):
                from meshmode import FileExistsError
                raise FileExistsError("output file '%s' already exists" %
                                      filename)

            ax = self.fig.gca()
            ax.plot(self.x[0], u, '-')
            ax.plot(self.x[0], u, 'k.')
            if self.ylim is not None:
                ax.set_ylim(self.ylim)

            ax.set_xlabel("$x$")
            ax.set_ylabel("$u$")
            ax.set_title("t = {:.2f}".format(evt.t))

            self.fig.savefig(filename)
            self.fig.clf()
        else:
            self.vis.write_vtk_file("%s.vtu" % basename,
                                    [("u", evt.state_component)],
                                    overwrite=overwrite)
Exemplo n.º 4
0
def write_vertex_vtk_file(mesh, file_name, compressor=None, overwrite=False):
    from pyvisfile.vtk import (UnstructuredGrid, DataArray,
                               AppendedDataXMLGenerator, VF_LIST_OF_COMPONENTS)

    # {{{ create cell_types

    from pyvisfile.vtk import (VTK_LINE, VTK_TRIANGLE, VTK_TETRA, VTK_QUAD,
                               VTK_HEXAHEDRON)

    from meshmode.mesh import TensorProductElementGroup, SimplexElementGroup

    cell_types = np.empty(mesh.nelements, dtype=np.uint8)
    cell_types.fill(255)
    for egrp in mesh.groups:
        if isinstance(egrp, SimplexElementGroup):
            vtk_cell_type = {
                1: VTK_LINE,
                2: VTK_TRIANGLE,
                3: VTK_TETRA,
            }[egrp.dim]
        elif isinstance(egrp, TensorProductElementGroup):
            vtk_cell_type = {
                1: VTK_LINE,
                2: VTK_QUAD,
                3: VTK_HEXAHEDRON,
            }[egrp.dim]
        else:
            raise NotImplementedError("mesh vtk file writing for "
                                      "element group of type '%s'" %
                                      type(egrp).__name__)

        cell_types[
                egrp.element_nr_base:
                egrp.element_nr_base + egrp.nelements] = \
                        vtk_cell_type

    assert (cell_types != 255).all()

    # }}}

    grid = UnstructuredGrid(
        (mesh.nvertices,
         DataArray(
             "points", mesh.vertices, vector_format=VF_LIST_OF_COMPONENTS)),
        cells=np.hstack(
            [vgrp.vertex_indices.reshape(-1) for vgrp in mesh.groups]),
        cell_types=cell_types)

    import os
    from meshmode import FileExistsError
    if os.path.exists(file_name):
        if overwrite:
            os.remove(file_name)
        else:
            raise FileExistsError("output file '%s' already exists" %
                                  file_name)

    with open(file_name, "w") as outf:
        AppendedDataXMLGenerator(compressor)(grid).write(outf)
Exemplo n.º 5
0
def write_nodal_adjacency_vtk_file(file_name, mesh,
                                   compressor=None,
                                   overwrite=False):
    from pyvisfile.vtk import (
            UnstructuredGrid, DataArray,
            AppendedDataXMLGenerator,
            VTK_LINE,
            VF_LIST_OF_COMPONENTS)

    centroids = np.empty(
            (mesh.ambient_dim, mesh.nelements),
            dtype=mesh.vertices.dtype)

    for grp in mesh.groups:
        iel_base = grp.element_nr_base
        centroids[:, iel_base:iel_base+grp.nelements] = (
                np.sum(mesh.vertices[:, grp.vertex_indices], axis=-1)
                / grp.vertex_indices.shape[-1])

    adj = mesh.nodal_adjacency

    nconnections = len(adj.neighbors)
    connections = np.empty((nconnections, 2), dtype=np.int32)

    nb_starts = adj.neighbors_starts
    for iel in range(mesh.nelements):
        connections[nb_starts[iel]:nb_starts[iel+1], 0] = iel

    connections[:, 1] = adj.neighbors

    grid = UnstructuredGrid(
            (mesh.nelements,
                DataArray("points",
                    centroids,
                    vector_format=VF_LIST_OF_COMPONENTS)),
            cells=connections.reshape(-1),
            cell_types=np.asarray([VTK_LINE] * nconnections,
                dtype=np.uint8))

    import os
    from meshmode import FileExistsError
    if os.path.exists(file_name):
        if overwrite:
            os.remove(file_name)
        else:
            raise FileExistsError("output file '%s' already exists" % file_name)

    with open(file_name, "w") as outf:
        AppendedDataXMLGenerator(compressor)(grid).write(outf)
Exemplo n.º 6
0
    def write_vtk_file(self, file_name, names_and_fields,
            compressor=None, real_only=False, overwrite=False,
            use_high_order=None,
            par_manifest_filename=None, par_file_names=None):
        """Write a Vtk XML file (typical extension ``.vtu``) containing
        the visualization data in *names_and_fields*. Can optionally also write
        manifests for distributed memory simulation (typical extension
        ``.pvtu``). See also :meth:`write_parallel_vtk_file` for a convenience
        wrapper.

        :arg names_and_fields: A list of tuples ``(name, value)``, where
            *name* is a string and *value* is a
            :class:`~meshmode.dof_array.DOFArray` or a constant,
            or an object array of those.
        :arg overwrite: If *True*, silently overwrite existing
            files.
        :arg use_high_order: Writes arbitrary order Lagrange VTK elements.
            These elements are described in
            `this blog post <https://blog.kitware.com/modeling-arbitrary-order-lagrange-finite-elements-in-the-visualization-toolkit/>`__
            and are available in VTK 8.1 and newer.
        :arg par_manifest_filename: If not *None* write a distributed-memory
            manifest with this file name if *file_name* matches the first entry in
            *par_file_names*.
        :arg par_file_names: A list of file names of visualization files to
            include in the distributed-memory manifest.

        .. versionchanged:: 2020.2

            - Added *par_manifest_filename* and *par_file_names*.
            - Added *use_high_order*.
        """ # noqa

        if use_high_order is None:
            use_high_order = False
        if use_high_order:
            if not self.is_equidistant:
                raise RuntimeError("Cannot visualize high-order Lagrange elements "
                        "using a non-equidistant visualizer. "
                        "Call 'make_visualizer' with 'force_equidistant=True'.")

            connectivity = self._vtk_lagrange_connectivity
        else:
            connectivity = self._vtk_connectivity

        from pyvisfile.vtk import (
                UnstructuredGrid, DataArray,
                AppendedDataXMLGenerator,
                ParallelXMLGenerator,
                VF_LIST_OF_COMPONENTS)

        nodes = self._vis_nodes_numpy()
        names_and_fields = [
                (name, resample_to_numpy(self.connection, fld))
                for name, fld in names_and_fields]

        # {{{ create cell_types

        nsubelements = sum(vgrp.nsubelements for vgrp in connectivity.groups)
        cell_types = np.empty(nsubelements, dtype=np.uint8)
        cell_types.fill(255)

        for vgrp in connectivity.groups:
            isubelements = np.s_[
                    vgrp.subelement_nr_base:
                    vgrp.subelement_nr_base + vgrp.nsubelements]
            cell_types[isubelements] = vgrp.vtk_cell_type

        assert (cell_types < 255).all()

        # }}}

        # {{{ shrink elements

        if abs(self.element_shrink_factor - 1.0) > 1.0e-14:
            node_nr_base = 0
            for vgrp in self.vis_discr.groups:
                nodes_view = (
                        nodes[:, node_nr_base:node_nr_base + vgrp.ndofs]
                        .reshape(nodes.shape[0], vgrp.nelements, vgrp.nunit_dofs))

                el_centers = np.mean(nodes_view, axis=-1)
                nodes_view[:] = (
                        (self.element_shrink_factor * nodes_view)
                        + (1-self.element_shrink_factor)
                        * el_centers[:, :, np.newaxis])

                node_nr_base += vgrp.ndofs

        # }}}

        # {{{ create grid

        nodes = nodes.reshape(self.vis_discr.ambient_dim, -1)
        points = DataArray("points", nodes, vector_format=VF_LIST_OF_COMPONENTS)

        grid = UnstructuredGrid(
                (nodes.shape[1], points),
                cells=connectivity.cells,
                cell_types=cell_types)

        for name, field in separate_by_real_and_imag(names_and_fields, real_only):
            grid.add_pointdata(
                    DataArray(name, field, vector_format=VF_LIST_OF_COMPONENTS)
                    )

        # }}}

        # {{{ write

        import os
        from meshmode import FileExistsError

        # {{{ write either both the vis file and the manifest, or neither

        if os.path.exists(file_name):
            if overwrite:
                # we simply overwrite below, no need to remove
                pass
            else:
                raise FileExistsError("output file '%s' already exists"
                                      % file_name)

        if par_manifest_filename is not None:
            if os.path.exists(par_manifest_filename):
                if overwrite:
                    # we simply overwrite below, no need to remove
                    pass
                else:
                    raise FileExistsError("output file '%s' already exists"
                            % par_manifest_filename)
            else:
                pass

        # }}}

        with open(file_name, "w") as outf:
            generator = AppendedDataXMLGenerator(
                    compressor=compressor,
                    vtk_file_version=connectivity.version)

            generator(grid).write(outf)

        if par_file_names is not None:
            if par_manifest_filename is None:
                raise ValueError("must specify par_manifest_filename if "
                        "par_file_names are given")

            if par_file_names[0] == file_name:
                with open(par_manifest_filename, "w") as outf:
                    generator = ParallelXMLGenerator(par_file_names)
                    generator(grid).write(outf)
Exemplo n.º 7
0
    def write_vtk_file(self,
                       file_name,
                       names_and_fields,
                       compressor=None,
                       real_only=False,
                       overwrite=False):

        from pyvisfile.vtk import (UnstructuredGrid, DataArray,
                                   AppendedDataXMLGenerator,
                                   VF_LIST_OF_COMPONENTS)

        with cl.CommandQueue(self.vis_discr.cl_context) as queue:
            nodes = self.vis_discr.nodes().with_queue(queue).get()

            names_and_fields = [(name, self._resample_and_get(queue, fld))
                                for name, fld in names_and_fields]

        vc_groups = self._vis_connectivity()

        # {{{ create cell_types

        nsubelements = sum(vgrp.nsubelements for vgrp in vc_groups)
        cell_types = np.empty(nsubelements, dtype=np.uint8)
        cell_types.fill(255)
        for vgrp in vc_groups:
            cell_types[
                    vgrp.subelement_nr_base:
                    vgrp.subelement_nr_base + vgrp.nsubelements] = \
                            vgrp.vtk_cell_type
        assert (cell_types < 255).all()

        # }}}

        if self.element_shrink_factor != 1:
            for vgrp in self.vis_discr.groups:
                nodes_view = vgrp.view(nodes)
                el_centers = np.mean(nodes_view, axis=-1)
                nodes_view[:] = ((self.element_shrink_factor * nodes_view) +
                                 (1 - self.element_shrink_factor) *
                                 el_centers[:, :, np.newaxis])

        grid = UnstructuredGrid(
            (self.vis_discr.nnodes,
             DataArray("points",
                       nodes.reshape(self.vis_discr.ambient_dim, -1),
                       vector_format=VF_LIST_OF_COMPONENTS)),
            cells=np.hstack(
                [vgrp.vis_connectivity.reshape(-1) for vgrp in vc_groups]),
            cell_types=cell_types)

        # for name, field in separate_by_real_and_imag(cell_data, real_only):
        #     grid.add_celldata(DataArray(name, field,
        #         vector_format=VF_LIST_OF_COMPONENTS))

        for name, field in separate_by_real_and_imag(names_and_fields,
                                                     real_only):
            grid.add_pointdata(
                DataArray(name, field, vector_format=VF_LIST_OF_COMPONENTS))

        import os
        from meshmode import FileExistsError
        if os.path.exists(file_name):
            if overwrite:
                os.remove(file_name)
            else:
                raise FileExistsError("output file '%s' already exists" %
                                      file_name)

        with open(file_name, "w") as outf:
            AppendedDataXMLGenerator(compressor)(grid).write(outf)