Skip to content

Modelling

This page describes functions contained in the modelling module used to model or parametrize the connectivity of connectomes

conn_prob_2nd_order_model(adj, node_properties, **kwargs)

Wrapper function for 2nd-order probability model building to be used within a processing pipeline, optionally for multiple random subsets of neurons.

Parameters:

Name Type Description Default
adj sparse

Sparse (symmetric) adjacency matrix of the circuit

required
node_properties DataFrame

Data frame with neuron properties

required
kwargs dict

Additional model building settings; see Notes for details

{}

Returns:

Type Description
DataFrame

Data frame with model paramters (columns) for different seeds (rows) (No plotting and data/model/figures saving supported)

Raises:

Type Description
AssertionError

If the adjacency matrix is not a square matrix matching the length of the neuron properties table

AssertionError

If invalid arguments given in kwargs which are internally used by this wrapper (like model_order, ...)

AssertionError

If model fitting error occurs

AssertionError

If sample_seeds provided as scalar but is not a positive integer

KeyError

If name(s) of coordinates not in columns of neuron properties table

Warning

If sample_seeds provided as list with duplicates

Warning

If sample_seeds provided but ignored because subsampling not applicable

Notes

The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

The 2nd-order model as defined in [1]_ describes connection probabilities as a function of distance between pre- and post-synaptic neurons. Specifically, we use here an exponential distance-dependent model of the form: $$ p(d) = \mbox{scale} * exp(-\mbox{exponent} * d) $$ with d as distance in \(\mu m\), and the model parameters scale defining the connection probability at distance zero, and exponent the exponent of distance-dependent decay in \(\mu m^{-1}\).

kwargs may contain following (optional) settings:

  • bin_size_um Bin size in um for depth binning (optional; default: 100)
  • max_range_um Max. distance range in um to consider (optional; default: full distance range)
  • sample_size Size of random subset of neurons to consider (optional; default: no subsampling)
  • sample_seeds Integer number of seeds to randomly generate, or list of specific random seeds, for reproducible selection of random subset of neurons (optional)
  • meta_seed Meta seed for generating N random seeds, if integer number N of sample_seeds is provided (optional; default: 0)
  • coord_names Names of the coordinates (columns in neuron properties table) based on which to compute Euclidean distance (optional; default: ["x", "y", "z"])
  • N_split Number of data splits (> 1) to sequentially extract data from, to reduce memory consumption (optional; default: no splitting)
See Also

conn_prob_2nd_order_pathway_model : 2nd-order model building function wrapper for different source/target node populations conn_prob_model : Underlying generic model building function wrapper

References

.. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

Source code in src/connalysis/modelling/modelling.py
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
def conn_prob_2nd_order_model(adj, node_properties, **kwargs):
    """Wrapper function for 2nd-order probability model building to be used within a processing pipeline, optionally for multiple random subsets of neurons.

    Parameters
    ----------
    adj : scipy.sparse
        Sparse (symmetric) adjacency matrix of the circuit
    node_properties : pandas.DataFrame
        Data frame with neuron properties
    kwargs : dict, optional
        Additional model building settings; see Notes for details

    Returns
    -------
    pandas.DataFrame
        Data frame with model paramters (columns) for different seeds (rows)
        (No plotting and data/model/figures saving supported)

    Raises
    ------
    AssertionError
        If the adjacency matrix is not a square matrix matching the length of the neuron properties table
    AssertionError
        If invalid arguments given in kwargs which are internally used by this wrapper (like model_order, ...)
    AssertionError
        If model fitting error occurs
    AssertionError
        If sample_seeds provided as scalar but is not a positive integer
    KeyError
        If name(s) of coordinates not in columns of neuron properties table
    Warning
        If sample_seeds provided as list with duplicates
    Warning
        If sample_seeds provided but ignored because subsampling not applicable

    Notes
    -----
    The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

    The 2nd-order model as defined in [1]_ describes connection probabilities as a function of distance between pre- and post-synaptic neurons. Specifically, we use here an exponential distance-dependent model of the form:
    $$
    p(d) = \mbox{scale} * exp(-\mbox{exponent} * d)
    $$
    with `d` as distance in $\mu m$, and the model parameters `scale` defining the connection probability at distance zero, and `exponent` the exponent of distance-dependent decay in $\mu m^{-1}$.

    `kwargs` may contain following (optional) settings:

    - `bin_size_um` Bin size in um for depth binning (optional; default: 100)
    - `max_range_um` Max. distance range in um to consider (optional; default: full distance range)
    - `sample_size` Size of random subset of neurons to consider (optional; default: no subsampling)
    - `sample_seeds` Integer number of seeds to randomly generate, or list of specific random seeds, for reproducible selection of random subset of neurons (optional)
    - `meta_seed` Meta seed for generating N random seeds, if integer number N of sample_seeds is provided (optional; default: 0)
    - `coord_names` Names of the coordinates (columns in neuron properties table) based on which to compute Euclidean distance (optional; default: ["x", "y", "z"])
    - `N_split` Number of data splits (> 1) to sequentially extract data from, to reduce memory consumption (optional; default: no splitting)

    See Also
    --------
    conn_prob_2nd_order_pathway_model : 2nd-order model building function wrapper for different source/target node populations
    conn_prob_model : Underlying generic model building function wrapper

    References
    ----------
    .. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

    """

    assert 'model_order' not in kwargs.keys(), f'ERROR: Invalid argument "model_order" in kwargs!'

    return conn_prob_model(adj, node_properties, model_order=2, **kwargs)

conn_prob_2nd_order_pathway_model(adj, node_properties_src, node_properties_tgt, **kwargs)

Wrapper function for 2nd-order probability model building to be used within a processing pipeline for pathways with different source and target node populations, optionally for multiple random subsets of neurons.

Parameters:

Name Type Description Default
adj sparse

Sparse adjacency matrix of the circuit (may be non-symmetric)

required
node_properties_src DataFrame

Data frame with source neuron properties (corresponding to the rows in adj)

required
node_properties_tgt DataFrame

Data frame with target neuron properties (corresponding to the columns in adj)

required
kwargs dict

Additional model building settings; see "See Also" for details

{}

Returns:

Type Description
DataFrame

Data frame with model paramters (columns) for different seeds (rows) (No plotting and data/model/figures saving supported)

Raises:

Type Description
AssertionError

If the rows/columns of the adjacency matrix are not matching the lengths of the source/target neuron properties tables

AssertionError

If invalid arguments given in kwargs which are internally used by this wrapper (like model_order, ...)

AssertionError

If model fitting error occurs

AssertionError

If data splitting selected, which is not supported for pathway model building

AssertionError

If sample_seeds provided as scalar but is not a positive integer

KeyError

If name(s) of coordinates not in columns of neuron properties table

Warning

If sample_seeds provided as list with duplicates

Warning

If sample_seeds provided but ignored because subsampling not applicable

Notes

The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

The 2nd-order model as defined in [1]_. See "See Also" for details.

See Also

conn_prob_2nd_order_model : Special case of 2nd-order model building function wrapper for same source/target node population; further details to be found here

References

.. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

Source code in src/connalysis/modelling/modelling.py
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def conn_prob_2nd_order_pathway_model(adj, node_properties_src, node_properties_tgt, **kwargs):
    """Wrapper function for 2nd-order probability model building to be used within a processing pipeline for pathways with different source and target node populations, optionally for multiple random subsets of neurons.

    Parameters
    ----------
    adj : scipy.sparse
        Sparse adjacency matrix of the circuit (may be non-symmetric)
    node_properties_src : pandas.DataFrame
        Data frame with source neuron properties (corresponding to the rows in adj)
    node_properties_tgt : pandas.DataFrame
        Data frame with target neuron properties (corresponding to the columns in adj)
    kwargs : dict, optional
        Additional model building settings; see "See Also" for details

    Returns
    -------
    pandas.DataFrame
        Data frame with model paramters (columns) for different seeds (rows)
        (No plotting and data/model/figures saving supported)

    Raises
    ------
    AssertionError
        If the rows/columns of the adjacency matrix are not matching the lengths of the source/target neuron properties tables
    AssertionError
        If invalid arguments given in kwargs which are internally used by this wrapper (like model_order, ...)
    AssertionError
        If model fitting error occurs
    AssertionError
        If data splitting selected, which is not supported for pathway model building
    AssertionError
        If sample_seeds provided as scalar but is not a positive integer
    KeyError
        If name(s) of coordinates not in columns of neuron properties table
    Warning
        If sample_seeds provided as list with duplicates
    Warning
        If sample_seeds provided but ignored because subsampling not applicable

    Notes
    -----
    The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

    The 2nd-order model as defined in [1]_. See "See Also" for details.

    See Also
    --------
    conn_prob_2nd_order_model : Special case of 2nd-order model building function wrapper for same source/target node population; further details to be found here

    References
    ----------
    .. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

    """

    assert 'model_order' not in kwargs.keys(), f'ERROR: Invalid argument "model_order" in kwargs!'

    return conn_prob_pathway_model(adj, node_properties_src, node_properties_tgt, model_order=2, **kwargs)

conn_prob_3rd_order_model(adj, node_properties, **kwargs)

Wrapper function for 3rd-order probability model building to be used within a processing pipeline, optionally for multiple random subsets of neurons.

Parameters:

Name Type Description Default
adj sparse

Sparse (symmetric) adjacency matrix of the circuit

required
node_properties DataFrame

Data frame with neuron properties

required
kwargs dict

Additional model building settings; see Notes for details

{}

Returns:

Type Description
DataFrame

Data frame with model paramters (columns) for different seeds (rows) (No plotting and data/model/figures saving supported)

Raises:

Type Description
AssertionError

If the adjacency matrix is not a square matrix matching the length of the neuron properties table

AssertionError

If invalid arguments given in kwargs which are internally used by this wrapper (like model_order, ...)

AssertionError

If model fitting error occurs

AssertionError

If sample_seeds provided as scalar but is not a positive integer

KeyError

If name(s) of coordinates not in columns of neuron properties table

Warning

If sample_seeds provided as list with duplicates

Warning

If sample_seeds provided but ignored because subsampling not applicable

Notes

The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

The 3rd-order model as defined in [1]_ describes connection probabilities as a bipolar function of distance between pre- and post-synaptic neurons. Specifically, we use here an bipolar exponential distance-dependent model of the form: $$ p(d, \Delta depth) = \mbox{scale}_N * exp(-\mbox{exponent}_N * d)~\mbox{if}~\Delta depth < 0 $$ $$ p(d, \Delta depth) = \mbox{scale}_P * exp(-\mbox{exponent}_P * d)~\mbox{if}~\Delta depth > 0 $$ $$ p(d, \Delta depth) = \mbox{Average of both}~\mbox{if}~\Delta depth = 0 $$ with d as distance in \(\mu m\), \(\Delta depth\) as difference in depth coordinate (arbitrary unit, as only sign is used; post-synaptic neuron below (\(\Delta depth < 0\)) or above (\(\Delta depth > 0\)) pre-synaptic neuron), and the model parameters scale defining the connection probability at distance zero, and exponent the exponent of distance-dependent decay in \(\mu m^{-1}\) for both cases.

kwargs may contain following (optional) settings:

  • bin_size_um Bin size in um for depth binning (optional; default: 100)
  • max_range_um Max. distance range in um to consider (optional; default: full distance range)
  • sample_size Size of random subset of neurons to consider (optional; default: no subsampling)
  • sample_seeds Integer number of seeds to randomly generate, or list of specific random seeds, for reproducible selection of random subset of neurons (optional)
  • meta_seed Meta seed for generating N random seeds, if integer number N of sample_seeds is provided (optional; default: 0)
  • coord_names Names of the coordinates (columns in neuron properties table) based on which to compute Euclidean distance (optional; default: ["x", "y", "z"])
  • depth_name Name of depth coordinate (column in neuron properties table) to use in 3rd-order (bipolar) model (optional; default: "depth")
  • N_split Number of data splits (> 1) to sequentially extract data from, to reduce memory consumption (optional; default: no splitting)
See Also

conn_prob_3rd_order_pathway_model : 3rd-order model building function wrapper for different source/target node populations conn_prob_model : Underlying generic model building function wrapper

References

.. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

Source code in src/connalysis/modelling/modelling.py
265
266
267
268
269
270
271
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def conn_prob_3rd_order_model(adj, node_properties, **kwargs):
    """Wrapper function for 3rd-order probability model building to be used within a processing pipeline, optionally for multiple random subsets of neurons.

    Parameters
    ----------
    adj : scipy.sparse
        Sparse (symmetric) adjacency matrix of the circuit
    node_properties : pandas.DataFrame
        Data frame with neuron properties
    kwargs : dict, optional
        Additional model building settings; see Notes for details

    Returns
    -------
    pandas.DataFrame
        Data frame with model paramters (columns) for different seeds (rows)
        (No plotting and data/model/figures saving supported)

    Raises
    ------
    AssertionError
        If the adjacency matrix is not a square matrix matching the length of the neuron properties table
    AssertionError
        If invalid arguments given in kwargs which are internally used by this wrapper (like model_order, ...)
    AssertionError
        If model fitting error occurs
    AssertionError
        If sample_seeds provided as scalar but is not a positive integer
    KeyError
        If name(s) of coordinates not in columns of neuron properties table
    Warning
        If sample_seeds provided as list with duplicates
    Warning
        If sample_seeds provided but ignored because subsampling not applicable

    Notes
    -----
    The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

    The 3rd-order model as defined in [1]_ describes connection probabilities as a bipolar function of distance between pre- and post-synaptic neurons. Specifically, we use here an bipolar exponential distance-dependent model of the form:
    $$
    p(d, \Delta depth) = \mbox{scale}_N * exp(-\mbox{exponent}_N * d)~\mbox{if}~\Delta depth < 0
    $$
    $$
    p(d, \Delta depth) = \mbox{scale}_P * exp(-\mbox{exponent}_P * d)~\mbox{if}~\Delta depth > 0
    $$
    $$
    p(d, \Delta depth) = \mbox{Average of both}~\mbox{if}~\Delta depth = 0
    $$
    with `d` as distance in $\mu m$, $\Delta depth$ as difference in depth coordinate (arbitrary unit, as only sign is used; post-synaptic neuron below ($\Delta depth < 0$) or above ($\Delta depth > 0$) pre-synaptic neuron), and the model parameters `scale` defining the connection probability at distance zero, and `exponent` the exponent of distance-dependent decay in $\mu m^{-1}$ for both cases.

    `kwargs` may contain following (optional) settings:

    - `bin_size_um` Bin size in um for depth binning (optional; default: 100)
    - `max_range_um` Max. distance range in um to consider (optional; default: full distance range)
    - `sample_size` Size of random subset of neurons to consider (optional; default: no subsampling)
    - `sample_seeds` Integer number of seeds to randomly generate, or list of specific random seeds, for reproducible selection of random subset of neurons (optional)
    - `meta_seed` Meta seed for generating N random seeds, if integer number N of sample_seeds is provided (optional; default: 0)
    - `coord_names` Names of the coordinates (columns in neuron properties table) based on which to compute Euclidean distance (optional; default: ["x", "y", "z"])
    - `depth_name` Name of depth coordinate (column in neuron properties table) to use in 3rd-order (bipolar) model (optional; default: "depth")
    - `N_split` Number of data splits (> 1) to sequentially extract data from, to reduce memory consumption (optional; default: no splitting)

    See Also
    --------
    conn_prob_3rd_order_pathway_model : 3rd-order model building function wrapper for different source/target node populations
    conn_prob_model : Underlying generic model building function wrapper

    References
    ----------
    .. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

    """

    assert 'model_order' not in kwargs.keys(), f'ERROR: Invalid argument "model_order" in kwargs!'

    return conn_prob_model(adj, node_properties, model_order=3, **kwargs)

conn_prob_3rd_order_pathway_model(adj, node_properties_src, node_properties_tgt, **kwargs)

Wrapper function for 3rd-order probability model building to be used within a processing pipeline for pathways with different source and target node populations, optionally for multiple random subsets of neurons.

Parameters:

Name Type Description Default
adj sparse

Sparse adjacency matrix of the circuit (may be non-symmetric)

required
node_properties_src DataFrame

Data frame with source neuron properties (corresponding to the rows in adj)

required
node_properties_tgt DataFrame

Data frame with target neuron properties (corresponding to the columns in adj)

required
kwargs dict

Additional model building settings; see "See Also" for details

{}

Returns:

Type Description
DataFrame

Data frame with model paramters (columns) for different seeds (rows) (No plotting and data/model/figures saving supported)

Raises:

Type Description
AssertionError

If the rows/columns of the adjacency matrix are not matching the lengths of the source/target neuron properties tables

AssertionError

If invalid arguments given in kwargs which are internally used by this wrapper (like model_order, ...)

AssertionError

If model fitting error occurs

AssertionError

If data splitting selected, which is not supported for pathway model building

AssertionError

If sample_seeds provided as scalar but is not a positive integer

KeyError

If name(s) of coordinates not in columns of neuron properties table

Warning

If sample_seeds provided as list with duplicates

Warning

If sample_seeds provided but ignored because subsampling not applicable

Notes

The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

The 3rd-order model as defined in [1]_. See "See Also" for details.

See Also

conn_prob_3rd_order_model : Special case of 3rd-order model building function wrapper for same source/target node population; further details to be found here

References

.. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

Source code in src/connalysis/modelling/modelling.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def conn_prob_3rd_order_pathway_model(adj, node_properties_src, node_properties_tgt, **kwargs):
    """Wrapper function for 3rd-order probability model building to be used within a processing pipeline for pathways with different source and target node populations, optionally for multiple random subsets of neurons.

    Parameters
    ----------
    adj : scipy.sparse
        Sparse adjacency matrix of the circuit (may be non-symmetric)
    node_properties_src : pandas.DataFrame
        Data frame with source neuron properties (corresponding to the rows in adj)
    node_properties_tgt : pandas.DataFrame
        Data frame with target neuron properties (corresponding to the columns in adj)
    kwargs : dict, optional
        Additional model building settings; see "See Also" for details

    Returns
    -------
    pandas.DataFrame
        Data frame with model paramters (columns) for different seeds (rows)
        (No plotting and data/model/figures saving supported)

    Raises
    ------
    AssertionError
        If the rows/columns of the adjacency matrix are not matching the lengths of the source/target neuron properties tables
    AssertionError
        If invalid arguments given in kwargs which are internally used by this wrapper (like model_order, ...)
    AssertionError
        If model fitting error occurs
    AssertionError
        If data splitting selected, which is not supported for pathway model building
    AssertionError
        If sample_seeds provided as scalar but is not a positive integer
    KeyError
        If name(s) of coordinates not in columns of neuron properties table
    Warning
        If sample_seeds provided as list with duplicates
    Warning
        If sample_seeds provided but ignored because subsampling not applicable

    Notes
    -----
    The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

    The 3rd-order model as defined in [1]_. See "See Also" for details.

    See Also
    --------
    conn_prob_3rd_order_model : Special case of 3rd-order model building function wrapper for same source/target node population; further details to be found here

    References
    ----------
    .. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

    """

    assert 'model_order' not in kwargs.keys(), f'ERROR: Invalid argument "model_order" in kwargs!'

    return conn_prob_pathway_model(adj, node_properties_src, node_properties_tgt, model_order=3, **kwargs)

conn_prob_model(adj, node_properties, **kwargs)

Wrapper function for generic probability model building to be used within a processing pipeline, optionally for multiple random subsets of neurons.

Parameters:

Name Type Description Default
adj sparse

Sparse (symmetric) adjacency matrix of the circuit

required
node_properties DataFrame

Data frame with neuron properties

required
kwargs dict

Additional model building settings; see Notes for details

{}

Returns:

Type Description
DataFrame

Data frame with model paramters (columns) for different seeds (rows) (No plotting and data/model/figures saving supported)

Raises:

Type Description
AssertionError

If the adjacency matrix is not a square matrix matching the length of the neuron properties table

AssertionError

If invalid arguments given in kwargs which are internally used by this wrapper

AssertionError

If model fitting error occurs

AssertionError

If sample_seeds provided as scalar but is not a positive integer

AssertionError

If model order not supported (supported: 2, 3)

KeyError

If model order not provided

KeyError

If name(s) of coordinates not in columns of neuron properties table

Warning

If sample_seeds provided as list with duplicates

Warning

If sample_seeds provided but ignored because subsampling not applicable

Notes

The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

The 2nd-order and 3rd-order models as defined in [1]_ are supported. See "See Also" for details.

kwargs may contain following settings, most of which are optional:

  • model_order Model order (2 or 3)
  • bin_size_um Bin size in um for depth binning (optional; default: 100)
  • max_range_um Max. distance range in um to consider (optional; default: full distance range)
  • sample_size Size of random subset of neurons to consider (optional; default: no subsampling)
  • sample_seeds Integer number of seeds to randomly generate, or list of specific random seeds, for reproducible selection of random subset of neurons (optional)
  • meta_seed Meta seed for generating N random seeds, if integer number N of sample_seeds is provided (optional; default: 0)
  • coord_names Names of the coordinates (columns in neuron properties table) based on which to compute Euclidean distance (optional; default: ["x", "y", "z"])
  • depth_name Name of depth coordinate (column in neuron properties table) to use in 3rd-order (bipolar) model (optional; default: "depth")
  • N_split Number of data splits (> 1) to sequentially extract data from, to reduce memory consumption (optional; default: no splitting)
See Also

conn_prob_2nd_order_model : 2nd-order model building function wrapper for same source/target node population conn_prob_3rd_order_model : 3rd-order model building function wrapper for same source/target node population conn_prob_pathway_model : Generic model building function wrapper for differet source/target node populations

References

.. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

Source code in src/connalysis/modelling/modelling.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
def conn_prob_model(adj, node_properties, **kwargs):
    """Wrapper function for generic probability model building to be used within a processing pipeline, optionally for multiple random subsets of neurons.

    Parameters
    ----------
    adj : scipy.sparse
        Sparse (symmetric) adjacency matrix of the circuit
    node_properties : pandas.DataFrame
        Data frame with neuron properties
    kwargs : dict, optional
        Additional model building settings; see Notes for details

    Returns
    -------
    pandas.DataFrame
        Data frame with model paramters (columns) for different seeds (rows)
        (No plotting and data/model/figures saving supported)

    Raises
    ------
    AssertionError
        If the adjacency matrix is not a square matrix matching the length of the neuron properties table
    AssertionError
        If invalid arguments given in kwargs which are internally used by this wrapper
    AssertionError
        If model fitting error occurs
    AssertionError
        If sample_seeds provided as scalar but is not a positive integer
    AssertionError
        If model order not supported (supported: 2, 3)
    KeyError
        If model order not provided
    KeyError
        If name(s) of coordinates not in columns of neuron properties table
    Warning
        If sample_seeds provided as list with duplicates
    Warning
        If sample_seeds provided but ignored because subsampling not applicable

    Notes
    -----
    The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

    The 2nd-order and 3rd-order models as defined in [1]_ are supported. See "See Also" for details.

    `kwargs` may contain following settings, most of which are optional:

    - `model_order` Model order (2 or 3)
    - `bin_size_um` Bin size in um for depth binning (optional; default: 100)
    - `max_range_um` Max. distance range in um to consider (optional; default: full distance range)
    - `sample_size` Size of random subset of neurons to consider (optional; default: no subsampling)
    - `sample_seeds` Integer number of seeds to randomly generate, or list of specific random seeds, for reproducible selection of random subset of neurons (optional)
    - `meta_seed` Meta seed for generating N random seeds, if integer number N of sample_seeds is provided (optional; default: 0)
    - `coord_names` Names of the coordinates (columns in neuron properties table) based on which to compute Euclidean distance (optional; default: ["x", "y", "z"])
    - `depth_name` Name of depth coordinate (column in neuron properties table) to use in 3rd-order (bipolar) model (optional; default: "depth")
    - `N_split` Number of data splits (> 1) to sequentially extract data from, to reduce memory consumption (optional; default: no splitting)

    See Also
    --------
    conn_prob_2nd_order_model : 2nd-order model building function wrapper for same source/target node population
    conn_prob_3rd_order_model : 3rd-order model building function wrapper for same source/target node population
    conn_prob_pathway_model : Generic model building function wrapper for differet source/target node populations

    References
    ----------
    .. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

    """

    assert adj.shape[0] == adj.shape[1] == node_properties.shape[0], 'ERROR: Data size mismatch!'

    invalid_args = ['model_name', 'sample_seed', 'model_dir', 'data_dir', 'plot_dir', 'do_plot', 'part_idx'] # Not allowed arguments, as they will be set/used internally
    for arg in invalid_args:
        assert arg not in kwargs.keys(), f'ERROR: Invalid argument "{arg}" in kwargs!'
    kwargs.update({'model_dir': None, 'data_dir': None, 'plot_dir': None, 'do_plot': False, 'part_idx': None}) # Disable plotting/saving
    model_name = None
    model_order = kwargs.pop('model_order')

    sample_size = kwargs.get('sample_size')
    if sample_size is None or sample_size <= 0 or sample_size >= node_properties.shape[0]:
        sample_seeds = [None] # No randomization
        if kwargs.pop('sample_seeds', None) is not None:
            logging.warning('Using all neurons, ignoring sample seeds!')
    else:
        sample_seeds = kwargs.pop('sample_seeds', 1)

        if not isinstance(sample_seeds, list): # sample_seeds corresponds to number of seeds to generate
            sample_seeds = _generate_seeds(sample_seeds, meta_seed=kwargs.pop('meta_seed', 0))
        else:
            num_seeds = len(sample_seeds)
            sample_seeds = list(np.unique(sample_seeds)) # Assure that unique and sorted
            if len(sample_seeds) < num_seeds:
                logging.warning(f'Duplicate seeds provided!')

    model_params = pd.DataFrame()
    for seed in sample_seeds:
        kwargs.update({'sample_seed': seed})
        _, model_dict = run_model_building(adj, node_properties, model_name, model_order, **kwargs)
        model_params = pd.concat([model_params, pd.DataFrame(model_dict['model_params'], index=pd.Index([seed], name='seed'))])

    return model_params

conn_prob_pathway_model(adj, node_properties_src, node_properties_tgt, **kwargs)

Wrapper function for generic probability model building to be used within a processing pipeline for pathways with different source and target node populations, optionally for multiple random subsets of neurons.

Parameters:

Name Type Description Default
adj sparse

Sparse adjacency matrix of the circuit (may be non-symmetric)

required
node_properties_src DataFrame

Data frame with source neuron properties (corresponding to the rows in adj)

required
node_properties_tgt DataFrame

Data frame with target neuron properties (corresponding to the columns in adj)

required
kwargs dict

Additional model building settings; see "See Also" for details

{}

Returns:

Type Description
DataFrame

Data frame with model paramters (columns) for different seeds (rows) (No plotting and data/model/figures saving supported)

Raises:

Type Description
AssertionError

If the rows/columns of the adjacency matrix are not matching the lengths of the source/target neuron properties tables

AssertionError

If invalid arguments given in kwargs which are internally used by this wrapper

AssertionError

If model fitting error occurs

AssertionError

If sample_seeds provided as scalar but is not a positive integer

AssertionError

If model order not supported (supported: 2, 3)

AssertionError

If data splitting selected, which is not supported for pathway model building

KeyError

If model order not provided

KeyError

If name(s) of coordinates not in columns of neuron properties table

Warning

If sample_seeds provided as list with duplicates

Warning

If sample_seeds provided but ignored because subsampling not applicable

Notes

The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

The 2nd-order and 3rd-order models as defined in [1]_ are supported. See "See Also" for details.

See Also

conn_prob_model : Special case of generic model building function wrapper for same source/target node population; further details to be found here conn_prob_2nd_order_pathway_model : 2nd-order model building function wrapper for different source/target node population conn_prob_3rd_order_pathway_model : 3rd-order model building function wrapper for different source/target node population

References

.. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

Source code in src/connalysis/modelling/modelling.py
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
def conn_prob_pathway_model(adj, node_properties_src, node_properties_tgt, **kwargs):
    """Wrapper function for generic probability model building to be used within a processing pipeline for pathways with different source and target node populations, optionally for multiple random subsets of neurons.

    Parameters
    ----------
    adj : scipy.sparse
        Sparse adjacency matrix of the circuit (may be non-symmetric)
    node_properties_src : pandas.DataFrame
        Data frame with source neuron properties (corresponding to the rows in adj)
    node_properties_tgt : pandas.DataFrame
        Data frame with target neuron properties (corresponding to the columns in adj)
    kwargs : dict, optional
        Additional model building settings; see "See Also" for details

    Returns
    -------
    pandas.DataFrame
        Data frame with model paramters (columns) for different seeds (rows)
        (No plotting and data/model/figures saving supported)

    Raises
    ------
    AssertionError
        If the rows/columns of the adjacency matrix are not matching the lengths of the source/target neuron properties tables
    AssertionError
        If invalid arguments given in kwargs which are internally used by this wrapper
    AssertionError
        If model fitting error occurs
    AssertionError
        If sample_seeds provided as scalar but is not a positive integer
    AssertionError
        If model order not supported (supported: 2, 3)
    AssertionError
        If data splitting selected, which is not supported for pathway model building
    KeyError
        If model order not provided
    KeyError
        If name(s) of coordinates not in columns of neuron properties table
    Warning
        If sample_seeds provided as list with duplicates
    Warning
        If sample_seeds provided but ignored because subsampling not applicable

    Notes
    -----
    The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

    The 2nd-order and 3rd-order models as defined in [1]_ are supported. See "See Also" for details.

    See Also
    --------
    conn_prob_model : Special case of generic model building function wrapper for same source/target node population; further details to be found here
    conn_prob_2nd_order_pathway_model : 2nd-order model building function wrapper for different source/target node population
    conn_prob_3rd_order_pathway_model : 3rd-order model building function wrapper for different source/target node population

    References
    ----------
    .. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

    """

    assert adj.shape[0] == node_properties_src.shape[0] and adj.shape[1] == node_properties_tgt.shape[0], 'ERROR: Data size mismatch!'

    invalid_args = ['model_name', 'sample_seed', 'model_dir', 'data_dir', 'plot_dir', 'do_plot', 'part_idx'] # Not allowed arguments, as they will be set/used internally
    for arg in invalid_args:
        assert arg not in kwargs.keys(), f'ERROR: Invalid argument "{arg}" in kwargs!'
    kwargs.update({'model_dir': None, 'data_dir': None, 'plot_dir': None, 'do_plot': False, 'part_idx': None}) # Disable plotting/saving
    model_name = None
    model_order = kwargs.pop('model_order')

    sample_size = kwargs.get('sample_size')
    if sample_size is None  or sample_size <= 0 or sample_size >= np.maximum(node_properties_src.shape[0], node_properties_tgt.shape[0]):
        sample_seeds = [None] # No randomization
        if kwargs.pop('sample_seeds', None) is not None:
            logging.warning('Using all neurons, ignoring sample seeds!')
    else:
        sample_seeds = kwargs.pop('sample_seeds', 1)

        if not isinstance(sample_seeds, list): # sample_seeds corresponds to number of seeds to generate
            sample_seeds = _generate_seeds(sample_seeds, meta_seed=kwargs.pop('meta_seed', 0))
        else:
            num_seeds = len(sample_seeds)
            sample_seeds = list(np.unique(sample_seeds)) # Assure that unique and sorted
            if len(sample_seeds) < num_seeds:
                logging.warning(f'Duplicate seeds provided!')

    model_params = pd.DataFrame()
    for seed in sample_seeds:
        kwargs.update({'sample_seed': seed})
        _, model_dict = run_pathway_model_building(adj, node_properties_src, node_properties_tgt, model_name, model_order, **kwargs)
        model_params = pd.concat([model_params, pd.DataFrame(model_dict['model_params'], index=pd.Index([seed], name='seed'))])

    return model_params

run_batch_model_building(adj_file, nrn_file, cfg_file, N_split=None, part_idx=None)

Main function for data extraction and model building to be used in a batch script on different data splits.

Parameters:

Name Type Description Default
adj_file str

File name (.npz format) of scipy.sparse adjacency matrix of the circuit

required
nrn_file str

File name (.h5 or .feather format) of pandas.DataFrame with neuron properties

required
cfg_file str

File name (.json format) of config dict specifying the model building operation; see Notes for details

required
N_split int

Number of data splits to divide data extraction into (to reduce memory consumption)

None
part_idx int

Index of current data split (part) to extract data from Range: 0 .. N_split - 1 Run data extraction of given data split -1 Merge data splits and build model

None

Returns:

Type Description
None

Nothing returned here; Data/model/figures are written to output directories as specified in cfg_file

Raises:

Type Description
AssertionError

If nrn_file is not in .h5 or .feather format

AssertionError

If the adjacency matrix is not a square matrix matching the length of the neuron properties table

AssertionError

If model order not supported (supported: 2, 3)

AssertionError

If model fitting error occurs

KeyError

If name(s) of coordinates not in columns of neuron properties table

Notes

The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

cfg_file must be a .json file containing a dictionary with following entries, most of which are optional:

  • model_name Name of the model (to be used in file names, ...)
  • model_order Model order (2 or 3)
  • bin_size_um Bin size in um for depth binning (optional; default: 100)
  • max_range_um Max. distance range in um to consider (optional; default: full distance range)
  • sample_size Size of random subset of neurons to consider (optional; default: no subsampling)
  • sample_seed Seed for reproducible selection of random subset of neurons (optional)
  • coord_names Names of the coordinates (columns in neuron properties table) based on which to compute Euclidean distance (optional; default: ["x", "y", "z"])
  • depth_name Name of depth coordinate (column in neuron properties table) to use in 3rd-order (bipolar) model (optional; default: "depth")
  • model_dir Output directory where to save the model (optional; default: no saving)
  • data_dir Output directory where to save the extracted data (optional; default: no saving)
  • do_plot Enable/disable output plotting (optional; default: no plotting)
  • plot_dir Output directory where to save the plots, if plotting enabled (optional; default: no saving)
  • N_split Number of data splits (> 1) to sequentially extract data from, to reduce memory consumption (optional; default: no splitting)
  • part_idx Part index (from 0 to N_split-1) to run data extraction only on a specific data split; -1 to merge existing splits and build model (optional; default: data extraction and model building for all splits)
See Also

run_model_building : Underlying main function for model building

Source code in src/connalysis/modelling/modelling.py
 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
120
121
122
123
124
def run_batch_model_building(adj_file, nrn_file, cfg_file, N_split=None, part_idx=None):
    """Main function for data extraction and model building to be used in a batch script on different data splits.

    Parameters
    ----------
    adj_file : str
        File name (.npz format) of scipy.sparse adjacency matrix of the circuit
    nrn_file : str
        File name (.h5 or .feather format) of pandas.DataFrame with neuron properties
    cfg_file : str
        File name (.json format) of config dict specifying the model building operation; see Notes for details
    N_split : int, optional
        Number of data splits to divide data extraction into (to reduce memory consumption)
    part_idx : int, optional
        Index of current data split (part) to extract data from
        Range:  0 .. N_split - 1 Run data extraction of given data split
               -1                Merge data splits and build model

    Returns
    -------
    None
        Nothing returned here; Data/model/figures are written to output directories as specified in `cfg_file`

    Raises
    ------
    AssertionError
        If nrn_file is not in .h5 or .feather format
    AssertionError
        If the adjacency matrix is not a square matrix matching the length of the neuron properties table
    AssertionError
        If model order not supported (supported: 2, 3)
    AssertionError
        If model fitting error occurs
    KeyError
        If name(s) of coordinates not in columns of neuron properties table

    Notes
    -----
    The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

    `cfg_file` must be a .json file containing a dictionary with following entries, most of which are optional:

    - `model_name` Name of the model (to be used in file names, ...)
    - `model_order` Model order (2 or 3)
    - `bin_size_um` Bin size in um for depth binning (optional; default: 100)
    - `max_range_um` Max. distance range in um to consider (optional; default: full distance range)
    - `sample_size` Size of random subset of neurons to consider (optional; default: no subsampling)
    - `sample_seed` Seed for reproducible selection of random subset of neurons (optional)
    - `coord_names` Names of the coordinates (columns in neuron properties table) based on which to compute Euclidean distance (optional; default: ["x", "y", "z"])
    - `depth_name` Name of depth coordinate (column in neuron properties table) to use in 3rd-order (bipolar) model (optional; default: "depth")
    - `model_dir` Output directory where to save the model (optional; default: no saving)
    - `data_dir` Output directory where to save the extracted data (optional; default: no saving)
    - `do_plot` Enable/disable output plotting (optional; default: no plotting)
    - `plot_dir` Output directory where to save the plots, if plotting enabled (optional; default: no saving)
    - `N_split` Number of data splits (> 1) to sequentially extract data from, to reduce memory consumption (optional; default: no splitting)
    - `part_idx` Part index (from 0 to N_split-1) to run data extraction only on a specific data split; -1 to merge existing splits and build model (optional; default: data extraction and model building for all splits)

    See Also
    --------
    run_model_building : Underlying main function for model building

    """

    # Load adjacency matrix (.npz) & neuron properties table (.h5 or .feather)
    adj = sps.load_npz(adj_file)
    if os.path.splitext(nrn_file)[-1] == '.h5':
        node_properties = pd.read_hdf(nrn_file)
    elif os.path.splitext(nrn_file)[-1] == '.feather':
        node_properties = pd.read_feather(nrn_file)
    else:
        assert False, f'ERROR: Neuron table format "{os.path.splitext(nrn_file)[-1]}" not supported!'

    assert adj.shape[0] == adj.shape[1] == node_properties.shape[0], 'ERROR: Data size mismatch!'
    logging.info(f'Loaded connectivity and properties of {node_properties.shape[0]} neurons')

    # Load config file (.json)
    with open(cfg_file, 'r') as f:
        config_dict = json.load(f)

    # Set/Overwrite data split options
    if N_split is not None:
        config_dict.update({'N_split': int(N_split)})
    if part_idx is not None:
        config_dict.update({'part_idx': int(part_idx)})

    # Run model building
    run_model_building(adj, node_properties, **config_dict)

run_model_building(adj, node_properties, model_name, model_order, **kwargs)

Main function for probability model building, consisting of three steps: Data extraction, model fitting, and (optionally) data/model visualization.

Parameters:

Name Type Description Default
adj sparse

Sparse (symmetric) adjacency matrix of the circuit

required
node_properties DataFrame

Data frame with neuron properties

required
model_name str

Name of the model (to be used in file names, ...)

required
model_order int

Model order (2 or 3)

required
kwargs dict

Additional model building settings; see Notes for details

{}

Returns:

Type Description
dict

Data dictionary containing extracted data points (connection probabilities) from the "extract" step; Data/figures also written to output directories as specified in kwargs

dict

Model dictionary containing probability model fitted to data points from "model fitting" step; Model/figures also written to output directories as specified in kwargs

Raises:

Type Description
AssertionError

If the adjacency matrix is not a square matrix matching the length of the neuron properties table

AssertionError

If model order not supported (supported: 2, 3)

AssertionError

If model fitting error occurs

KeyError

If name(s) of coordinates not in columns of neuron properties table

Notes

The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

The 2nd-order and 3rd-order models as defined in [1]_ are supported. See "See Also" for details.

kwargs may contain following (optional) settings:

  • bin_size_um Bin size in um for depth binning (optional; default: 100)
  • max_range_um Max. distance range in um to consider (optional; default: full distance range)
  • sample_size Size of random subset of neurons to consider (optional; default: no subsampling)
  • sample_seed Seed for reproducible selection of random subset of neurons (optional)
  • coord_names Names of the coordinates (columns in neuron properties table) based on which to compute Euclidean distance (optional; default: ["x", "y", "z"])
  • depth_name Name of depth coordinate (column in neuron properties table) to use in 3rd-order (bipolar) model (optional; default: "depth")
  • model_dir Output directory where to save the model (optional; default: no saving)
  • data_dir Output directory where to save the extracted data (optional; default: no saving)
  • do_plot Enable/disable output plotting (optional; default: no plotting)
  • plot_dir Output directory where to save the plots, if plotting enabled (optional; default: no saving)
  • N_split Number of data splits (> 1) to sequentially extract data from, to reduce memory consumption (optional; default: no splitting)
  • part_idx Part index (from 0 to N_split-1) to run data extraction only on a specific data split; -1 to merge existing splits and build model (optional; default: data extraction and model building for all splits)
See Also

run_pathway_model_building : Main model building function for differet source/target node populations conn_prob_2nd_order_model : 2nd-order model building function wrapper for same source/target node population to be used within a processing pipeline conn_prob_3rd_order_model : 3rd-order model building function wrapper for same source/target node population to be used within a processing pipeline

References

.. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

Source code in src/connalysis/modelling/modelling.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
def run_model_building(adj, node_properties, model_name, model_order, **kwargs):
    """Main function for probability model building, consisting of three steps: Data extraction, model fitting, and (optionally) data/model visualization.

    Parameters
    ----------
    adj : scipy.sparse
        Sparse (symmetric) adjacency matrix of the circuit
    node_properties : pandas.DataFrame
        Data frame with neuron properties
    model_name : str
        Name of the model (to be used in file names, ...)
    model_order : int
        Model order (2 or 3)
    kwargs : dict, optional
        Additional model building settings; see Notes for details

    Returns
    -------
    dict
        Data dictionary containing extracted data points (connection probabilities) from the "extract" step; Data/figures also written to output directories as specified in kwargs
    dict
        Model dictionary containing probability model fitted to data points from "model fitting" step; Model/figures also written to output directories as specified in kwargs

    Raises
    ------
    AssertionError
        If the adjacency matrix is not a square matrix matching the length of the neuron properties table
    AssertionError
        If model order not supported (supported: 2, 3)
    AssertionError
        If model fitting error occurs
    KeyError
        If name(s) of coordinates not in columns of neuron properties table

    Notes
    -----
    The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

    The 2nd-order and 3rd-order models as defined in [1]_ are supported. See "See Also" for details.

    `kwargs` may contain following (optional) settings:

    - `bin_size_um` Bin size in um for depth binning (optional; default: 100)
    - `max_range_um` Max. distance range in um to consider (optional; default: full distance range)
    - `sample_size` Size of random subset of neurons to consider (optional; default: no subsampling)
    - `sample_seed` Seed for reproducible selection of random subset of neurons (optional)
    - `coord_names` Names of the coordinates (columns in neuron properties table) based on which to compute Euclidean distance (optional; default: ["x", "y", "z"])
    - `depth_name` Name of depth coordinate (column in neuron properties table) to use in 3rd-order (bipolar) model (optional; default: "depth")
    - `model_dir` Output directory where to save the model (optional; default: no saving)
    - `data_dir` Output directory where to save the extracted data (optional; default: no saving)
    - `do_plot` Enable/disable output plotting (optional; default: no plotting)
    - `plot_dir` Output directory where to save the plots, if plotting enabled (optional; default: no saving)
    - `N_split` Number of data splits (> 1) to sequentially extract data from, to reduce memory consumption (optional; default: no splitting)
    - `part_idx` Part index (from 0 to N_split-1) to run data extraction only on a specific data split; -1 to merge existing splits and build model (optional; default: data extraction and model building for all splits)

    See Also
    --------
    run_pathway_model_building : Main model building function for differet source/target node populations
    conn_prob_2nd_order_model : 2nd-order model building function wrapper for same source/target node population to be used within a processing pipeline
    conn_prob_3rd_order_model : 3rd-order model building function wrapper for same source/target node population to be used within a processing pipeline

    References
    ----------
    .. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

    """

    logging.info(f'Running order-{model_order} model building {kwargs}...')

    assert adj.shape[0] == adj.shape[1] == node_properties.shape[0], 'ERROR: Data size mismatch!'

    # Subsampling (optional)
    sample_size = kwargs.get('sample_size')
    sample_seed = kwargs.get('sample_seed')
    if sample_size is not None and sample_size > 0 and sample_size < node_properties.shape[0]:
        logging.info(f'Subsampling to {sample_size} of {node_properties.shape[0]} neurons (seed={sample_seed})')
        np.random.seed(sample_seed)
        sub_sel = np.random.permutation([True] * sample_size + [False] * (node_properties.shape[0] - sample_size))
        adj = adj.tocsr()[sub_sel, :].tocsc()[:, sub_sel].tocsr()
        node_properties = node_properties.loc[sub_sel, :]

    # Set modelling functions
    if model_order == 2: # Distance-dependent
        fct_extract = _extract_2nd_order
        fct_fit = _build_2nd_order
        fct_plot = _plot_2nd_order
    elif model_order == 3: # Bipolar distance-dependent
        fct_extract = _extract_3rd_order
        fct_fit = _build_3rd_order
        fct_plot = _plot_3rd_order
    else:
        assert False, f'ERROR: Order-{model_order} model building not supported!'

    # Data splits (optional)
    N_split = kwargs.pop('N_split', None)
    part_idx = kwargs.pop('part_idx', None)
    if N_split is None:
        split_indices = None
    else:
        assert N_split > 1, 'ERROR: Number of data splits must be larger than 1!'
        split_indices = np.split(np.arange(node_properties.shape[0]), np.cumsum([np.ceil(node_properties.shape[0] / N_split).astype(int)] * (N_split - 1)))

    if part_idx is None or part_idx == -1: # Run data extraction and model building for all splits
        extract_only = False
        data_fn = 'data'
    else: # Run only data extraction of given part idx
        assert N_split is not None and 0 <= part_idx < N_split, 'ERROR: Part index out of range!'
        extract_only = True
        data_fn = 'data' + _get_data_part_name(N_split, part_idx)

    # Extract connection probability data
    if part_idx == -1: # Special case: Load and merge results of existing parts
        assert N_split is not None, 'ERROR: Number of data splits required!'
        data_dict = _merge_data(kwargs.get('data_dir'), model_name, data_fn, [_get_data_part_name(N_split, p) for p in range(N_split)])
    else:
        data_dict = fct_extract(adj, node_properties, split_indices=split_indices, part_idx=part_idx, **kwargs)
    _save_data(data_dict, kwargs.get('data_dir'), model_name, data_fn)

    if extract_only: # Stop here and return data dict
        return data_dict, {}

    # Fit model
    model_dict = fct_fit(**data_dict, **kwargs)
    _save_data(model_dict, kwargs.get('model_dir'), model_name, 'model')

    # Visualize data/model (optional)
    if kwargs.get('do_plot'):
        fct_plot(adj, node_properties, model_name, **data_dict, **model_dict, **kwargs)

    return data_dict, model_dict

run_pathway_model_building(adj, node_properties_src, node_properties_tgt, model_name, model_order, **kwargs)

Main function for probability model building for pathways with different source and target node populations, consisting of three steps: Data extraction, model fitting, and (optionally) data/model visualization.

Parameters:

Name Type Description Default
adj sparse

Sparse adjacency matrix of the circuit (may be non-symmetric)

required
node_properties_src DataFrame

Data frame with source neuron properties (corresponding to the rows in adj)

required
node_properties_tgt DataFrame

Data frame with target neuron properties (corresponding to the columns in adj)

required
model_name str

Name of the model (to be used in file names, ...)

required
model_order int

Model order (2 or 3)

required
kwargs dict

Additional model building settings; see "See Also" for details

{}

Returns:

Type Description
dict

Data dictionary containing extracted data points (connection probabilities) from the "extract" step; Data/figures also written to output directories as specified in kwargs

dict

Model dictionary containing probability model fitted to data points from "model fitting" step; Model/figures also written to output directories as specified in kwargs

Raises:

Type Description
AssertionError

If the rows/columns of the adjacency matrix are not matching the lengths of the source/target neuron properties tables

AssertionError

If model order not supported (supported: 2, 3)

AssertionError

If model fitting error occurs

AssertionError

If data splitting selected, which is not supported for pathway model building

KeyError

If name(s) of coordinates not in columns of neuron properties table

Notes

The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

The 2nd-order and 3rd-order models as defined in [1]_ are supported. See "See Also" for details.

See Also

run_model_building : Main model building function for same source/target node populations; further details to be found here conn_prob_2nd_order_pathway_model : 2nd-order model building function wrapper for different source/target node populations to be used within a processing pipeline conn_prob_3rd_order_pathway_model : 3rd-order model building function wrapper for different source/target node populations to be used within a processing pipeline

References

.. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

Source code in src/connalysis/modelling/modelling.py
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
def run_pathway_model_building(adj, node_properties_src, node_properties_tgt, model_name, model_order, **kwargs):
    """Main function for probability model building for pathways with different source and target node populations, consisting of three steps: Data extraction, model fitting, and (optionally) data/model visualization.

    Parameters
    ----------
    adj : scipy.sparse
        Sparse adjacency matrix of the circuit (may be non-symmetric)
    node_properties_src : pandas.DataFrame
        Data frame with source neuron properties (corresponding to the rows in adj)
    node_properties_tgt : pandas.DataFrame
        Data frame with target neuron properties (corresponding to the columns in adj)
    model_name : str
        Name of the model (to be used in file names, ...)
    model_order : int
        Model order (2 or 3)
    kwargs : dict, optional
        Additional model building settings; see "See Also" for details

    Returns
    -------
    dict
        Data dictionary containing extracted data points (connection probabilities) from the "extract" step; Data/figures also written to output directories as specified in kwargs
    dict
        Model dictionary containing probability model fitted to data points from "model fitting" step; Model/figures also written to output directories as specified in kwargs

    Raises
    ------
    AssertionError
        If the rows/columns of the adjacency matrix are not matching the lengths of the source/target neuron properties tables
    AssertionError
        If model order not supported (supported: 2, 3)
    AssertionError
        If model fitting error occurs
    AssertionError
        If data splitting selected, which is not supported for pathway model building
    KeyError
        If name(s) of coordinates not in columns of neuron properties table

    Notes
    -----
    The adjacency matrix encodes connectivity between source (rows) and taget (columns) neurons.

    The 2nd-order and 3rd-order models as defined in [1]_ are supported. See "See Also" for details.

    See Also
    --------
    run_model_building : Main model building function for same source/target node populations; further details to be found here
    conn_prob_2nd_order_pathway_model : 2nd-order model building function wrapper for different source/target node populations to be used within a processing pipeline
    conn_prob_3rd_order_pathway_model : 3rd-order model building function wrapper for different source/target node populations to be used within a processing pipeline

    References
    ----------
    .. [1] Gal E, Perin R, Markram H, London M, Segev I, "Neuron Geometry Underlies Universal Network Features in Cortical Microcircuits," bioRxiv, doi: https://doi.org/10.1101/656058.

    """

    logging.info(f'Running order-{model_order} model building {kwargs}...')

    assert adj.shape[0] == node_properties_src.shape[0] and adj.shape[1] == node_properties_tgt.shape[0], 'ERROR: Data size mismatch!'

    # Subsampling (optional)
    sample_size = kwargs.get('sample_size')
    sample_seed = kwargs.get('sample_seed')
    if sample_size is not None and sample_size > 0 and sample_size < np.maximum(node_properties_src.shape[0], node_properties_tgt.shape[0]):
        logging.info(f'Subsampling to {sample_size} of {node_properties_src.shape[0]}x{node_properties_tgt.shape[0]} neurons (seed={sample_seed})')
        np.random.seed(sample_seed)
        if sample_size < node_properties_src.shape[0]:
            sub_sel_src = np.random.permutation([True] * sample_size + [False] * (node_properties_src.shape[0] - sample_size))
        else:
            sub_sel_src = np.full(node_properties_src.shape[0], True)

        if sample_size < node_properties_tgt.shape[0]:
            sub_sel_tgt = np.random.permutation([True] * sample_size + [False] * (node_properties_tgt.shape[0] - sample_size))
        else:
            sub_sel_tgt = np.full(node_properties_tgt.shape[0], True)

        adj = adj.tocsr()[sub_sel_src, :].tocsc()[:, sub_sel_tgt].tocsr()
        # adj = adj[sub_sel_src, :][:, sub_sel_tgt]
        node_properties_src = node_properties_src.loc[sub_sel_src, :]
        node_properties_tgt = node_properties_tgt.loc[sub_sel_tgt, :]

    # Set modelling functions
    if model_order == 2: # Distance-dependent
        fct_extract = _extract_2nd_order_pathway
        fct_fit = _build_2nd_order
        fct_plot = _plot_2nd_order
    elif model_order == 3: # Bipolar distance-dependent
        fct_extract = _extract_3rd_order_pathway
        fct_fit = _build_3rd_order
        fct_plot = _plot_3rd_order
    else:
        assert False, f'ERROR: Order-{model_order} model building not supported!'

    # Data splits (optional)
    N_split = kwargs.pop('N_split', None)
    part_idx = kwargs.pop('part_idx', None)
    assert N_split is None and part_idx is None, 'ERROR: Data splitting not supported!'
    data_fn = 'data'

    # Extract connection probability data
    data_dict = fct_extract(adj, node_properties_src, node_properties_tgt, split_indices=None, part_idx=None, **kwargs)
    _save_data(data_dict, kwargs.get('data_dir'), model_name, data_fn)

    # Fit model
    model_dict = fct_fit(**data_dict, **kwargs)
    _save_data(model_dict, kwargs.get('model_dir'), model_name, 'model')

    # Visualize data/model (optional)
    if kwargs.get('do_plot'):
        fct_plot(adj, [node_properties_src, node_properties_tgt], model_name, **data_dict, **model_dict, **kwargs)

    return data_dict, model_dict