-
Notifications
You must be signed in to change notification settings - Fork 30
/
PlotMorphology.py
1190 lines (1048 loc) · 38.2 KB
/
PlotMorphology.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
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
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
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
263
264
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
341
342
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
401
402
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
504
505
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
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
747
748
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Utilities to plot NeuroML2 cell morphologies.
File: pyneuroml/plot/PlotMorphology.py
Copyright 2023 NeuroML contributors
"""
import argparse
import os
import sys
import random
import typing
import logging
import numpy
import matplotlib
from matplotlib import pyplot as plt
from pyneuroml.pynml import read_neuroml2_file
from pyneuroml.utils.cli import build_namespace
from pyneuroml.utils import extract_position_info
from pyneuroml.utils.plot import (
add_text_to_matplotlib_2D_plot,
get_next_hex_color,
add_box_to_matplotlib_2D_plot,
get_new_matplotlib_morph_plot,
autoscale_matplotlib_plot,
add_scalebar_to_matplotlib_plot,
add_line_to_matplotlib_2D_plot,
DEFAULTS,
)
from neuroml import SegmentGroup, Cell, Segment, NeuroMLDocument
from neuroml.neuro_lex_ids import neuro_lex_ids
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def process_args():
"""
Parse command-line arguments.
"""
parser = argparse.ArgumentParser(
description=("A script which can generate plots of morphologies in NeuroML 2")
)
parser.add_argument(
"nmlFile",
type=str,
metavar="<NeuroML 2 file>",
help="Name of the NeuroML 2 file",
)
parser.add_argument(
"-v", action="store_true", default=DEFAULTS["v"], help="Verbose output"
)
parser.add_argument(
"-nogui",
action="store_true",
default=DEFAULTS["nogui"],
help="Don't open plot window",
)
parser.add_argument(
"-plane2d",
type=str,
metavar="<plane, e.g. xy, yz, zx>",
default=DEFAULTS["plane2d"],
help="Plane to plot on for 2D plot",
)
parser.add_argument(
"-plotType",
type=str,
metavar="<type: detailed, constant, or schematic>",
default=DEFAULTS["plotType"],
help="Level of detail to plot in",
)
parser.add_argument(
"-theme",
type=str,
metavar="<theme: light, dark>",
default=DEFAULTS["theme"],
help="Theme to use for interactive 3d plotting (not used for 2d plotting)",
)
parser.add_argument(
"-minWidth",
type=float,
metavar="<min width of lines>",
default=DEFAULTS["minWidth"],
help="Minimum width of lines to use",
)
parser.add_argument(
"-interactive3d",
action="store_true",
default=DEFAULTS["interactive3d"],
help="Show interactive 3D plot",
)
parser.add_argument(
"-saveToFile",
type=str,
metavar="<Image file name>",
default=None,
help="Name of the image file, for 2D plot",
)
parser.add_argument(
"-square",
action="store_true",
default=DEFAULTS["square"],
help="Scale axes so that image is approximately square, for 2D plot",
)
return parser.parse_args()
def main(args=None):
if args is None:
args = process_args()
plot_from_console(a=args)
def plot_from_console(a: typing.Optional[typing.Any] = None, **kwargs: str):
"""Wrapper around functions for the console script.
:param a: arguments object
:type a:
:param kwargs: other arguments
"""
a = build_namespace(DEFAULTS, a, **kwargs)
print(a)
if a.interactive3d:
from pyneuroml.plot.PlotMorphologyVispy import plot_interactive_3D
plot_interactive_3D(
nml_file=a.nml_file,
min_width=a.min_width,
verbose=a.v,
plot_type=a.plot_type,
theme=a.theme,
)
else:
plot_2D(
a.nml_file,
a.plane2d,
a.min_width,
a.v,
a.nogui,
a.save_to_file,
a.square,
a.plot_type,
)
def plot_2D(
nml_file: typing.Union[str, NeuroMLDocument, Cell],
plane2d: str = "xy",
min_width: float = DEFAULTS["minWidth"], # noqa
verbose: bool = False,
nogui: bool = False,
save_to_file: typing.Optional[str] = None,
square: bool = False,
plot_type: str = "detailed",
title: typing.Optional[str] = None,
close_plot: bool = False,
):
"""Plot cells in a 2D plane.
If a file with a network containing multiple cells is provided, it will
plot all the cells. For detailed neuroml.Cell types, it will plot their
complete morphology. For point neurons, we only plot the points (locations)
where they are.
This method uses matplotlib.
:param nml_file: path to NeuroML cell file, or a NeuroMLDocument object
:type nml_file: str or :py:class:`neuroml.NeuroMLDocument` or
:py:class:`neuroml.Cell`
:param plane2d: what plane to plot (xy/yx/yz/zy/zx/xz)
:type plane2d: str
:param min_width: minimum width for segments (useful for visualising very
thin segments): default 0.8um
:type min_width: float
:param verbose: show extra information (default: False)
:type verbose: bool
:param nogui: do not show matplotlib GUI (default: false)
:type nogui: bool
:param save_to_file: optional filename to save generated morphology to
:type save_to_file: str
:param square: scale axes so that image is approximately square
:type square: bool
:param plot_type: type of plot, one of:
- "detailed": show detailed morphology taking into account each segment's
width
- "constant": show morphology, but use constant line widths
- "schematic": only plot each unbranched segment group as a straight
line, not following each segment
This is only applicable for neuroml.Cell cells (ones with some
morphology)
:type plot_type: str
:param title: title of plot
:type title: str
:param close_plot: call pyplot.close() to close plot after plotting
:type close_plot: bool
"""
if plot_type not in ["detailed", "constant", "schematic"]:
raise ValueError(
"plot_type must be one of 'detailed', 'constant', or 'schematic'"
)
if verbose:
print("Plotting %s" % nml_file)
if type(nml_file) == str:
nml_model = read_neuroml2_file(
nml_file,
include_includes=True,
check_validity_pre_include=False,
verbose=False,
optimized=True,
)
elif isinstance(nml_file, Cell):
nml_model = NeuroMLDocument(id="newdoc")
nml_model.add(nml_file)
elif isinstance(nml_file, NeuroMLDocument):
nml_model = nml_file
else:
raise TypeError(
"Passed model is not a NeuroML file path, nor a neuroml.Cell, nor a neuroml.NeuroMLDocument"
)
(
cell_id_vs_cell,
pop_id_vs_cell,
positions,
pop_id_vs_color,
pop_id_vs_radii,
) = extract_position_info(nml_model, verbose)
if title is None:
if len(nml_model.networks) > 0:
title = "2D plot of %s from %s" % (nml_model.networks[0].id, nml_file)
else:
title = "2D plot of %s" % (nml_model.cells[0].id)
if verbose:
logger.debug(f"positions: {positions}")
logger.debug(f"pop_id_vs_cell: {pop_id_vs_cell}")
logger.debug(f"cell_id_vs_cell: {cell_id_vs_cell}")
logger.debug(f"pop_id_vs_color: {pop_id_vs_color}")
logger.debug(f"pop_id_vs_radii: {pop_id_vs_radii}")
fig, ax = get_new_matplotlib_morph_plot(title, plane2d)
axis_min_max = [float("inf"), -1 * float("inf")]
for pop_id in pop_id_vs_cell:
cell = pop_id_vs_cell[pop_id]
pos_pop = positions[pop_id]
for cell_index in pos_pop:
pos = pos_pop[cell_index]
radius = pop_id_vs_radii[pop_id] if pop_id in pop_id_vs_radii else 10
color = pop_id_vs_color[pop_id] if pop_id in pop_id_vs_color else None
if cell is None:
plot_2D_point_cells(
offset=pos,
plane2d=plane2d,
color=color,
soma_radius=radius,
verbose=verbose,
ax=ax,
fig=fig,
autoscale=False,
scalebar=False,
nogui=True,
)
else:
if plot_type == "schematic":
plot_2D_schematic(
offset=pos,
cell=cell,
segment_groups=None,
labels=True,
plane2d=plane2d,
verbose=verbose,
fig=fig,
ax=ax,
scalebar=False,
nogui=True,
autoscale=False,
square=False,
)
else:
plot_2D_cell_morphology(
offset=pos,
cell=cell,
plane2d=plane2d,
color=color,
plot_type=plot_type,
verbose=verbose,
fig=fig,
ax=ax,
min_width=min_width,
axis_min_max=axis_min_max,
scalebar=False,
nogui=True,
autoscale=False,
square=False,
)
add_scalebar_to_matplotlib_plot(axis_min_max, ax)
autoscale_matplotlib_plot(verbose, square)
if save_to_file:
abs_file = os.path.abspath(save_to_file)
plt.savefig(abs_file, dpi=200, bbox_inches="tight")
print(f"Saved image on plane {plane2d} to {abs_file} of plot: {title}")
if not nogui:
plt.show()
if close_plot:
logger.info("Closing plot")
plt.close()
def plot_2D_cell_morphology(
offset: typing.List[float] = [0, 0],
cell: Cell = None,
plane2d: str = "xy",
color: typing.Optional[str] = None,
title: str = "",
verbose: bool = False,
fig: matplotlib.figure.Figure = None,
ax: matplotlib.axes.Axes = None,
min_width: float = DEFAULTS["minWidth"],
axis_min_max: typing.List = [float("inf"), -1 * float("inf")],
scalebar: bool = False,
nogui: bool = True,
autoscale: bool = True,
square: bool = False,
plot_type: str = "detailed",
save_to_file: typing.Optional[str] = None,
close_plot: bool = False,
overlay_data: typing.Optional[typing.Dict[int, float]] = None,
overlay_data_label: typing.Optional[str] = None,
datamin: typing.Optional[float] = None,
datamax: typing.Optional[float] = None,
colormap_name: str = "viridis",
):
"""Plot the detailed 2D morphology of a cell in provided plane.
The method can also overlay data onto the morphology.
.. versionadded:: 1.0.0
.. seealso::
:py:func:`plot_2D`
general function for plotting
:py:func:`plot_2D_schematic`
for plotting only segmeng groups with their labels
:py:func:`plot_2D_point_cells`
for plotting point cells
:param offset: offset for cell
:type offset: [float, float]
:param cell: cell to plot
:type cell: neuroml.Cell
:param plane2d: plane to plot on
:type plane2d: str
:param color: color to use for all segments
:type color: str
:param fig: a matplotlib.figure.Figure object to use
:type fig: matplotlib.figure.Figure
:param ax: a matplotlib.axes.Axes object to use
:type ax: matplotlib.axes.Axes
:param min_width: minimum width for segments (useful for visualising very
thin segments): default 0.8um
:type min_width: float
:param axis_min_max: min, max value of axes
:type axis_min_max: [float, float]
:param title: title of plot
:type title: str
:param verbose: show extra information (default: False)
:type verbose: bool
:param nogui: do not show matplotlib GUI (default: false)
:type nogui: bool
:param save_to_file: optional filename to save generated morphology to
:type save_to_file: str
:param square: scale axes so that image is approximately square
:type square: bool
:param autoscale: toggle autoscaling
:type autoscale: bool
:param scalebar: toggle scalebar
:type scalebar: bool
:param close_plot: call pyplot.close() to close plot after plotting
:type close_plot: bool
:param overlay_data: data to overlay over the morphology
this must be a dictionary with segment ids as keys, the single value to
overlay as values
:type overlay_data: dict, keys are segment ids, values are magnitudes to
overlay on curtain plots
:param overlay_data_label: label of data being overlaid
:type overlay_data_label: str
:param colormap_name: name of matplotlib colourmap to use for data overlay
See:
https://matplotlib.org/stable/api/matplotlib_configuration_api.html#matplotlib.colormaps
Note: random colours are used for each segment if no data is to be overlaid
:type colormap_name: str
:param datamin: min limits of data (useful to compare different plots)
:type datamin: float
:param datamax: max limits of data (useful to compare different plots)
:type datamax: float
:raises: ValueError if `cell` is None
"""
if cell is None:
raise ValueError(
"No cell provided. If you would like to plot a network of point neurons, consider using `plot_2D_point_cells` instead"
)
try:
soma_segs = cell.get_all_segments_in_group("soma_group")
except Exception:
soma_segs = []
try:
dend_segs = cell.get_all_segments_in_group("dendrite_group")
except Exception:
dend_segs = []
try:
axon_segs = cell.get_all_segments_in_group("axon_group")
except Exception:
axon_segs = []
if fig is None:
fig, ax = get_new_matplotlib_morph_plot(title)
# overlaying data
data_max = -1 * float("inf")
data_min = float("inf")
acolormap = None
norm = None
if overlay_data:
this_max = numpy.max(list(overlay_data.values()))
this_min = numpy.min(list(overlay_data.values()))
if this_max > data_max:
data_max = this_max
if this_min < data_min:
data_min = this_min
if datamin is not None:
data_min = datamin
if datamax is not None:
data_max = datamax
acolormap = matplotlib.colormaps[colormap_name]
norm = matplotlib.colors.Normalize(vmin=data_min, vmax=data_max)
fig.colorbar(
matplotlib.cm.ScalarMappable(norm=norm, cmap=acolormap),
label=overlay_data_label,
)
# random default color
for seg in cell.morphology.segments:
p = cell.get_actual_proximal(seg.id)
d = seg.distal
width = (p.diameter + d.diameter) / 2
if width < min_width:
width = min_width
if plot_type == "constant":
width = min_width
if overlay_data and acolormap and norm:
try:
seg_color = acolormap(norm(overlay_data[seg.id]))
except KeyError:
seg_color = "black"
else:
seg_color = "b"
if seg.id in soma_segs:
seg_color = "g"
elif seg.id in axon_segs:
seg_color = "r"
spherical = (
p.x == d.x and p.y == d.y and p.z == d.z and p.diameter == d.diameter
)
if verbose:
logger.info(
"\nSeg %s, id: %s%s has proximal: %s, distal: %s (width: %s, min_width: %s), color: %s"
% (
seg.name,
seg.id,
" (spherical)" if spherical else "",
p,
d,
width,
min_width,
str(seg_color),
)
)
if plane2d == "xy":
add_line_to_matplotlib_2D_plot(
ax,
[offset[0] + p.x, offset[0] + d.x],
[offset[1] + p.y, offset[1] + d.y],
width,
seg_color if color is None else color,
axis_min_max,
)
elif plane2d == "yx":
add_line_to_matplotlib_2D_plot(
ax,
[offset[1] + p.y, offset[1] + d.y],
[offset[0] + p.x, offset[0] + d.x],
width,
seg_color if color is None else color,
axis_min_max,
)
elif plane2d == "xz":
add_line_to_matplotlib_2D_plot(
ax,
[offset[0] + p.x, offset[0] + d.x],
[offset[2] + p.z, offset[2] + d.z],
width,
seg_color if color is None else color,
axis_min_max,
)
elif plane2d == "zx":
add_line_to_matplotlib_2D_plot(
ax,
[offset[2] + p.z, offset[2] + d.z],
[offset[0] + p.x, offset[0] + d.x],
width,
seg_color if color is None else color,
axis_min_max,
)
elif plane2d == "yz":
add_line_to_matplotlib_2D_plot(
ax,
[offset[1] + p.y, offset[1] + d.y],
[offset[2] + p.z, offset[2] + d.z],
width,
seg_color if color is None else color,
axis_min_max,
)
elif plane2d == "zy":
add_line_to_matplotlib_2D_plot(
ax,
[offset[2] + p.z, offset[2] + d.z],
[offset[1] + p.y, offset[1] + d.y],
width,
seg_color if color is None else color,
axis_min_max,
)
else:
raise Exception(f"Invalid value for plane: {plane2d}")
if verbose:
print("Extent x: %s -> %s" % (axis_min_max[0], axis_min_max[1]))
if scalebar:
add_scalebar_to_matplotlib_plot(axis_min_max, ax)
if autoscale:
autoscale_matplotlib_plot(verbose, square)
if save_to_file:
abs_file = os.path.abspath(save_to_file)
plt.savefig(abs_file, dpi=200, bbox_inches="tight")
print(f"Saved image on plane {plane2d} to {abs_file} of plot: {title}")
if not nogui:
plt.show()
if close_plot:
logger.info("closing plot")
plt.close()
def plot_2D_point_cells(
offset: typing.List[float] = [0, 0],
plane2d: str = "xy",
color: typing.Optional[str] = None,
soma_radius: float = 10.0,
title: str = "",
verbose: bool = False,
fig: matplotlib.figure.Figure = None,
ax: matplotlib.axes.Axes = None,
axis_min_max: typing.List = [float("inf"), -1 * float("inf")],
scalebar: bool = False,
nogui: bool = True,
autoscale: bool = True,
square: bool = False,
save_to_file: typing.Optional[str] = None,
close_plot: bool = False,
):
"""Plot point cells.
.. versionadded:: 1.0.0
.. seealso::
:py:func:`plot_2D`
general function for plotting
:py:func:`plot_2D_schematic`
for plotting only segmeng groups with their labels
:py:func:`plot_2D_cell_morphology`
for plotting cells with detailed morphologies
:param offset: location of cell
:type offset: [float, float]
:param plane2d: plane to plot on
:type plane2d: str
:param color: color to use for cell
:type color: str
:param soma_radius: radius of soma
:type soma_radius: float
:param fig: a matplotlib.figure.Figure object to use
:type fig: matplotlib.figure.Figure
:param ax: a matplotlib.axes.Axes object to use
:type ax: matplotlib.axes.Axes
:param axis_min_max: min, max value of axes
:type axis_min_max: [float, float]
:param title: title of plot
:type title: str
:param verbose: show extra information (default: False)
:type verbose: bool
:param nogui: do not show matplotlib GUI (default: false)
:type nogui: bool
:param save_to_file: optional filename to save generated morphology to
:type save_to_file: str
:param square: scale axes so that image is approximately square
:type square: bool
:param autoscale: toggle autoscaling
:type autoscale: bool
:param scalebar: toggle scalebar
:type scalebar: bool
:param close_plot: call pyplot.close() to close plot after plotting
:type close_plot: bool
"""
if fig is None:
fig, ax = get_new_matplotlib_morph_plot(title)
cell_color = get_next_hex_color()
if plane2d == "xy":
add_line_to_matplotlib_2D_plot(
ax,
[offset[0], offset[0]],
[offset[1], offset[1]],
soma_radius,
cell_color if color is None else color,
axis_min_max,
)
elif plane2d == "yx":
add_line_to_matplotlib_2D_plot(
ax,
[offset[1], offset[1]],
[offset[0], offset[0]],
soma_radius,
cell_color if color is None else color,
axis_min_max,
)
elif plane2d == "xz":
add_line_to_matplotlib_2D_plot(
ax,
[offset[0], offset[0]],
[offset[2], offset[2]],
soma_radius,
cell_color if color is None else color,
axis_min_max,
)
elif plane2d == "zx":
add_line_to_matplotlib_2D_plot(
ax,
[offset[2], offset[2]],
[offset[0], offset[0]],
soma_radius,
cell_color if color is None else color,
axis_min_max,
)
elif plane2d == "yz":
add_line_to_matplotlib_2D_plot(
ax,
[offset[1], offset[1]],
[offset[2], offset[2]],
soma_radius,
cell_color if color is None else color,
axis_min_max,
)
elif plane2d == "zy":
add_line_to_matplotlib_2D_plot(
ax,
[offset[2], offset[2]],
[offset[1], offset[1]],
soma_radius,
cell_color if color is None else color,
axis_min_max,
)
else:
raise Exception(f"Invalid value for plane: {plane2d}")
if scalebar:
add_scalebar_to_matplotlib_plot(axis_min_max, ax)
if autoscale:
autoscale_matplotlib_plot(verbose, square)
if save_to_file:
abs_file = os.path.abspath(save_to_file)
plt.savefig(abs_file, dpi=200, bbox_inches="tight")
print(f"Saved image on plane {plane2d} to {abs_file} of plot: {title}")
if not nogui:
plt.show()
if close_plot:
logger.info("closing plot")
plt.close()
def plot_2D_schematic(
cell: Cell,
segment_groups: typing.Optional[typing.List[SegmentGroup]],
offset: typing.List[float] = [0, 0],
labels: bool = False,
plane2d: str = "xy",
width: float = 2.0,
verbose: bool = False,
square: bool = False,
nogui: bool = False,
save_to_file: typing.Optional[str] = None,
scalebar: bool = True,
autoscale: bool = True,
fig: matplotlib.figure.Figure = None,
ax: matplotlib.axes.Axes = None,
title: str = "",
close_plot: bool = False,
) -> None:
"""Plot a 2D schematic of the provided segment groups.
This plots each segment group as a straight line between its first and last
segment.
.. versionadded:: 1.0.0
.. seealso::
:py:func:`plot_2D`
general function for plotting
:py:func:`plot_2D_point_cells`
for plotting point cells
:py:func:`plot_2D_cell_morphology`
for plotting cells with detailed morphologies
:param offset: offset for cell
:type offset: [float, float]
:param cell: cell to plot
:type cell: neuroml.Cell
:param segment_groups: list of unbranched segment groups to plot
:type segment_groups: list(SegmentGroup)
:param labels: toggle labelling of segment groups
:type labels: bool
:param plane2d: what plane to plot (xy/yx/yz/zy/zx/xz)
:type plane2d: str
:param width: width for lines
:type width: float
:param verbose: show extra information (default: False)
:type verbose: bool
:param square: scale axes so that image is approximately square
:type square: bool
:param nogui: do not show matplotlib GUI (default: false)
:type nogui: bool
:param save_to_file: optional filename to save generated morphology to
:type save_to_file: str
:param fig: a matplotlib.figure.Figure object to use
:type fig: matplotlib.figure.Figure
:param ax: a matplotlib.axes.Axes object to use
:type ax: matplotlib.axes.Axes
:param title: title of plot
:type title: str
:param square: scale axes so that image is approximately square
:type square: bool
:param autoscale: toggle autoscaling
:type autoscale: bool
:param scalebar: toggle scalebar
:type scalebar: bool
:param close_plot: call pyplot.close() to close plot after plotting
:type close_plot: bool
"""
if title == "":
title = f"2D schematic of segment groups from {cell.id}"
# if no segment groups are given, do them all
if segment_groups is None:
segment_groups = []
for sg in cell.morphology.segment_groups:
if sg.neuro_lex_id == neuro_lex_ids["section"]:
segment_groups.append(sg.id)
ord_segs = cell.get_ordered_segments_in_groups(
segment_groups, check_parentage=False
)
if fig is None:
logger.debug("No figure provided, creating new fig and ax")
fig, ax = get_new_matplotlib_morph_plot(title, plane2d)
if plane2d == "xy":
ax.set_xlabel("x (μm)")
ax.set_ylabel("y (μm)")
elif plane2d == "yx":
ax.set_xlabel("y (μm)")
ax.set_ylabel("x (μm)")
elif plane2d == "xz":
ax.set_xlabel("x (μm)")
ax.set_ylabel("z (μm)")
elif plane2d == "zx":
ax.set_xlabel("z (μm)")
ax.set_ylabel("x (μm)")
elif plane2d == "yz":
ax.set_xlabel("y (μm)")
ax.set_ylabel("z (μm)")
elif plane2d == "zy":
ax.set_xlabel("z (μm)")
ax.set_ylabel("y (μm)")
else:
logger.error(f"Invalid value for plane: {plane2d}")
sys.exit(-1)
# use a mutable object so it can be passed as an argument to methods, using
# float (immuatable) variables requires us to return these from all methods
axis_min_max = [float("inf"), -1 * float("inf")]
width = 1
for sgid, segs in ord_segs.items():
sgobj = cell.get_segment_group(sgid)
if sgobj.neuro_lex_id != neuro_lex_ids["section"]:
raise ValueError(
f"{sgobj} does not have neuro_lex_id set to indicate it is an unbranched segment"
)
# get proximal and distal points
first_seg = segs[0] # type: Segment
last_seg = segs[-1] # type: Segment
# unique color for each segment group
color = get_next_hex_color()
if plane2d == "xy":
add_line_to_matplotlib_2D_plot(
ax,
[offset[0] + first_seg.proximal.x, offset[0] + last_seg.distal.x],
[offset[1] + first_seg.proximal.y, offset[1] + last_seg.distal.y],
width,
color,
axis_min_max,
)
if labels:
add_text_to_matplotlib_2D_plot(
ax,
[offset[0] + first_seg.proximal.x, offset[0] + last_seg.distal.x],
[offset[1] + first_seg.proximal.y, offset[1] + last_seg.distal.y],
color=color,
text=sgid,
)
elif plane2d == "yx":
add_line_to_matplotlib_2D_plot(
ax,
[offset[0] + first_seg.proximal.y, offset[0] + last_seg.distal.y],
[offset[1] + first_seg.proximal.x, offset[1] + last_seg.distal.x],
width,
color,
axis_min_max,
)
if labels:
add_text_to_matplotlib_2D_plot(
ax,
[offset[0] + first_seg.proximal.y, offset[0] + last_seg.distal.y],
[offset[1] + first_seg.proximal.x, offset[1] + last_seg.distal.x],
color=color,
text=sgid,
)
elif plane2d == "xz":
add_line_to_matplotlib_2D_plot(
ax,
[offset[0] + first_seg.proximal.x, offset[0] + last_seg.distal.x],
[offset[1] + first_seg.proximal.z, offset[1] + last_seg.distal.z],
width,
color,
axis_min_max,
)
if labels:
add_text_to_matplotlib_2D_plot(
ax,
[offset[0] + first_seg.proximal.x, offset[0] + last_seg.distal.x],
[offset[1] + first_seg.proximal.z, offset[1] + last_seg.distal.z],
color=color,
text=sgid,
)
elif plane2d == "zx":
add_line_to_matplotlib_2D_plot(
ax,
[offset[0] + first_seg.proximal.z, offset[0] + last_seg.distal.z],
[offset[1] + first_seg.proximal.x, offset[1] + last_seg.distal.x],
width,
color,
axis_min_max,
)
if labels:
add_text_to_matplotlib_2D_plot(
ax,
[offset[0] + first_seg.proximal.z, offset[0] + last_seg.distal.z],
[offset[1] + first_seg.proximal.x, offset[1] + last_seg.distal.x],
color=color,
text=sgid,
)
elif plane2d == "yz":
add_line_to_matplotlib_2D_plot(
ax,
[offset[0] + first_seg.proximal.y, offset[0] + last_seg.distal.y],
[offset[1] + first_seg.proximal.z, offset[1] + last_seg.distal.z],
width,
color,
axis_min_max,
)
if labels:
add_text_to_matplotlib_2D_plot(
ax,
[offset[0] + first_seg.proximal.y, offset[0] + last_seg.distal.y],
[offset[1] + first_seg.proximal.z, offset[1] + last_seg.distal.z],
color=color,
text=sgid,
)
elif plane2d == "zy":
add_line_to_matplotlib_2D_plot(
ax,
[offset[0] + first_seg.proximal.z, offset[0] + last_seg.distal.z],
[offset[1] + first_seg.proximal.y, offset[1] + last_seg.distal.y],
width,
color,
axis_min_max,
)
if labels:
add_text_to_matplotlib_2D_plot(
ax,
[offset[0] + first_seg.proximal.z, offset[0] + last_seg.distal.z],
[offset[1] + first_seg.proximal.y, offset[1] + last_seg.distal.y],
color=color,
text=sgid,
)
else:
raise Exception(f"Invalid value for plane: {plane2d}")
if verbose:
print("Extent x: %s -> %s" % (axis_min_max[0], axis_min_max[1]))
if scalebar:
add_scalebar_to_matplotlib_plot(axis_min_max, ax)
if autoscale:
autoscale_matplotlib_plot(verbose, square)
if save_to_file:
abs_file = os.path.abspath(save_to_file)
plt.savefig(abs_file, dpi=200, bbox_inches="tight")
print(f"Saved image on plane {plane2d} to {abs_file} of plot: {title}")
if not nogui:
plt.show()
if close_plot:
logger.info("closing plot")
plt.close()