How to use the meshio._exceptions.ReadError 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 / stl / _stl.py View on Github external
# )

    # numpy.loadtxt is super slow
    # data = numpy.loadtxt(
    #     f,
    #     comments=["solid", "facet", "outer loop", "endloop", "endfacet", "endsolid"],
    #     usecols=(1, 2, 3),
    # )
    data = iter_loadtxt(
        f,
        comments=("solid", "outer loop", "endloop", "endfacet", "endsolid"),
        # usecols=(1, 2, 3),
    )

    if data.shape[0] % 4 != 0:
        raise ReadError()

    # split off the facet normals
    facet_rows = numpy.zeros(len(data), dtype=bool)
    facet_rows[0::4] = True
    facet_normals = data[facet_rows]
    data = data[~facet_rows]

    facets = numpy.split(data, data.shape[0] // 3)
    points, cells = data_from_facets(facets)
    return Mesh(points, cells, cell_data={"facet_normals": [facet_normals]})
github nschloe / meshio / meshio / vtk / _vtk.py View on Github external
dtype = numpy.dtype(vtk_to_numpy_dtype_name[data_type])
    lt, _ = f.readline().decode("utf-8").split()
    if lt.upper() != "LOOKUP_TABLE":
        raise ReadError()

    if is_ascii:
        data = numpy.fromfile(f, count=num_data, sep=" ", dtype=dtype)
    else:
        # Binary data is big endian, see
        # .
        dtype = dtype.newbyteorder(">")
        data = numpy.fromfile(f, count=num_data, dtype=dtype)
        line = f.readline().decode("utf-8")
        if line != "\n":
            raise ReadError()

    return {data_name: data}
github nschloe / meshio / meshio / xdmf / main.py View on Github external
precision = data_item.attrib["Precision"]
        except KeyError:
            precision = "4"

        if data_item.get("Format") == "XML":
            return numpy.fromstring(
                data_item.text,
                dtype=xdmf_to_numpy_type[(data_type, precision)],
                sep=" ",
            ).reshape(dims)
        elif data_item.get("Format") == "Binary":
            return numpy.fromfile(
                data_item.text.strip(), dtype=xdmf_to_numpy_type[(data_type, precision)]
            ).reshape(dims)
        elif data_item.get("Format") != "HDF":
            raise ReadError("Unknown XDMF Format '{}'.".format(data_item.get("Format")))

        info = data_item.text.strip()
        filename, h5path = info.split(":")

        # The HDF5 file path is given with respect to the XDMF (XML) file.
        full_hdf5_path = os.path.join(os.path.dirname(self.filename), filename)

        f = h5py.File(full_hdf5_path, "r")

        # Some files don't contain the leading slash /.
        if h5path[0] == "/":
            h5path = h5path[1:]

        for key in h5path.split("/"):
            f = f[key]
        # `[()]` gives a numpy.ndarray
github nschloe / meshio / meshio / abaqus / _abaqus.py View on Github external
'instance' : 'dummy2,
        'generate' : None,
    }
    """
    if required_keys is None:
        required_keys = []
    words = word.split(",")
    param_map = {}
    for wordi in words:
        if "=" not in wordi:
            key = wordi.strip().upper()
            value = None
        else:
            sword = wordi.split("=")
            if len(sword) != 2:
                raise ReadError(sword)
            key = sword[0].strip().upper()
            value = sword[1].strip()
        param_map[key] = value

    msg = ""
    for key in required_keys:
        if key not in param_map:
            msg += "{} not found in {}\n".format(key, word)
    if msg:
        raise RuntimeError(msg)
    return param_map
github nschloe / meshio / meshio / ansys / _ansys.py View on Github external
# be the current line already).
    last_char = line.strip()[-1]
    while last_char != "(":
        last_char = f.read(1).decode("utf-8")

    if out.group(1) == "":
        # ASCII data
        pts = numpy.empty((num_points, dim))
        for k in range(num_points):
            # skip ahead to the first line with data
            line = ""
            while line.strip() == "":
                line = f.readline().decode("utf-8")
            dat = line.split()
            if len(dat) != dim:
                raise ReadError()
            for d in range(dim):
                pts[k][d] = float(dat[d])
    else:
        # binary data
        if out.group(1) == "20":
            dtype = numpy.float32
        else:
            if out.group(1) != "30":
                ReadError("Expected keys '20' or '30', got {}.".format(out.group(1)))
            dtype = numpy.float64
        # read point data
        pts = numpy.fromfile(f, count=dim * num_points, dtype=dtype).reshape(
            (num_points, dim)
        )

    # make sure that the data set is properly closed
github nschloe / meshio / meshio / vtk / _vtk.py View on Github external
def _read_scalar_field(f, num_data, split, is_ascii):
    data_name = split[1]
    data_type = split[2].lower()
    try:
        num_comp = int(split[3])
    except IndexError:
        num_comp = 1

    # The standard says:
    # > The parameter numComp must range between (1,4) inclusive; [...]
    if not (0 < num_comp < 5):
        raise ReadError("The parameter numComp must range between (1,4) inclusive")

    dtype = numpy.dtype(vtk_to_numpy_dtype_name[data_type])
    lt, _ = f.readline().decode("utf-8").split()
    if lt.upper() != "LOOKUP_TABLE":
        raise ReadError()

    if is_ascii:
        data = numpy.fromfile(f, count=num_data, sep=" ", dtype=dtype)
    else:
        # Binary data is big endian, see
        # .
        dtype = dtype.newbyteorder(">")
        data = numpy.fromfile(f, count=num_data, dtype=dtype)
        line = f.readline().decode("utf-8")
        if line != "\n":
            raise ReadError()
github nschloe / meshio / meshio / vtk / _vtk.py View on Github external
if len(cells) > 0 and cells[-1].type == cell_type:
                cells[-1].data.append(cell)
            else:
                cells.append(CellBlock(cell_type, [cell]))

        # convert data to numpy arrays
        for k, c in enumerate(cells):
            cells[k] = CellBlock(c.type, numpy.array(c.data))
    else:
        # Deduct offsets from the cell types. This is much faster than manually going
        # through the data array. Slight disadvantage: This doesn't work for cells with
        # a custom number of points.
        numnodes = vtk_type_to_numnodes[types]
        if not numpy.all(numnodes > 0):
            raise ReadError("File contains cells that meshio cannot handle.")
        offsets = numpy.cumsum(numnodes + 1) - (numnodes + 1)

        if not numpy.all(numnodes == data[offsets]):
            raise ReadError()

        b = numpy.concatenate(
            [[0], numpy.where(types[:-1] != types[1:])[0] + 1, [len(types)]]
        )
        for start, end in zip(b[:-1], b[1:]):
            meshio_type = vtk_to_meshio_type[types[start]]
            n = data[offsets[start]]
            cell_idx = 1 + _vtk_to_meshio_order(types[start], n, dtype=offsets.dtype)
            indices = numpy.add.outer(offsets[start:end], cell_idx)
            cells.append(CellBlock(meshio_type, data[indices]))
            for name, d in cell_data_raw.items():
                if name not in cell_data:
github nschloe / meshio / meshio / gmsh / _gmsh41.py View on Github external
dtype=type(num_ele),
            )
        tpe = _gmsh_to_meshio_type[type_ele]
        num_nodes_per_ele = num_nodes_per_cell[tpe]
        d = fromfile(f, c_size_t, int(num_ele * (1 + num_nodes_per_ele))).reshape(
            (num_ele, -1)
        )
        if physical_tags is None:
            data.append((None, tpe, d))
        else:
            data.append((physical_tags[dim_entity][tag_entity], tpe, d))

    if not is_ascii:
        line = f.readline().decode("utf-8")
        if line != "\n":
            raise ReadError()
    line = f.readline().decode("utf-8")
    if line.strip() != "$EndElements":
        raise ReadError()

    # Inverse point tags
    inv_tags = numpy.full(numpy.max(point_tags) + 1, -1, dtype=int)
    inv_tags[point_tags] = numpy.arange(len(point_tags))

    # Note that the first column in the data array is the element tag; discard it.
    data = [
        (physical_tag, tpe, inv_tags[d[:, 1:] - 1]) for physical_tag, tpe, d in data
    ]

    cells = []
    for physical_tag, key, values in data:
        cells.append((key, values))
github nschloe / meshio / meshio / exodus / _exodus.py View on Github external
found_z = True
            if found_z:
                double.append((name[:-2], ir, iz))
                is_accounted_for[ir] = True
                is_accounted_for[iz] = True
            else:
                single.append((name, ir))
                is_accounted_for[ir] = True
        else:
            single.append((name, k))
            is_accounted_for[k] = True

        k += 1

    if not all(is_accounted_for):
        raise ReadError()
    return single, double, triple
github nschloe / meshio / meshio / dolfin / _dolfin.py View on Github external
# TODO remove .as_posix when requiring Python 3.6
    for f in os.listdir(dir_name.as_posix()):
        # Check if there are files by the name "_*.xml"; if yes,
        # extract the * pattern and make it the name of the data set.
        out = re.match("{}_([^\\.]+)\\.xml".format(basename), f)
        if not out:
            continue
        name = out.group(1)

        parser = ET.XMLParser()
        tree = ET.parse((dir_name / f).as_posix(), parser)
        root = tree.getroot()

        mesh_functions = list(root)
        if len(mesh_functions) != 1:
            raise ReadError("Can only handle one mesh function")
        mesh_function = mesh_functions[0]

        if mesh_function.tag != "mesh_function":
            raise ReadError()
        size = int(mesh_function.attrib["size"])
        dtype = dolfin_type_to_numpy_type[mesh_function.attrib["type"]]
        data = numpy.empty(size, dtype=dtype)
        for child in mesh_function:
            if child.tag != "entity":
                raise ReadError()
            idx = int(child.attrib["index"])
            data[idx] = child.attrib["value"]

        if name not in cell_data:
            cell_data[name] = []
        cell_data[name].append(data)