-
Notifications
You must be signed in to change notification settings - Fork 1
/
spine_head_analyzer.py
2160 lines (1812 loc) · 86.9 KB
/
spine_head_analyzer.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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>
"""
This file contains the classes for Spine Head Analyzer.
"""
# stuff to call Volrover individual executables
import subprocess
import os
import time
import difflib
import re
import itertools
# blender imports
import bpy
from bpy.props import BoolProperty, CollectionProperty, EnumProperty, \
FloatProperty, FloatVectorProperty, IntProperty, \
IntVectorProperty, PointerProperty, StringProperty
import mathutils
# python imports
import re
import numpy as np
import neuropil_tools
import cellblender
# Spine Head Analyzer Operators:
class NEUROPIL_OT_spine_namestruct(bpy.types.Operator):
bl_idname = "processor_tool.spine_namestruct"
bl_label = "Define Naming Pattern for Main Object"
bl_description = "Define Naming Pattern for Main Object"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_options = {'UNDO'}
spine_namestruct_name: StringProperty(name = "Name: ", description = "Assign Spine Name", default = "")
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_props_dialog(self)
def execute(self, context):
context.scene.test_tool.spine_namestruct(context, self.spine_namestruct_name)
return {'FINISHED'}
class NEUROPIL_OT_psd_namestruct(bpy.types.Operator):
bl_idname = "processor_tool.psd_namestruct"
bl_label = "Define Naming Pattern for Meta Object"
bl_description = "Define Naming Pattern for Meta Object"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_options = {'UNDO'}
PSD_namestruct_name: StringProperty(name = "Name: ", description = "Assign PSD Name", default = "")
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_props_dialog(self)
def execute(self, context):
context.scene.test_tool.PSD_namestruct(context, self.PSD_namestruct_name)
return {'FINISHED'}
#class NEUROPIL_OT_inter_namestruct(bpy.types.Operator):
# bl_idname = "spine_head_analyzer.inter_namestruct"
# bl_label = "Define Naming Pattern for Intermediate Region (spine neck)"
# bl_description = "Define Naming Pattern for Intermediate Region (spine neck)"
# bl_space_type = "PROPERTIES"
# bl_region_type = "WINDOW"
# bl_options = {'UNDO'}
#global inter_namestruct_name
#inter_namestruct_name: StringProperty(name = "Name: ", description = "Assign Intermediate Region Name", default = "")
#def invoke(self, context, event):
# wm = context.window_manager
# return wm.invoke_props_dialog(self)
#def execute(self, context):
# context.scene.volume_analyzer.inter_namestruct(context, self.inter_namestruct_name)
# return {'FINISHED'}
#class NEUROPIL_OT_outer_namestruct(bpy.types.Operator):
# bl_idname = "spine_head_analyzer.outer_namestruct"
# bl_label = "Define Naming Pattern for Outer Region (whole spine)"
# bl_description = "Define Naming Pattern for Outer Region (whole spine)"
# bl_space_type = "PROPERTIES"
# bl_region_type = "WINDOW"
# bl_options = {'UNDO'}
##global outer_namestruct_name
# outer_namestruct_name: StringProperty(name = "Name: ", description = "Assign Outer Region Name", default = "")
# def invoke(self, context, event):
# wm = context.window_manager
# return wm.invoke_props_dialog(self)
# def execute(self, context):
# context.scene.volume_analyzer.outer_namestruct(context, self.outer_namestruct_name)
# return {'FINISHED'}
class NEUROPIL_OT_inner_namestruct(bpy.types.Operator):
bl_idname = "spine_head_analyzer.inner_namestruct"
bl_label = "Define Naming Pattern for Inner Region (spine head)"
bl_description = "Define Naming Pattern for Inner Region (spine head)"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_options = {'UNDO'}
#global inner_namestruct_name
# inner_namestruct_name: StringProperty(name = "Name: ", description = "Assign Inner Region Name", default = "")
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_props_dialog(self)
def execute(self, context):
context.scene.volume_analyzer.inner_namestruct(context, self.inner_namestruct_name)
return {'FINISHED'}
class NEUROPIL_OT_select_psd(bpy.types.Operator):
bl_idname = "spine_head_analyzer.select_psd"
bl_label = "Select Faces of Contact"
bl_description = "Select Faces of Contact"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.object.spine_head_ana.select_psd(context)
return {'FINISHED'}
class NEUROPIL_OT_reset_psd(bpy.types.Operator):
bl_idname = "spine_head_analyzer.reset_psd"
bl_label = "Reset Contact Data to Initial State"
bl_description = "Reset Contact Data to Initial State"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.object.spine_head_ana.reset_psd(context)
return {'FINISHED'}
class NEUROPIL_OT_generate_mock_psd(bpy.types.Operator):
bl_idname = "spine_head_analyzer.generate_mock_psd"
bl_label = "Initialize Region"
bl_description = "Initialize Region"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.object.spine_head_ana.generate_mock_psd(context)
return {'FINISHED'}
class NEUROPIL_OT_remove_mock_psd(bpy.types.Operator):
bl_idname = "spine_head_analyzer.remove_mock_psd"
bl_label = "Remove Initialized Region"
bl_description = "Remove Initialized Region"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.object.spine_head_ana.remove_mock_psd(context)
return {'FINISHED'}
class NEUROPIL_OT_compute_volume(bpy.types.Operator):
bl_idname = "spine_head_analyzer.compute_volume"
bl_label = "Label spine head and compute its volume"
bl_description = "Label spine head and compute its volume"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.object.spine_head_ana.compute_volume(context,'head')
return {'FINISHED'}
class NEUROPIL_OT_compute_volume_spine(bpy.types.Operator):
bl_idname = "spine_head_analyzer.compute_volume_spine"
bl_label = "Label whole spine and compute its volume"
bl_description = "Label whole spine and compute its volume"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.object.spine_head_ana.compute_volume(context,'spine')
return {'FINISHED'}
class NEUROPIL_OT_calculate_diameter(bpy.types.Operator):
bl_idname = "spine_head_analyzer.calculate_diameter"
bl_label = "Calculate diameter"
bl_description = "Calculate diameter of spine neck"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.object.spine_head_ana.calculate_diameter(context)
return{'FINISHED'}
class NEUROPIL_OT_calculate_diameter_head(bpy.types.Operator):
bl_idname = "spine_head_analyzer.calculate_diameter_head"
bl_label = "Calculate diameter (head)"
bl_description = "Calculate diameter of spine head"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.object.spine_head_ana.calculate_diameter_head(context)
return{'FINISHED'}
class NEUROPIL_OT_recompute_volumes(bpy.types.Operator):
bl_idname = "spine_head_analyzer.recompute_volumes"
bl_label = "Recompute volumes of all spines, heads, and necks on object"
bl_description = "Recompute volumes of all spines, heads, and necks on object"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
report_file = open('spine_data_report.txt','w')
dends = bpy.context.scene.test_tool.spine_namestruct_name.replace('#', '[0-9]')
dend_filter = dends
#dend_filter = 'd[0-9]{2}$'
dend_objs = [obj.name for obj in context.scene.collection.children[0].objects if re.match(dend_filter,obj.name) != None]
dend_objs.sort()
orig_obj = context.active_object
orig_obj.select_set(False)
orig_obj.hide_viewport = False
bpy.context.view_layer.objects.active = None
bpy.context.view_layer.update()
for dend in dend_objs:
obj = context.scene.collection.children[0].objects[dend]
obj.hide_viewport = False
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
bpy.context.view_layer.update()
obj.spine_head_ana.recompute_volumes(context,report_file)
obj.select_set(False)
obj.hide_viewport = True
bpy.context.view_layer.objects.active = None
bpy.context.view_layer.update()
orig_obj.hide_viewport = False
orig_obj.select_set(True)
bpy.context.view_layer.objects.active = orig_obj
# context.object.spine_head_ana.recompute_volumes(context,context.active_object)
report_file.close()
return {'FINISHED'}
class NEUROPIL_OT_output(bpy.types.Operator):
bl_idname = "spine_head_analyzer.output"
bl_label = "Output Data"
bl_description = "Output Data"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
date = time.ctime().split()
day = date[1] + '_' + date[2] + '_' + date[4]
filepath = bpy.data.filepath
blendfilename = filepath.split('/')[-1]
blendfilename2 = blendfilename[:-6]
path = filepath[:-len(blendfilename)]
outfilename = path + blendfilename2 + '_' + day + '.txt'
if bpy.data.filepath != None:
dend_outFile = open(outfilename, 'wt')
dend_outFile.write('# sy pre_post head_vol spine_vol neck_vol computed_area region_area dia_head_max dia_head_min dia_neck_max dia_neck_min\n')
dends = bpy.context.scene.test_tool.spine_namestruct_name.replace('#', '[0-9]')
dend_filter = dends
dend_objs = [obj for obj in context.scene.collection.children[0].objects if re.match(dend_filter,obj.name) != None]
#dend_filter = 'd[0-9][0-9]*sp[0-9]'
#dend_objs = [obj for obj in context.scene.collection.children[0].objects]
#print(dend_objs)
for obj in dend_objs:
#dend_outFile.write('%s \n' % obj.name)
obj.spine_head_ana.output(context, obj, dend_outFile)
dend_outFile.close()
else:
dend_outFile = open(outfilename, 'wt')
dend_outFile.write('# sy pre_post head_vol spine_vol neck_vol computed_area region_area\n')
dends = bpy.context.scene.test_tool.spine_namestruct_name.replace('#', '[0-9]')
dend_filter = dends
dend_objs = [obj for obj in context.scene.collection.children[0].objects if re.match(dend_filter,obj.name) != None]
#print(dend_objs)
for obj in dend_objs:
#dend_outFile.write('%s \n' % obj.name)
obj.spine_head_ana.output(context, obj, dend_outFile)
dend_outFile.close()
#xon_outFile = open('spine_head_analysis_output.axons.txt', 'wt')
#axon_outFile.write('# sy pre_post spine_vol head_vol neck_vol spine_area head_area neck_area psd_az_area psd_az_loc_x psd_az_loc_y psd_az_loc_z neck_base_loc_x neck_base_loc_y neck_base_loc_z mito h_hooked h_concave h_flatface h_bulbous h_skinny n_short n_long n_stubby n_thin n_tapered n_branched n_twotiered glia_spicule glia_ensheathed glia_adjacent glia_distant exclude\n')
#axon_filter = 'a[0-9]{2}$'
#axon_objs = [obj for obj in context.scene.collection.children[0].objects if re.match(axon_filter,obj.name) != None]
#for obj in axon_objs:
# obj.spine_head_ana.output(context,axon_outFile)
#axon_outFile.close()
return {'FINISHED'}
# Spine Head Analyzer Panel:
class NEUROPIL_UL_check_psd(bpy.types.UIList):
use_contact_filter: BoolProperty(name = "Filter Region List by Contact Names", default = True)
def draw_item(self, context, layout, data, item, icon, active_data,
active_propname, index):
self.use_filter_show = True
scn = context.scene
active_obj = context.active_object
psd = active_obj.spine_head_ana.psd_list.get(item.name)
if psd != None:
if psd.contact_type == 'PROTRUSION':
volume = active_obj.spine_head_ana.psd_list[item.name].volume
volume_spine = active_obj.spine_head_ana.psd_list[item.name].volume_spine
if (volume == 0.0) and (volume_spine == 0.0):
layout.label(item.name)
else:
layout.label(item.name, icon='FILE_TICK')
elif psd.contact_type == 'VARICOSITY':
volume = active_obj.spine_head_ana.psd_list[item.name].volume
if (volume == 0.0):
layout.label(item.name)
else:
layout.label(item.name, icon='FILE_TICK')
elif psd.contact_type == 'PLAIN':
layout.label(item.name, icon='STYLUS_PRESSURE')
else:
layout.label(item.name)
def draw_filter(self, context, layout):
box1 = layout.box()
row = box1.row()
row.prop(self, 'use_contact_filter', text='Use Contact Name Filter')
def filter_items(self, context, data, propname):
helper_funcs = bpy.types.UI_UL_list
regs = getattr(data, propname)
obj = context.active_object
if obj.processor.contact_pattern_match_list:
contact_pattern = obj.processor.contact_pattern_match_list[obj.spine_head_ana.active_contact_pattern_index]
else:
contact_pattern = None
flt_flags = []
flt_neworder = []
if self.use_contact_filter and contact_pattern:
bn1_regex = contact_pattern.base_name_1_regex
bn2_regex = contact_pattern.base_name_2_regex
c_regex = contact_pattern.contact_name_regex
c_reg_regex = bn1_regex + c_regex + bn2_regex
c_reg_recomp = re.compile(c_reg_regex)
flt_flags = [ self.bitflag_filter_item*((c_reg_recomp.fullmatch(reg.name)!=None)) for reg in regs ]
else:
flt_flags = [self.bitflag_filter_item]*len(regs)
flt_neworder = helper_funcs.sort_items_by_name(regs, 'name')
return flt_flags, flt_neworder
class NEUROPIL_UL_contact_patterns(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data,
active_propname, index):
layout.label(item.name)
class NEUROPIL_PT_SpineHeadAnalyzer(bpy.types.Panel):
bl_label = "Morphometric Analysis Tool"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_options = {'DEFAULT_CLOSED'}
bl_category = "Neuropil Tools"
def draw(self, context):
if context.object != None:
context.object.spine_head_ana.draw_panel(context, panel=self)
class SpineHeadAnalyzerSceneProperty(bpy.types.PropertyGroup):
varicosity_label: StringProperty("Varicosity Label", default = 'axb')
protrusion_label: StringProperty("Protrusion Label", default = 'sp')
head_label: StringProperty("Head Label", default = 'sph')
neck_label: StringProperty("Neck Label", default = 'spn')
'''
inner_namestruct_name: StringProperty("Set Inner Region Name", default = "d##sph##")
inter_namestruct_name: StringProperty("Set Intermediate Region Name", default = "d##spn##")
outer_namestruct_name: StringProperty("Set Outer Region Name", default = "d##sp##")
def spine_namestruct(self, context, spine_namestruct_name):
self.spine_namestruct_name = spine_namestruct_name
def PSD_namestruct(self, context, PSD_namestruct_name):
self.PSD_namestruct_name = PSD_namestruct_name
def inter_namestruct(self, context, inter_namestruct_name):
self.inter_namestruct_name = inter_namestruct_name
def outer_namestruct(self, context, outer_namestruct_name):
self.outer_namestruct_name = outer_namestruct_name
def inner_namestruct(self, context, inner_namestruct_name):
self.inner_namestruct_name = inner_namestruct_name
'''
# Spine Head Analyzer Properties:
# Properties of the PSDs:
class SpineHeadAnalyzerPSDProperty(bpy.types.PropertyGroup):
name: StringProperty(name="Spine PSD or AZ Name", default="")
char_postsynaptic: BoolProperty(name="Pre or Postsynaptic",default=True)
head_name: StringProperty(name="Spine Head Name", default="")
spine_name: StringProperty(name="Spine Name", default="")
neck_name: StringProperty(name="Spine Neck Name", default="")
volume: FloatProperty(name="Volume of Spine Head",default=0.0)
volume_spine: FloatProperty(name="Volume of Spine",default=0.0)
volume_neck: FloatProperty(name="Volume of Spine Neck",default=0.0)
area_head: FloatProperty(name="Area of Spine Head",default=0.0)
area_spine: FloatProperty(name="Area of Spine",default=0.0)
area_neck: FloatProperty(name="Surface Area of Spine Neck",default=0.0)
area_neck_cross_section_abt: FloatProperty(name="Area of Spine Neck cross section based on avg of top and base cross section area",default=0.0)
area_neck_cross_section_lbt: FloatProperty(name="Area of Spine Neck cross section based on volume_neck/length_neck_lbt",default=0.0)
area_psd_az: FloatProperty(name="Area of PSD or AZ",default=0.0)
diameter_neck_max: FloatProperty(name="Diameter of Neck",default=0.0)
diameter_neck_min: FloatProperty(name="Diameter of Neck",default=0.0)
diameter_neck_lbt: FloatProperty(name="Diameter of Neck based on area_neck_cross_section_lbt",default=0.0)
length_neck: FloatProperty(name="Length of Neck based on volume_neck/area_neck_cross_section",default=0.0)
length_neck_lbt: FloatProperty(name="Length of Neck based on distance from base to top",default=0.0)
diameter_head_max: FloatProperty(name="Diameter of Head",default=0.0)
diameter_head_min: FloatProperty(name="Diameter of Head",default=0.0)
diameter_head_lbt: FloatProperty(name="Diameter of Head based on area_neck_cross_section_lbt",default=0.0)
length_head: FloatProperty(name="Length of Head based on volume_neck/area_neck_cross_section",default=0.0)
length_head_lbt: FloatProperty(name="Length of Head based on distance from base to top",default=0.0)
psd_az_location: FloatVectorProperty(name="Location of PSD or AZ",default=(0.0,0.0,0.0))
neck_top_location: FloatVectorProperty(name="Location of Top of Spine Neck",default=(0.0,0.0,0.0))
neck_base_location: FloatVectorProperty(name="Location of Base of Spine Neck",default=(0.0,0.0,0.0))
char_mito: BoolProperty(name="Mitochondrion in Bouton",default=False)
exclude: BoolProperty(name="Exclude this spine?", default=False)
contact_type_enum = [
('PLAIN', 'Plain (surface only)', ''),
('PROTRUSION', 'Protrusion (head, neck)', ''),
('VARICOSITY', 'Varicosity (in-line swelling)', '')]
contact_type: EnumProperty(
items=contact_type_enum, name="Contact Type",
description="Type of Contact")
ensheathment_enum = [
('Distant','Distant',''),
('Partial','Partial',''),
('Full','Full','')
]
ensheathment: EnumProperty(items = ensheathment_enum, name="Glial Ensheathment", description='Degree of Glial Ensheathment')
#inner_namestruct_name = bpy.context.scene.volume_analyzer.inner_namestruct_name
#inter_namestruct_name = bpy.context.scene.volume_analyzer.inter_namestruct_name
#outer_namestruct_name = bpy.context.scene.volume_analyzer.outer_namestruct_name
def init_psd(self,context,name):
obj_name = context.active_object.name
'''
dends = bpy.context.scene.test_tool.spine_namestruct_name.replace('#', '[0-9]')
dend_filter = dends
#dend_filter = 'd[0-9]{2}$'
axon_filter = 'a[0-9]{2}$'
if re.match(dend_filter,obj_name) != None:
self.char_postsynaptic = True
elif re.match(axon_filter,obj_name) != None:
self.char_postsynaptic = False
'''
# FIXME: hard code contact to be a Protrusion
self.char_postsynaptic = True
self.contact_type = 'PLAIN'
self.name = name
self.head_name = ""
self.spine_name = ""
self.neck_name = ""
self.volume = 0.0
self.volume_spine = 0.0
self.volume_neck = 0.0
self.area_head = 0.0
self.area_spine = 0.0
self.area_neck = 0.0
self.area_neck_cross_section_abt = 0.0
self.area_neck_cross_section_lbt = 0.0
self.area_psd_az = self.compute_region_area(context,self.name)
self.diameter_neck_max = 0.0
self.diameter_neck_min = 0.0
self.diameter_neck_lbt = 0.0
self.length_neck = 0.0
self.length_neck_lbt = 0.0
self.diameter_head_max = 0.0
self.diameter_head_min = 0.0
self.diameter_head_lbt = 0.0
self.length_head = 0.0
self.length_head_lbt = 0.0
self.compute_psd_az_location(context)
self.neck_top_location = (0.0,0.0,0.0)
self.neck_base_location = (0.0,0.0,0.0)
self.char_mito = False
self.exclude = False
self.ensheathment = 'Distant'
def select_psd(self,context):
# For this spine head, select faces of this PSD:
bpy.data.screens['Default']
obj = context.active_object
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.reveal()
reg = obj.mcell.regions.region_list[self.name]
#if reg != None:
bpy.ops.mesh.select_all(action='DESELECT')
reg.select_region_faces(context)
#else:
def get_region_index(self,context):
active_obj = context.active_object
reg_list = active_obj.mcell.regions.region_list
reg_index = [i for i in range(len(reg_list)) if reg_list[i].name == self.name][0]
return(reg_index)
def compute_region_area(self,context,region_name):
obj = context.active_object
mesh = obj.data
reg = obj.mcell.regions.region_list[region_name]
reg_faces = list(reg.get_region_faces(mesh))
t_mat = obj.matrix_world
area = 0.0
for face_index in reg_faces:
face = mesh.polygons[face_index]
tv0 = mesh.vertices[face.vertices[0]].co * t_mat
tv1 = mesh.vertices[face.vertices[1]].co * t_mat
tv2 = mesh.vertices[face.vertices[2]].co * t_mat
area += mathutils.geometry.area_tri(tv0, tv1, tv2)
# print(" Area of %s with %d faces is %g" % (region_name,len(reg_faces),area))
return(area)
def compute_areas(self,context):
self.area_psd_az = self.compute_region_area(context,self.name)
name = self.name
obj = context.active_object
reg_list = obj.mcell.regions.region_list
region_name = self.name.replace(name, name + '_sph')
if reg_list.get(region_name) != None:
self.area_head = self.compute_region_area(context,region_name)
region_name = self.name.replace(name, name + '_sp')
if reg_list.get(region_name) != None:
self.area_spine = self.compute_region_area(context,region_name)
region_name = self.name.replace(name, name + '_spn')
if reg_list.get(region_name) != None:
self.area_neck = self.compute_region_area(context,region_name)
region_name = self.name.replace('cs','axb')
if reg_list.get(region_name) != None:
self.area_head = self.compute_region_area(context,region_name)
def compute_psd_az_location(self,context):
obj = context.active_object
mesh = obj.data
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_mode(type='VERT')
self.select_psd(context)
bpy.ops.object.mode_set(mode='OBJECT')
psd_az_verts = [v.co for v in mesh.vertices if v.select == True]
av = [0,0,0]
for v in psd_az_verts:
av[0] += v[0]
av[1] += v[1]
av[2] += v[2]
av[0] = av[0]/len(psd_az_verts)
av[1] = av[1]/len(psd_az_verts)
av[2] = av[2]/len(psd_az_verts)
self.psd_az_location = av.copy()
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_mode(type='FACE')
bpy.ops.object.mode_set(mode='OBJECT')
def select_spn(self, context):
# For this spine head, select faces of this PSD:
obj = context.active_object
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='DESELECT')
reg = obj.mcell.regions.region_list[self.neck_name]
reg.select_region_faces(context)
def select_sph(self, context):
# For this spine head, select faces of this PSD:
obj = context.active_object
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='DESELECT')
reg = obj.mcell.regions.region_list[self.head_name]
reg.select_region_faces(context)
def calculate_diameter(self, context):
self.select_spn(context)
mesh = context.active_object.data
old_to_new_index = dict()
selected_vertices = list()
selected_faces = list()
required_vertices = set()
for face in mesh.polygons:
if face.select:
required_vertices.add(face.vertices[0])
required_vertices.add(face.vertices[1])
required_vertices.add(face.vertices[2])
for i, vertex in enumerate(mesh.vertices):
if i in required_vertices:
old_to_new_index[i] = len(selected_vertices)
selected_vertices.append(vertex)
for face in mesh.polygons:
if face.select:
newa = old_to_new_index[face.vertices[0]] + 1
newb = old_to_new_index[face.vertices[1]] + 1
newc = old_to_new_index[face.vertices[2]] + 1
selected_faces.append((newa, newb, newc))
cwd = bpy.path.abspath(os.path.dirname(__file__))
tmp_obj = cwd + "/tmp.obj"
# exe = bpy.path.abspath(cwd + "/calc_diameter")
cmd = os.path.join(os.path.dirname(__file__), 'bin', 'calc_diameter')
with open(tmp_obj, "w+") as of:
for vertex in selected_vertices:
of.write("v %f %f %f\n" % (vertex.co.x, vertex.co.y, vertex.co.z))
for p1, p2, p3 in selected_faces:
of.write("f %d %d %d\n" % (p1, p2, p3))
subprocess.call([cmd, tmp_obj, cwd + "/"])
# [1:] means ignore the first row "# Segments: N"
diam_fn = cwd + "/tmp_diameters.txt"
#metrics = [line.split() for line in open(diam_fn)][1:]
sort = []
for line in open(diam_fn):
metrics = line.strip()
sort.append(metrics)
sort = sort[1:]
len_sort = len(sort)
#val = (len_sort/2)-1
sort.sort(reverse=True)
max_diameter = sort[0]
min_diameter = sort[-1]
#middle_seg = sort[int(val)]
#print(middle_seg)
self.diameter_neck_max = float(max_diameter)
self.diameter_neck_min = float(min_diameter)
def calculate_diameter_head(self, context):
self.select_sph(context)
mesh = context.active_object.data
old_to_new_index = dict()
selected_vertices = list()
selected_faces = list()
required_vertices = set()
for face in mesh.polygons:
if face.select:
required_vertices.add(face.vertices[0])
required_vertices.add(face.vertices[1])
required_vertices.add(face.vertices[2])
for i, vertex in enumerate(mesh.vertices):
if i in required_vertices:
old_to_new_index[i] = len(selected_vertices)
selected_vertices.append(vertex)
for face in mesh.polygons:
if face.select:
newa = old_to_new_index[face.vertices[0]] + 1
newb = old_to_new_index[face.vertices[1]] + 1
newc = old_to_new_index[face.vertices[2]] + 1
selected_faces.append((newa, newb, newc))
cwd = bpy.path.abspath(os.path.dirname(__file__))
tmp_obj = cwd + "/tmp.obj"
# exe = bpy.path.abspath(cwd + "/calc_diameter")
cmd = os.path.join(os.path.dirname(__file__), 'bin', 'calc_diameter')
with open(tmp_obj, "w+") as of:
for vertex in selected_vertices:
of.write("v %f %f %f\n" % (vertex.co.x, vertex.co.y, vertex.co.z))
for p1, p2, p3 in selected_faces:
of.write("f %d %d %d\n" % (p1, p2, p3))
subprocess.call([cmd, tmp_obj, cwd + "/"])
# [1:] means ignore the first row "# Segments: N"
diam_fn = cwd + "/tmp_diameters.txt"
#metrics = [line.split() for line in open(diam_fn)][1:]
sort = []
for line in open(diam_fn):
metrics = line.strip()
sort.append(metrics)
sort = sort[1:]
len_sort = len(sort)
#val = (len_sort/2)-1
sort.sort(reverse=True)
max_diameter = sort[0]
min_diameter = sort[-1]
#middle_seg = sort[int(val)]
#print(middle_seg)
self.diameter_head_max = float(max_diameter)
self.diameter_head_min = float(min_diameter)
def compute_neck_stats(self, context):
obj = context.active_object
if self.volume_neck > 0.0:
name = self.name
spine_name = self.name.replace(name, name + '_sp')
head_name = self.name.replace(name, name + '_sph')
# Estimate neck length and diameter from neck volume and neck cross section areas
neck_top_loc, area_spine_neck_boundary = self.compute_neck_boundary_area(context,spine_name)
neck_base_loc, area_head_neck_boundary = self.compute_neck_boundary_area(context,head_name)
self.neck_top_location = neck_top_loc
self.neck_base_location = neck_base_loc
self.area_neck_cross_section_abt = (area_spine_neck_boundary + area_head_neck_boundary)/2.0
self.diameter_neck = 2*np.sqrt(self.area_neck_cross_section_abt/np.pi)
self.length_neck = self.volume_neck/self.area_neck_cross_section_abt
# Estimate neck diameter from neck volume and neck length from base to top
neck_axis = np.array(self.neck_base_location)-np.array(self.neck_top_location)
self.length_neck_lbt = np.linalg.norm(neck_axis)
self.area_neck_cross_section_lbt = self.volume_neck/self.length_neck_lbt
self.diameter_neck_lbt = 2*np.sqrt(self.area_neck_cross_section_lbt/np.pi)
print('spine_neck area:',area_spine_neck_boundary)
print('head_neck area:',area_head_neck_boundary)
print('avg neck cross section area:',self.area_neck_cross_section_abt)
print('neck diameter:',self.diameter_neck)
print('neck length:',self.length_neck)
print('len_bt neck cross section area:',self.area_neck_cross_section_lbt)
print('len_bt neck diameter:',self.diameter_neck_lbt)
print('neck length base to top:',self.length_neck_lbt)
def compute_neck_boundary_area(self, context, reg_name):
orig_obj = context.active_object
reg = orig_obj.mcell.regions.region_list[reg_name]
# Enter edit mode and unhide and deselect mesh
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='DESELECT')
# Select the region
reg.select_region_faces(context)
#duplicate region as new object
bpy.ops.mesh.duplicate()
#separate object from original
bpy.ops.mesh.separate(type = 'SELECTED')
# Unhide and deselect mesh and exit edit mode
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_mode(type='EDGE')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
#deselect original object
orig_obj.select_set(False)
#define and name duplicated object
dup_obj = bpy.context.selected_objects[0]
dup_obj.name = reg_name + '_tmp_boundary'
dup_obj.data.name = dup_obj.name
#make dup_obj active
scn = bpy.context.scene
bpy.context.view_layer.objects.active = dup_obj
#extract non-manifold boundary of dup_obj
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_mode(type='EDGE')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_non_manifold()
bpy.ops.mesh.select_all(action='INVERT')
bpy.ops.mesh.delete(type='EDGE')
bpy.ops.mesh.select_mode(type='VERT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.object.mode_set(mode='OBJECT')
# Now project the boundary onto its principle plane
# Get the mesh vertices
mesh = dup_obj.data
verts = mesh.vertices
bnd_verts = np.array([v.co for v in verts])
# Do PCA on the vertices
covm = np.cov(bnd_verts,rowvar=0)
eigval, eigvec = np.linalg.eig(covm)
# Take the top to two principle component vectors
r = np.sqrt(eigval)
r = sorted(list(enumerate(r)),key=lambda l: l[1], reverse=True)
pcv = []
for i in range(len(r)-1):
pcv.append(r[i][1]*eigvec[:,r[i][0]])
# Define the normal vector of the principle plane as
# the cross product of the two principle vectors
nvec = np.cross(pcv[0],pcv[1])
nvec = nvec/np.linalg.norm(nvec)
# Project the boundary vertices onto the principle plane
bnd_centroid = bnd_verts.mean(axis=0)
for i in range(len(bnd_verts)):
p = bnd_verts[i]
v = p - bnd_centroid
p_proj = p - np.dot(v,nvec)*nvec
verts[i].co.x = p_proj[0]
verts[i].co.y = p_proj[1]
verts[i].co.z = p_proj[2]
# verts.add(1)
# verts[-1].co = p_proj
# Make planar polygon out of the projected boundary
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.edge_face_add()
bpy.ops.object.mode_set(mode='OBJECT')
# Extract the boundary vertices in polygonal order
pverts = []
poly = mesh.polygons[0]
for vi in poly.vertices:
pverts.append(verts[vi].co)
# measure the area of the boundary cross section polygon
area = abs(self.area_3D_polygon(pverts, nvec))
# We're done so now delete boundary object and mesh
dup_obj.select_set(False)
bpy.context.scene.collection.children[0].objects.unlink(dup_obj)
bpy.data.objects.remove(dup_obj)
bpy.data.meshes.remove(mesh)
#reselect original object
bpy.context.view_layer.objects.active = orig_obj
orig_obj.select_set(True)
return(list(bnd_centroid), area)
def compute_normal_from_boundary(self, context, reg_name=None):
# Given a non-closed object of name of a non-closed surface region on
# an object, compute the normal vector of the best principle plane
# passing through the boundary of the region
orig_obj = context.active_object
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='DESELECT')
if reg_name:
reg = orig_obj.mcell.regions.region_list[reg_name]
# Enter edit mode and unhide and deselect mesh
# Select the region
reg.select_region_faces(context)
tmp_obj_name = reg_name + '_tmp_boundary'
else:
bpy.ops.mesh.select_all(action='SELECT')
tmp_obj_name = orig_obj.name + '_tmp_boundary'
#duplicate region as new object
bpy.ops.mesh.duplicate()
#separate object from original
bpy.ops.mesh.separate(type = 'SELECTED')
# Unhide and deselect mesh and exit edit mode
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_mode(type='EDGE')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
#deselect original object
orig_obj.select_set(False)
#define and name duplicated object
dup_obj = bpy.context.selected_objects[0]
dup_obj.name = tmp_obj_name
dup_obj.data.name = dup_obj.name
#make dup_obj active
scn = bpy.context.scene
bpy.context.view_layer.objects.active = dup_obj
# Compute centroid of object
mesh = dup_obj.data
verts = mesh.vertices
v_array = np.array([v.co for v in verts])
v_centroid = v_array.mean(axis=0)
#extract non-manifold boundary of dup_obj
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_mode(type='EDGE')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_non_manifold()
bpy.ops.mesh.select_all(action='INVERT')
bpy.ops.mesh.delete(type='EDGE')
bpy.ops.mesh.select_mode(type='VERT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.object.mode_set(mode='OBJECT')
# Now find the principle plane of the boundary
# Get the boundary vertices and compute centroid
mesh = dup_obj.data
verts = mesh.vertices
bnd_verts = np.array([v.co for v in verts])
bnd_centroid = bnd_verts.mean(axis=0)
# Do PCA on the vertices
covm = np.cov(bnd_verts,rowvar=0)
eigval, eigvec = np.linalg.eig(covm)
# Take the top to two principle component vectors
r = np.sqrt(eigval)
r = sorted(list(enumerate(r)),key=lambda l: l[1], reverse=True)
pcv = []
for i in range(len(r)-1):
pcv.append(r[i][1]*eigvec[:,r[i][0]])
# Define the normal vector of the principle plane as
# the cross product of the two principle vectors
# Orient the vector to point toward the centroid of the object
nvec = np.cross(pcv[0],pcv[1])
nvec = nvec/np.linalg.norm(nvec)
objvec = v_centroid - bnd_centroid
objvec = objvec/np.linalg.norm(objvec)
nvec = np.sign(nvec.dot(objvec))*nvec
# Convert nvec and bnd_centroid to list
nvec = list(nvec)
bnd_centroid = list(bnd_centroid)
# We're done so now delete boundary object and mesh