Skip to content

mesh_io

Source code in navis/io/mesh_io.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
class MeshReader(base.BaseReader):
    def __init__(
        self,
        output: str,
        fmt: str = DEFAULT_FMT,
        attrs: Optional[Dict[str, Any]] = None,
        errors: str = "raise",
    ):
        super().__init__(
            fmt=fmt,
            attrs=attrs,
            file_ext=MESH_LOAD_EXT,
            name_fallback="MESH",
            read_binary=True,
            errors=errors,
        )
        self.output = output

    def format_output(self, x):
        # This function replaces the BaseReader.format_output()
        # This is to avoid trying to convert multiple (image, header) to NeuronList
        if self.output == "trimesh":
            return x
        elif x:
            return core.NeuronList(x)
        else:
            return core.NeuronList([])

    @base.handle_errors
    def read_buffer(
        self, f, attrs: Optional[Dict[str, Any]] = None
    ) -> Union[tm.Trimesh, "core.Volume", "core.MeshNeuron"]:
        """Read buffer into mesh.

        Parameters
        ----------
        f :         IO
                    Readable buffer (must be bytes).
        attrs :     dict | None
                    Arbitrary attributes to include in the neurons.

        Returns
        -------
        Trimesh | MeshNeuron | Volume

        """
        if isinstance(f, HTTPResponse):
            f = io.StringIO(f.content)

        if isinstance(f, bytes):
            f = io.BytesIO(f)

        # We need to tell trimesh what file type we are reading
        if "file" not in attrs:
            raise KeyError(
                f'Unable to parse file type. "file" not in attributes: {attrs}'
            )

        file_type = attrs["file"].split(".")[-1]

        mesh = tm.load_mesh(f, file_type=file_type)

        if self.output == "trimesh":
            return mesh
        elif self.output == "volume":
            return core.Volume(mesh.vertices, mesh.faces, **attrs)

        # Turn into a MeshNeuron
        n = core.MeshNeuron(mesh)

        # Try adding properties one-by-one. If one fails, we'll keep track of it
        # in the `.meta` attribute
        meta = {}
        for k, v in attrs.items():
            try:
                n._register_attr(k, v)
            except (AttributeError, ValueError, TypeError):
                meta[k] = v

        if meta:
            n.meta = meta

        return n

Read buffer into mesh.

PARAMETER DESCRIPTION
f
    Readable buffer (must be bytes).

TYPE: IO

attrs
    Arbitrary attributes to include in the neurons.

TYPE: dict | None DEFAULT: None

RETURNS DESCRIPTION
Trimesh | MeshNeuron | Volume
Source code in navis/io/mesh_io.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@base.handle_errors
def read_buffer(
    self, f, attrs: Optional[Dict[str, Any]] = None
) -> Union[tm.Trimesh, "core.Volume", "core.MeshNeuron"]:
    """Read buffer into mesh.

    Parameters
    ----------
    f :         IO
                Readable buffer (must be bytes).
    attrs :     dict | None
                Arbitrary attributes to include in the neurons.

    Returns
    -------
    Trimesh | MeshNeuron | Volume

    """
    if isinstance(f, HTTPResponse):
        f = io.StringIO(f.content)

    if isinstance(f, bytes):
        f = io.BytesIO(f)

    # We need to tell trimesh what file type we are reading
    if "file" not in attrs:
        raise KeyError(
            f'Unable to parse file type. "file" not in attributes: {attrs}'
        )

    file_type = attrs["file"].split(".")[-1]

    mesh = tm.load_mesh(f, file_type=file_type)

    if self.output == "trimesh":
        return mesh
    elif self.output == "volume":
        return core.Volume(mesh.vertices, mesh.faces, **attrs)

    # Turn into a MeshNeuron
    n = core.MeshNeuron(mesh)

    # Try adding properties one-by-one. If one fails, we'll keep track of it
    # in the `.meta` attribute
    meta = {}
    for k, v in attrs.items():
        try:
            n._register_attr(k, v)
        except (AttributeError, ValueError, TypeError):
            meta[k] = v

    if meta:
        n.meta = meta

    return n