Skip to content

precomputed_io

Source code in navis/io/precomputed_io.py
 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
class PrecomputedMeshReader(PrecomputedReader):
    def __init__(
        self,
        fmt: str = DEFAULT_FMT,
        attrs: Optional[Dict[str, Any]] = None,
        errors: str = "raise",
    ):
        super().__init__(
            fmt=fmt,
            attrs=attrs,
            file_ext="",
            name_fallback="mesh",
            read_binary=True,
            errors=errors,
        )

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

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

        Returns
        -------
        core.MeshNeuron
        """
        if not isinstance(f.read(0), bytes):
            raise ValueError(f"Expected bytes, got {type(f.read(0))}")

        num_vertices = np.frombuffer(f.read(4), np.uint32)[0]
        vertices = np.frombuffer(f.read(int(3 * 4 * num_vertices)), np.float32).reshape(
            -1, 3
        )
        faces = np.frombuffer(f.read(), np.uint32).reshape(-1, 3)

        return core.MeshNeuron(
            {"vertices": vertices, "faces": faces},
            **(
                self._make_attributes(
                    {"name": self.name_fallback, "origin": "DataFrame"}, attrs
                )
            ),
        )

Read buffer into a MeshNeuron.

PARAMETER DESCRIPTION
f
    Readable buffer - must be bytes.

TYPE: IO

attrs
    Arbitrary attributes to include in the MeshNeuron.

TYPE: dict | None DEFAULT: None

RETURNS DESCRIPTION
core.MeshNeuron
Source code in navis/io/precomputed_io.py
 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
@base.handle_errors
def read_buffer(
    self, f: IO, attrs: Optional[Dict[str, Any]] = None
) -> "core.MeshNeuron":
    """Read buffer into a MeshNeuron.

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

    Returns
    -------
    core.MeshNeuron
    """
    if not isinstance(f.read(0), bytes):
        raise ValueError(f"Expected bytes, got {type(f.read(0))}")

    num_vertices = np.frombuffer(f.read(4), np.uint32)[0]
    vertices = np.frombuffer(f.read(int(3 * 4 * num_vertices)), np.float32).reshape(
        -1, 3
    )
    faces = np.frombuffer(f.read(), np.uint32).reshape(-1, 3)

    return core.MeshNeuron(
        {"vertices": vertices, "faces": faces},
        **(
            self._make_attributes(
                {"name": self.name_fallback, "origin": "DataFrame"}, attrs
            )
        ),
    )
Source code in navis/io/precomputed_io.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class PrecomputedReader(base.BaseReader):
    def is_valid_file(self, file):
        """Return True if file should be considered for reading."""
        if isinstance(file, zipfile.ZipInfo):
            file = str(file.filename)
        elif isinstance(file, Path):
            if not file.is_file():
                return False
            file = str(file.name)
        else:
            file = str(file)

        # Drop anything with a file extension or hidden files (e.g. ".DS_store")
        if "." in file:
            return False
        # Ignore the info file
        if file == "info":
            return False
        # Ignore manifests
        if file.endswith(":0"):
            return False
        return True

Return True if file should be considered for reading.

Source code in navis/io/precomputed_io.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def is_valid_file(self, file):
    """Return True if file should be considered for reading."""
    if isinstance(file, zipfile.ZipInfo):
        file = str(file.filename)
    elif isinstance(file, Path):
        if not file.is_file():
            return False
        file = str(file.name)
    else:
        file = str(file)

    # Drop anything with a file extension or hidden files (e.g. ".DS_store")
    if "." in file:
        return False
    # Ignore the info file
    if file == "info":
        return False
    # Ignore manifests
    if file.endswith(":0"):
        return False
    return True
Source code in navis/io/precomputed_io.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
class PrecomputedSkeletonReader(PrecomputedReader):
    def __init__(
        self,
        fmt: str = DEFAULT_FMT,
        attrs: Optional[Dict[str, Any]] = None,
        info: Dict[str, Any] = {},
        errors: str = "raise",
    ):
        super().__init__(
            fmt=fmt,
            attrs=attrs,
            file_ext="",
            name_fallback="skeleton",
            read_binary=True,
            errors=errors,
        )
        self.info = info

    @base.handle_errors
    def read_buffer(
        self, f: IO, attrs: Optional[Dict[str, Any]] = None
    ) -> "core.TreeNeuron":
        """Read buffer into a TreeNeuron.

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

        Returns
        -------
        core.TreeNeuron

        """
        if not isinstance(f.read(0), bytes):
            raise ValueError(f"Expected bytes, got {type(f.read(0))}")

        num_nodes = np.frombuffer(f.read(4), np.uint32)[0]
        num_edges = np.frombuffer(f.read(4), np.uint32)[0]
        nodes = np.frombuffer(f.read(int(3 * 4 * num_nodes)), np.float32).reshape(-1, 3)
        edges = np.frombuffer(f.read(int(2 * 4 * num_edges)), np.uint32).reshape(-1, 2)

        swc = self.make_swc(nodes, edges)

        # Check for malformed vertex attributes (should be list of dicts)
        if isinstance(self.info.get("vertex_attributes", None), dict):
            self.info["vertex_attributes"] = [self.info["vertex_attributes"]]

        # Parse additional vertex attributes if specified as per the info file
        for attr in self.info.get("vertex_attributes", []):
            dtype = np.dtype(attr["data_type"])
            n_comp = attr["num_components"]
            values = np.frombuffer(
                f.read(int(n_comp * dtype.itemsize * num_nodes)), dtype
            ).reshape(-1, n_comp)
            if n_comp == 1:
                swc[attr["id"]] = values.flatten()
            else:
                for i in range(n_comp):
                    swc[f"{attr['id']}_{i}"] = values[:, i]

        return core.TreeNeuron(
            swc,
            **(
                self._make_attributes(
                    {"name": self.name_fallback, "origin": "DataFrame"}, attrs
                )
            ),
        )

    def make_swc(self, nodes: np.ndarray, edges: np.ndarray) -> pd.DataFrame:
        """Make SWC table from nodes and edges.

        Parameters
        ----------
        nodes :     (N, 3) array
        edges :     (N, 2) array

        Returns
        -------
        pandas.DataFrame
        """
        swc = pd.DataFrame()
        swc["node_id"] = np.arange(len(nodes))
        swc["x"], swc["y"], swc["z"] = nodes[:, 0], nodes[:, 1], nodes[:, 2]

        edge_dict = dict(zip(edges[:, 1], edges[:, 0]))
        swc["parent_id"] = swc.node_id.map(lambda x: edge_dict.get(x, -1)).astype(
            np.int32
        )

        return swc

Make SWC table from nodes and edges.

PARAMETER DESCRIPTION
nodes

TYPE: (N, 3) array

edges

TYPE: (N, 2) array

RETURNS DESCRIPTION
pandas.DataFrame
Source code in navis/io/precomputed_io.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def make_swc(self, nodes: np.ndarray, edges: np.ndarray) -> pd.DataFrame:
    """Make SWC table from nodes and edges.

    Parameters
    ----------
    nodes :     (N, 3) array
    edges :     (N, 2) array

    Returns
    -------
    pandas.DataFrame
    """
    swc = pd.DataFrame()
    swc["node_id"] = np.arange(len(nodes))
    swc["x"], swc["y"], swc["z"] = nodes[:, 0], nodes[:, 1], nodes[:, 2]

    edge_dict = dict(zip(edges[:, 1], edges[:, 0]))
    swc["parent_id"] = swc.node_id.map(lambda x: edge_dict.get(x, -1)).astype(
        np.int32
    )

    return swc

Read buffer into a TreeNeuron.

PARAMETER DESCRIPTION
f
    Readable buffer - must be bytes.

TYPE: IO

attrs
    Arbitrary attributes to include in the TreeNeuron.

TYPE: dict | None DEFAULT: None

RETURNS DESCRIPTION
core.TreeNeuron
Source code in navis/io/precomputed_io.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
@base.handle_errors
def read_buffer(
    self, f: IO, attrs: Optional[Dict[str, Any]] = None
) -> "core.TreeNeuron":
    """Read buffer into a TreeNeuron.

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

    Returns
    -------
    core.TreeNeuron

    """
    if not isinstance(f.read(0), bytes):
        raise ValueError(f"Expected bytes, got {type(f.read(0))}")

    num_nodes = np.frombuffer(f.read(4), np.uint32)[0]
    num_edges = np.frombuffer(f.read(4), np.uint32)[0]
    nodes = np.frombuffer(f.read(int(3 * 4 * num_nodes)), np.float32).reshape(-1, 3)
    edges = np.frombuffer(f.read(int(2 * 4 * num_edges)), np.uint32).reshape(-1, 2)

    swc = self.make_swc(nodes, edges)

    # Check for malformed vertex attributes (should be list of dicts)
    if isinstance(self.info.get("vertex_attributes", None), dict):
        self.info["vertex_attributes"] = [self.info["vertex_attributes"]]

    # Parse additional vertex attributes if specified as per the info file
    for attr in self.info.get("vertex_attributes", []):
        dtype = np.dtype(attr["data_type"])
        n_comp = attr["num_components"]
        values = np.frombuffer(
            f.read(int(n_comp * dtype.itemsize * num_nodes)), dtype
        ).reshape(-1, n_comp)
        if n_comp == 1:
            swc[attr["id"]] = values.flatten()
        else:
            for i in range(n_comp):
                swc[f"{attr['id']}_{i}"] = values[:, i]

    return core.TreeNeuron(
        swc,
        **(
            self._make_attributes(
                {"name": self.name_fallback, "origin": "DataFrame"}, attrs
            )
        ),
    )

Writer class that also takes care of info files.

Source code in navis/io/precomputed_io.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
class PrecomputedWriter(base.Writer):
    """Writer class that also takes care of `info` files."""

    def write_any(self, x, filepath, write_info=True, **kwargs):
        """Write any to file. Default entry point."""
        # First write the actual neurons
        kwargs["write_info"] = False
        super().write_any(x, filepath=filepath, **kwargs)

        # Write info file to the correct directory/zipfile
        if write_info:
            add_props = {}
            if kwargs.get("radius", False):
                add_props["vertex_attributes"] = [
                    {"id": "radius", "data_type": "float32", "num_components": 1}
                ]

            if str(self.path).endswith(".zip"):
                with ZipFile(self.path, mode="a") as zf:
                    # Context-manager will remove temporary directory and its contents
                    with tempfile.TemporaryDirectory() as tempdir:
                        # Write info to zip
                        if write_info:
                            # Generate temporary filename
                            f = os.path.join(tempdir, "info")
                            write_info_file(x, f, add_props=add_props)
                            # Add file to zip
                            zf.write(f, arcname="info", compress_type=compression)
            else:
                fp = self.path
                # Find the first existing root directory
                while not fp.is_dir():
                    fp = fp.parent

                write_info_file(x, fp, add_props=add_props)

Write any to file. Default entry point.

Source code in navis/io/precomputed_io.py
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
def write_any(self, x, filepath, write_info=True, **kwargs):
    """Write any to file. Default entry point."""
    # First write the actual neurons
    kwargs["write_info"] = False
    super().write_any(x, filepath=filepath, **kwargs)

    # Write info file to the correct directory/zipfile
    if write_info:
        add_props = {}
        if kwargs.get("radius", False):
            add_props["vertex_attributes"] = [
                {"id": "radius", "data_type": "float32", "num_components": 1}
            ]

        if str(self.path).endswith(".zip"):
            with ZipFile(self.path, mode="a") as zf:
                # Context-manager will remove temporary directory and its contents
                with tempfile.TemporaryDirectory() as tempdir:
                    # Write info to zip
                    if write_info:
                        # Generate temporary filename
                        f = os.path.join(tempdir, "info")
                        write_info_file(x, f, add_props=add_props)
                        # Add file to zip
                        zf.write(f, arcname="info", compress_type=compression)
        else:
            fp = self.path
            # Find the first existing root directory
            while not fp.is_dir():
                fp = fp.parent

            write_info_file(x, fp, add_props=add_props)

Write neuroglancer 'info' file for given neurons.

PARAMETER DESCRIPTION
data

TYPE: navis.NeuronList | navis.Volumes | trimesh

filepath
       Path to write the file to.

TYPE: str | Path

add_props
       Additional properties to write to the file.

TYPE: dict DEFAULT: {}

Source code in navis/io/precomputed_io.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
def write_info_file(data, filepath, add_props={}):
    """Write neuroglancer 'info' file for given neurons.

    Parameters
    ----------
    data :         navis.NeuronList | navis.Volumes | trimesh
    filepath :     str | Path
                   Path to write the file to.
    add_props :    dict
                   Additional properties to write to the file.

    """
    info = {}
    if utils.is_iterable(data):
        types = list(set([type(d) for d in data]))
        if len(types) > 1:
            raise ValueError(
                "Unable to write info file for mixed data: " f"{data.types}"
            )
        data = data[0]

    if utils.is_mesh(data):
        info["@type"] = "neuroglancer_legacy_mesh"
    elif isinstance(data, core.TreeNeuron):
        info["@type"] = "neuroglancer_skeletons"

        # If we know the units add transform from "stored model"
        # to "model space" which is supposed to be nm
        if not data.units.dimensionless:
            u = data.units.to("1 nm").magnitude
        else:
            u = 1
        tr = np.zeros((4, 3), dtype=int)
        tr[:3, :3] = np.diag([u, u, u])
        info["transform"] = tr.T.flatten().tolist()

    else:
        raise TypeError(f'Unable to write info file for data of type "{type(data)}"')

    info.update(add_props)
    if not str(filepath).endswith("/info"):
        filepath = os.path.join(filepath, "info")
    with open(filepath, "w") as f:
        json.dump(info, f)