How to use the meshio._exceptions.WriteError function in meshio

To help you get started, we’ve selected a few meshio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nschloe / meshio / meshio / dolfin / _dolfin.py View on Github external
def _numpy_type_to_dolfin_type(dtype):
    types = {
        "int": [numpy.int8, numpy.int16, numpy.int32, numpy.int64],
        "uint": [numpy.uint8, numpy.uint16, numpy.uint32, numpy.uint64],
        "float": [numpy.float16, numpy.float32, numpy.float64],
    }
    for key, numpy_types in types.items():
        for numpy_type in numpy_types:
            if numpy.issubdtype(dtype, numpy_type):
                return key

    raise WriteError("Could not convert NumPy data type to DOLFIN data type.")
    return None
github nschloe / meshio / meshio / off / _off.py View on Github external
def write(filename, mesh):
    if mesh.points.shape[1] == 2:
        logging.warning(
            "OFF requires 3D points, but 2D points given. "
            "Appending 0 third component."
        )
        mesh.points = numpy.column_stack(
            [mesh.points[:, 0], mesh.points[:, 1], numpy.zeros(mesh.points.shape[0])]
        )

    if not any(c.type == "triangle" for c in mesh.cells):
        raise WriteError("Can only deal with triangular faces")

    tri = numpy.concatenate([c.data for c in mesh.cells if c.type == "triangle"])

    with open_file(filename, "wb") as fh:
        fh.write(b"OFF\n")
        fh.write(b"# Created by meshio\n\n")

        # counts
        c = "{} {} {}\n\n".format(mesh.points.shape[0], tri.shape[0], 0)
        fh.write(c.encode("utf-8"))

        # vertices
        # numpy.savetxt(fh, mesh.points, "%r")  # slower
        out = mesh.points
        fmt = " ".join(["{}"] * out.shape[1])
        out = "\n".join([fmt.format(*row) for row in out]) + "\n"
github nschloe / meshio / meshio / xdmf / main.py View on Github external
s = BytesIO()
            fmt = dtype_to_format_string[data.dtype.name]
            numpy.savetxt(s, data, fmt)
            return "\n" + s.getvalue().decode()
        elif self.data_format == "Binary":
            bin_filename = "{}{}.bin".format(
                os.path.splitext(self.filename)[0], self.data_counter
            )
            self.data_counter += 1
            # write binary data to file
            with open(bin_filename, "wb") as f:
                data.tofile(f)
            return bin_filename

        if self.data_format != "HDF":
            raise WriteError('Unknown data format "{}"'.format(self.data_format))
        name = "data{}".format(self.data_counter)
        self.data_counter += 1
        self.h5_file.create_dataset(
            name,
            data=data,
            compression=self.compression,
            compression_opts=self.compression_opts,
        )
        return os.path.basename(self.h5_filename) + ":/" + name
github nschloe / meshio / meshio / gmsh / _gmsh40.py View on Github external
if binary:
        total_num_cells = sum([data.shape[0] for _, data in cells])
        numpy.array([len(cells), total_num_cells], dtype=c_ulong).tofile(fh)

        consecutive_index = 0
        for cell_type, node_idcs in cells:
            # tagEntity(int) dimEntity(int) typeEle(int) numElements(unsigned long)
            numpy.array(
                [1, _geometric_dimension[cell_type], _meshio_to_gmsh_type[cell_type]],
                dtype=c_int,
            ).tofile(fh)
            numpy.array([node_idcs.shape[0]], dtype=c_ulong).tofile(fh)

            if node_idcs.dtype != c_int:
                raise WriteError()
            data = numpy.column_stack(
                [
                    numpy.arange(
                        consecutive_index,
                        consecutive_index + len(node_idcs),
                        dtype=c_int,
                    ),
                    # increment indices by one to conform with gmsh standard
                    node_idcs + 1,
                ]
            )
            data.tofile(fh)
            consecutive_index += len(node_idcs)

        fh.write(b"\n")
    else:
github nschloe / meshio / meshio / tetgen / _tetgen.py View on Github external
def write(filename, mesh, float_fmt=".16e"):
    filename = pathlib.Path(filename)
    if filename.suffix == ".node":
        node_filename = filename
        ele_filename = filename.parent / (filename.stem + ".ele")
    elif filename.suffix == ".ele":
        node_filename = filename.parent / (filename.stem + ".node")
        ele_filename = filename
    else:
        raise WriteError("Must specify .node or .ele file. Got {}.".format(filename))

    if mesh.points.shape[1] != 3:
        raise WriteError("Can only write 3D points")

    # write nodes
    # TODO remove .as_posix when requiring Python 3.6
    with open(node_filename.as_posix(), "w") as fh:
        fh.write("# This file was created by meshio v{}\n".format(__version__))
        fh.write("{} {} {} {}\n".format(mesh.points.shape[0], 3, 0, 0))
        fmt = "{} " + " ".join(3 * ["{:" + float_fmt + "}"]) + "\n"
        for k, pt in enumerate(mesh.points):
            fh.write(fmt.format(k, pt[0], pt[1], pt[2]))

    if not any(c.type == "tetra" for c in mesh.cells):
        raise WriteError("TegGen only supports tetrahedra")
github nschloe / meshio / meshio / flac3d / _flac3d.py View on Github external
def write(filename, mesh):
    """
    Write FLAC3D f3grid grid file (only ASCII).
    """
    if not any(cell_type in meshio_only for cell_type in mesh.cells.keys()):
        raise WriteError(
            "FLAC3D format only supports 'tetra', 'pyramid', 'wedge', and 'hexahedron'."
        )

    with open_file(filename, "w") as f:
        f.write("* FLAC3D grid produced by meshio v{}\n".format(version))
        f.write("* {}\n".format(time.ctime()))
        f.write("* GRIDPOINTS\n")
        _write_points(f, mesh.points)
        f.write("* ZONES\n")
        _write_cells(f, mesh.points, mesh.cells)

        if mesh.cell_data:
            if set(kk for v in mesh.cell_data.values() for kk in v.keys()).intersection(
                meshio_data
            ):
                f.write("* ZONE GROUPS\n")
github nschloe / meshio / meshio / mdpa / _mdpa.py View on Github external
def _write_elements_and_conditions(fh, cells, tag_data, binary=False, dimension=2):
    if binary:
        raise WriteError()
    # write elements
    entity = "Elements"
    dimension_name = str(dimension) + "D"
    wrong_dimension_name = "3D" if dimension == 2 else "2D"
    consecutive_index = 0
    aux_cell_type = None
    for cell_type, node_idcs in cells:
        # NOTE: The names of the dummy conditions are not regular, require extra work
        # local_dimension = local_dimension_types[cell_type]
        # if (local_dimension < dimension):
        # entity = "Conditions"

        if aux_cell_type is None:
            aux_cell_type = cell_type
            fh.write(
                (
github nschloe / meshio / meshio / svg / _svg.py View on Github external
def write(filename, mesh, float_fmt=".3f", stroke_width="1", force_width=None):
    if mesh.points.shape[1] == 3 and not numpy.allclose(
        mesh.points[:, 2], 0.0, rtol=0.0, atol=1.0e-14
    ):
        raise WriteError(
            "SVG can only handle flat 2D meshes (shape: {})".format(mesh.points.shape)
        )

    pts = mesh.points[:, :2].copy()
    pts[:, 1] = numpy.max(pts[:, 1]) - pts[:, 1]

    min_x = numpy.min(pts[:, 0])
    min_y = numpy.min(pts[:, 1])
    width = numpy.max(pts[:, 0]) - min_x
    height = numpy.max(pts[:, 1]) - min_y

    if force_width is not None:
        scaling_factor = force_width / width
        min_x *= scaling_factor
        min_y *= scaling_factor
        width *= scaling_factor
github nschloe / meshio / meshio / _helpers.py View on Github external
def write(filename, mesh, file_format=None, **kwargs):
    """Writes mesh together with data to a file.

    :params filename: File to write to.
    :type filename: str

    :params point_data: Named additional point data to write to the file.
    :type point_data: dict
    """
    if is_buffer(filename, "r"):
        if file_format is None:
            raise WriteError("File format must be supplied if `filename` is a buffer")
        if file_format == "tetgen":
            raise WriteError(
                "tetgen format is spread across multiple files, and so cannot be written to a buffer"
            )
    else:
        path = pathlib.Path(filename)
        if not file_format:
            # deduce file format from extension
            file_format = _filetype_from_path(path)

    try:
        writer = _writer_map[file_format]
    except KeyError:
        raise KeyError(
            "Unknown format '{}'. Pick one of {}".format(
                file_format, sorted(list(_writer_map.keys()))