Skip to content

ivscc

Extract features from a apical dendrite.

Source code in navis/morpho/ivscc.py
259
260
261
262
263
264
265
266
267
268
269
class ApicalDendriteFeatures(CompartmentFeatures):
    """Extract features from a apical dendrite."""

    def __init__(self, neuron: "core.TreeNeuron", verbose=False):
        super().__init__(neuron, "apical_dendrite", verbose=verbose)

    def extract_features(self):
        # Extract basic features via the parent class
        super().extract_features()

        return self.features

Extract features from an axon.

Source code in navis/morpho/ivscc.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
class AxonFeatures(CompartmentFeatures):
    """Extract features from an axon."""

    def __init__(self, neuron: "core.TreeNeuron", verbose=False):
        super().__init__(neuron, "axon", verbose=verbose)

    def extract_features(self):
        # Extract basic features via the parent class
        super().extract_features()

        # Now deal witha axon-specific features:

        if self.soma is not None:
            # Distance between axon root and soma surface
            # Note: we're catering for potentially multiple roots here
            axon_root_pos = self.neuron.nodes.loc[
                self.neuron.nodes.type == "root", ["x", "y", "z"]
            ].values

            # Closest dist between an axon root and the soma
            dist = np.linalg.norm(axon_root_pos - self.soma_pos, axis=1).min()

            # Subtract soma radius from the distance
            dist -= self.soma_radius

            self.record_feature("exit_distance", dist)

            # Axon theta: The relative radial position of the point where the neurite from which
            # the axon derives exits the soma.

            # Get the node where the axon exits the soma
            exit_node = self.neuron.nodes.loc[self.neuron.nodes.type == "root"]

            # Get theta
            theta = np.arctan2(
                exit_node.y.values - self.soma_pos[1],
                exit_node.x.values - self.soma_pos[0],
            )[0]
            self.record_feature("exit_theta", theta)

        return self.features

Extract features from a basal dendrite.

Source code in navis/morpho/ivscc.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
class BasalDendriteFeatures(CompartmentFeatures):
    """Extract features from a basal dendrite."""

    def __init__(self, neuron: "core.TreeNeuron", verbose=False):
        super().__init__(neuron, "basal_dendrite", verbose=verbose)

    def extract_features(self):
        # Extract basic features via the parent class
        super().extract_features()

        # Now deal with basal dendrite-specific features
        if self.soma is not None:
            # Number of stems sprouting from the soma
            # (i.e. number of nodes with a parent that is the soma)
            self.record_feature(
                "calculate_number_of_stems",
                (self.neuron.nodes.parent_id == self.soma).sum(),
            )

        return self.features

Base class for features.

Source code in navis/morpho/ivscc.py
 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
120
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
class BasicFeatures(Features):
    """Base class for features."""

    def extract_features(self):
        """Extract basic features."""
        self.record_feature(
            "extent_y", self.neuron.nodes.y.max() - self.neuron.nodes.y.min()
        )
        self.record_feature(
            "extent_x", self.neuron.nodes.x.max() - self.neuron.nodes.x.min()
        )
        self.record_feature(
            "max_branch_order", (self.neuron.nodes.type == "branch").sum() + 1
        )
        self.record_feature("num_nodes", len(self.neuron.nodes))
        self.record_feature("total_length", self.neuron.cable_length)

        if self.soma is None:
            if self.verbose:
                logger.warning(
                    f"{self.neuron.id} has no `.soma` attribute, skipping soma-related features."
                )
            return

        # x/y bias from soma
        # Note: this is absolute for x and relative for y
        self.record_feature(
            "bias_x",
            abs(
                (self.neuron.nodes.x.max() - self.soma_pos[0])
                - (self.soma_pos[0] - self.neuron.nodes.x.min())
            ),
        )
        self.record_feature(
            "bias_y",
            (self.neuron.nodes.y.max() - self.soma_pos[1])
            - (self.soma_pos[1] - self.neuron.nodes.y.min()),
        )

        # Distances from soma
        self.record_feature(
            "max_euclidean_distance",
            (
                (self.neuron.nodes[["x", "y", "z"]] - self.soma_pos)
                .pow(2)
                .sum(axis=1)
                .pow(0.5)
                .sum()
                .max()
            ),
        )
        self.record_feature(
            "max_path_length",
            self.leaf_dists.loc[
                self.leaf_dists.index.isin(self.neuron.nodes.node_id)
            ].values.max(),
        )

        # Tortuosity
        self.record_feature("mean_contraction", tortuosity(self.neuron))

        # Branching (number of linear segments between branch)
        self.record_feature("num_branches", len(self.neuron.small_segments))

        return self.features

Extract basic features.

Source code in navis/morpho/ivscc.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
def extract_features(self):
    """Extract basic features."""
    self.record_feature(
        "extent_y", self.neuron.nodes.y.max() - self.neuron.nodes.y.min()
    )
    self.record_feature(
        "extent_x", self.neuron.nodes.x.max() - self.neuron.nodes.x.min()
    )
    self.record_feature(
        "max_branch_order", (self.neuron.nodes.type == "branch").sum() + 1
    )
    self.record_feature("num_nodes", len(self.neuron.nodes))
    self.record_feature("total_length", self.neuron.cable_length)

    if self.soma is None:
        if self.verbose:
            logger.warning(
                f"{self.neuron.id} has no `.soma` attribute, skipping soma-related features."
            )
        return

    # x/y bias from soma
    # Note: this is absolute for x and relative for y
    self.record_feature(
        "bias_x",
        abs(
            (self.neuron.nodes.x.max() - self.soma_pos[0])
            - (self.soma_pos[0] - self.neuron.nodes.x.min())
        ),
    )
    self.record_feature(
        "bias_y",
        (self.neuron.nodes.y.max() - self.soma_pos[1])
        - (self.soma_pos[1] - self.neuron.nodes.y.min()),
    )

    # Distances from soma
    self.record_feature(
        "max_euclidean_distance",
        (
            (self.neuron.nodes[["x", "y", "z"]] - self.soma_pos)
            .pow(2)
            .sum(axis=1)
            .pow(0.5)
            .sum()
            .max()
        ),
    )
    self.record_feature(
        "max_path_length",
        self.leaf_dists.loc[
            self.leaf_dists.index.isin(self.neuron.nodes.node_id)
        ].values.max(),
    )

    # Tortuosity
    self.record_feature("mean_contraction", tortuosity(self.neuron))

    # Branching (number of linear segments between branch)
    self.record_feature("num_branches", len(self.neuron.small_segments))

    return self.features

Base class for compartment-specific features.

Source code in navis/morpho/ivscc.py
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
class CompartmentFeatures(BasicFeatures):
    """Base class for compartment-specific features."""

    def __init__(self, neuron: "core.TreeNeuron", compartment, verbose=False):
        if "label" not in neuron.nodes.columns:
            raise ValueError(
                f"No 'label' column found in node table for neuron {neuron.id}"
            )

        if (
            compartment not in neuron.nodes.label.values
            and comp_to_label.get(compartment, compartment)
            not in neuron.nodes.label.values
        ):
            raise CompartmentNotFoundError(
                f"No {compartment} ({comp_to_label.get(compartment, compartment)}) compartments found in neuron {neuron.id}"
            )

        # Initialize the parent class
        super().__init__(neuron, label=compartment, verbose=verbose)

        # Now subset the neuron to this compartment
        self.neuron = subset_neuron(
            self.neuron,
            (
                self.neuron.nodes.label.isin(
                    (compartment, comp_to_label[compartment])
                ).values
            ),
        )

An exception raised when a compartment is not found.

Source code in navis/morpho/ivscc.py
47
48
49
50
class CompartmentNotFoundError(Exception):
    """An exception raised when a compartment is not found."""

    pass
Source code in navis/morpho/ivscc.py
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
class Features(ABC):
    def __init__(self, neuron: "core.TreeNeuron", label=None, verbose=False):
        self.neuron = neuron
        self.verbose = verbose

        if label is None:
            self.label = ""
        elif not label.endswith("_"):
            self.label = f"{label}_"
        else:
            self.label = label

        # Make sure the neuron is rooted to the soma (if present)
        self.soma = self.neuron.soma
        if self.soma is not None:
            self.soma_pos = self.neuron.soma_pos[0]
            self.soma_radius = self.neuron.nodes.set_index("node_id").loc[
                self.soma, "radius"
            ]

            if self.neuron.soma not in self.neuron.root:
                self.neuron = self.neuron.reroot(self.neuron.soma)

            # Calculate geodesic distances from leafs to all other nodes (directed)
            self.leaf_dists = graph.geodesic_matrix(
                self.neuron, self.neuron.leafs.node_id.values, directed=True
            )
            # Replace infinities with -1
            self.leaf_dists[self.leaf_dists == float("inf")] = -1

        self.features = {}

    def record_feature(self, name, value):
        """Record a feature."""
        self.features[f"{self.label}{name}"] = value

    @abstractmethod
    def extract_features(self):
        """Extract features."""
        pass

Extract features.

Source code in navis/morpho/ivscc.py
89
90
91
92
@abstractmethod
def extract_features(self):
    """Extract features."""
    pass

Record a feature.

Source code in navis/morpho/ivscc.py
85
86
87
def record_feature(self, name, value):
    """Record a feature."""
    self.features[f"{self.label}{name}"] = value

Features that compare two compartments (e.g. overlap).

Source code in navis/morpho/ivscc.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
class OverlapFeatures(Features):
    """Features that compare two compartments (e.g. overlap)."""

    # Compartments to compare
    compartments = ("axon", "basal_dendrite", "apical_dendrite")

    def extract_features(self):
        # Iterate over compartments
        for c1 in self.compartments:
            if c1 in self.neuron.nodes.label.values:
                c1_nodes = self.neuron.nodes[self.neuron.nodes.label == c1]
            elif comp_to_label.get(c1, c1) in self.neuron.nodes.label.values:
                c1_nodes = self.neuron.nodes[
                    self.neuron.nodes.label == comp_to_label[c1]
                ]
            else:
                continue
            for c2 in self.compartments:
                if c1 == c2:
                    continue
                if c2 in self.neuron.nodes.label.values:
                    c2_nodes = self.neuron.nodes[self.neuron.nodes.label == c2]
                elif comp_to_label.get(c2, c2) in self.neuron.nodes.label.values:
                    c2_nodes = self.neuron.nodes[
                        self.neuron.nodes.label == comp_to_label[c2]
                    ]
                else:
                    continue

                # Calculate % of nodes of a given compartment type above/overlapping/below the
                # full y-extent of another compartment type
                self.features[f"{c1}_frac_above_{c2}"] = (
                    c1_nodes.y > c2_nodes.y.max()
                ).sum() / len(c1_nodes)
                self.features[f"{c1}_frac_intersect_{c2}"] = (
                    (c1_nodes.y >= c2_nodes.y.min()) & (c1_nodes.y <= c2_nodes.y.max())
                ).sum() / len(c1_nodes)
                self.features[f"{c1}_frac_below_{c2}"] = (
                    c1_nodes.y < c2_nodes.y.min()
                ).sum() / len(c1_nodes)

                # Calculate earth mover's distance (EMD) between the two compartments
                if f"{c2}_emd_with_{c1}" not in self.features:
                    self.features[f"{c1}_emd_with_{c2}"] = wasserstein_distance(
                        c1_nodes.y, c2_nodes.y
                    )

        return self.features