Skip to content

rda_io

Convert nat dotprops to navis Dotprops.

Source code in navis/io/rda_io.py
144
145
146
147
148
149
150
151
152
153
154
def dotprops_constructor(obj: Any,
                         attrs: Mapping[Union[str, bytes], Any],
                         ) -> 'core.Dotprops':
    """Convert nat dotprops to navis Dotprops."""
    pts = np.asarray(obj.pop('points'))
    vect = np.asarray(obj.pop('vect'))
    alpha = np.asarray(obj.pop('alpha'))
    k = int(attrs.get('k', 1)[0])
    file = attrs.get('file', [None])[0]

    return core.Dotprops(points=pts, k=k, alpha=alpha, vect=vect, file=file)

Convert nat neuron/catmaidneuron to navis TreeNeuron.

Source code in navis/io/rda_io.py
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
215
216
217
218
219
220
221
222
def neuron_constructor(obj: Any,
                       attrs: Mapping[Union[str, bytes], Any],
                       ) -> 'core.TreeNeuron':
    """Convert nat neuron/catmaidneuron to navis TreeNeuron."""
    # Data to skip
    DO_NOT_USE = ['nTrees', 'SegList', 'NumPoints', 'StartPoint', 'EndPoints',
                  'BranchPoints', 'NumSegs']

    # Construct neuron from just the nodes
    n = core.TreeNeuron(obj.pop('d'))

    # R uses diameter, not radius - let's fix that
    if 'radius' in n.nodes.columns:
        has_rad = n.nodes.radius.fillna(0) > 0
        n.nodes.loc[has_rad, 'radius'] = n.nodes.loc[has_rad, 'radius'] / 2

    # If this is a CATMAID neuron, we assume it's in nanometers
    if 'catmaidneuron' in attrs.get('class', []):
        n.units = 'nm'

    # Reuse ID
    if 'skid' in obj:
        skid = obj.pop('skid')
        if utils.is_iterable(skid):
            n.id = skid[0]
        else:
            n.id = skid

    # Try attaching other data
    for k, v in obj.items():
        if k in DO_NOT_USE:
            continue
        try:
            setattr(n, k, v)
        except BaseException:
            pass

    return n

Convert nat neuronlists to navis NeuronLists.

Source code in navis/io/rda_io.py
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
def neuronlist_constructor(obj: Any,
                           attrs: Mapping[Union[str, bytes], Any],
                           ) -> 'core.NeuronList':
    """Convert nat neuronlists to navis NeuronLists."""
    # Set IDs
    neurons = []
    for k, n in obj.items():
        if isinstance(n, (core.BaseNeuron, core.NeuronList)):
            n.id = k
            neurons.append(n)
        else:
            logger.warning(f'Unexpected object in neuronlist: {type(n)}. '
                           'Possible parsing error.')

    # Turn into NeuronList
    nl = core.NeuronList(neurons)

    # Now parse extra attributes DataFrame
    df = attrs.get('df', None)
    if isinstance(df, pd.DataFrame):
        # Make sure we have still the correct order
        nl = nl.idx[attrs['names']]

        for col in df:
            # Skip non-string columns
            if not isinstance(col, str):
                continue

            # Skip some columns
            if col.lower() in ['type', 'idx']:
                continue
            if col.lower() in nl[0].__dict__.keys():
                continue

            for n, v in zip(nl, df[col].values):
                # Register
                n._register_attr(col.lower(), v)

    return nl

Convert e.g. mesh3d to navis Volume.

Source code in navis/io/rda_io.py
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
def volume_constructor(obj: Any,
                       attrs: Mapping[Union[str, bytes], Any],
                       ) -> 'core.Volume':
    """Convert e.g. mesh3d to navis Volume."""
    if 'vb' in obj and 'it' in obj:
        verts = np.asarray(obj.pop('vb'))[:3, :].T
        faces = np.asarray(obj.pop('it')).T - 1
        return core.Volume(vertices=verts, faces=faces)
    elif 'Vertices' in obj and "Regions" in obj:
        verts = obj['Vertices'][['X', 'Y', 'Z']].values

        # If only one region
        if len(obj['Regions']) == 1:
            region = list(obj['Regions'].keys())[0]
            faces = obj['Regions'][region][['V1', 'V2', 'V3']].values - 1
            return core.Volume(vertices=verts, faces=faces)
        else:
            volumes = []
            for r in obj['Regions']:
                faces = obj['Regions'][r][['V1', 'V2', 'V3']].values - 1
                volumes.append(core.Volume(vertices=verts, faces=faces, name=r))
            return volumes
    else:
        logger.warning('Unable to construct Volume from R object of type '
                       f'"{attrs["class"]}". Returning raw data')
        return obj