-
Notifications
You must be signed in to change notification settings - Fork 13
/
_CATMAIDImport2.79.py
12440 lines (10210 loc) · 612 KB
/
_CATMAIDImport2.79.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
"""
CATMAID to Blender Import Script - connects to CATMAID servers and retrieves
skeleton data
Copyright (C) 2014 Philipp Schlegel
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 3 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, see <http://www.gnu.org/licenses/>.
"""
import ssl
# Uncomment this if you're having problems with SSL certificate of your CATMAID server
# NOT recommended!
safe_ssl = ssl._create_default_https_context
unsafe_ssl = ssl._create_unverified_context
#ssl._create_default_https_context = ssl._create_unverified_context
import asyncio
import base64
import bpy
import blf
import colorsys
import copy
import concurrent.futures
import datetime
import http.cookiejar as cj
import json
import math
import mathutils
import numpy as np
import os
import random
import re
import statistics
import sys
import threading
import time
import urllib
# Use requests if possible
try:
import requests
from requests.exceptions import HTTPError
print('requests library found')
except:
requests = None
from urllib.error import HTTPError
print('requests library not found - falling back to urllib')
try:
from scipy.spatial import distance
from scipy import cluster
except:
print('Unable to import SciPy. Some functions will not work!')
try:
import matplotlib.pyplot as plt
import pylab
except:
print('Unable to import matplotlib. Some functions will not work!')
from bpy.types import Operator, AddonPreferences
from bpy_extras.io_utils import ImportHelper, ExportHelper
from bpy.props import FloatVectorProperty, FloatProperty, StringProperty, BoolProperty, EnumProperty, IntProperty, CollectionProperty
remote_instance = None
connected = False
#bl_info holds plugin info
bl_info = {
"name": "CATMAIDImport",
"author": "Philipp Schlegel",
"version": (6, 2, 2),
"for_catmaid_version": '2018.11.09-254-g70f32ec',
"blender": (2, 7, 9),
"location": "Properties > Scene > CATMAID Import",
"description": "Imports Neuron from CATMAID server, Analysis tools, Export to SVG",
"warning": "",
"wiki_url": "",
"tracker_url": "",
"category": "Object"}
class CATMAIDimportPanel(bpy.types.Panel):
"""Creates Import Menu in Properties -> Scene """
bl_label = "CATMAID Import"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "scene"
def draw(self, context):
layout = self.layout
#Version check panel
config = bpy.data.scenes[0].CONFIG_VersionManager
layout.label(text="Your Blender Script Version: %s" % config.current_version)
if config.latest_version == 'NA':
layout.label(text="On Github: Please Connect...")
else:
layout.label(text="On Github: %s" % config.latest_version)
layout.label(text="Tested for CATMAID Version: %s" % config.tested_catmaid_version)
if config.your_catmaid_server == "":
layout.label(text="Your CATMAID Server: Please Connect...")
else:
layout.label(text="Your CATMAID Server: %s" % config.your_catmaid_server)
if not compare_version(config.current_version, config.last_stable_version):
layout.label(text="Your are behind the last working", icon = 'ERROR')
layout.label(text=" version of the Script!")
layout.label(text="Please Download + Replace with the")
layout.label(text="latest Version of CATMAIDImport.py:")
layout.label(text="https://github.com/schlegelp/CATMAID-to-Blender")
elif not compare_version(config.current_version, config.latest_version) and config.new_features != '':
layout.label(text="New Features in Latest Version: %s" % config.new_features)
if config.your_catmaid_server != 'Please connect...' and config.your_catmaid_server != config.tested_catmaid_version:
layout.label(text="Your server is running a version of CATMAID", icon = 'ERROR')
layout.label(text=" that may not be supported!")
if config.message != '':
print('Message from Github: %s' % config.message)
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("check.version", text = "Check Versions", icon ='VISIBLE_IPO_ON')
layout.label('CATMAID Import:')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("connect.to_catmaid", text = "Connect 2 CATMAID", icon = 'PLUGIN')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("retrieve.neuron", text = "Import Neuron(s)", icon = 'ARMATURE_DATA')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("retrieve.partners", text = "Retrieve Partners", icon = 'AUTOMERGE_ON')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("retrieve.by_pairs", text = "Retrieve Paired", icon = 'MOD_ARRAY')
row.operator("display.help", text = "", icon ='QUESTION').entry = 'retrieve.by_pairs'
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("retrieve.in_volume", text = "Retrieve in Volume", icon = 'BBOX')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("reload.neurons", text = "Reload Neurons", icon = 'FILE_REFRESH')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("retrieve.connectors", text = "Retrieve Connectors", icon = 'PMARKER_SEL')
row.operator("display.help", text = "", icon ='QUESTION').entry = 'retrieve.connectors'
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("retrieve.tags", text = "Retrieve Tags", icon = 'SYNTAX_OFF')
layout.label('Materials:')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("change.material", text = "Change Materials", icon ='COLOR_BLUE')
row.operator("display.help", text = "", icon ='QUESTION').entry = 'change.material'
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("random.all_materials", text = "Randomize Color", icon ='COLOR')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("color.by_spatial", text = "By Spatial Distr.", icon ='ROTATECENTER')
row.operator("display.help", text = "", icon ='QUESTION').entry = 'color.by_spatial'
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("color.by_annotation", text = "By Annotation", icon ='SORTALPHA')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("color.by_synapse_count", text = "By Synapse Count", icon ='IPO_QUART')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("color.by_pairs", text = "By Pairs", icon ='MOD_ARRAY')
row.operator("display.help", text = "", icon ='QUESTION').entry = 'color.by_pairs'
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("color.by_strahler", text = "By Strahler Index", icon ='MOD_ARRAY')
row.operator("display.help", text = "", icon ='QUESTION').entry = 'color.by_strahler'
layout.label(text="Export to SVG:")
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("exportall.to_svg", text = 'Export Morphology', icon = 'EXPORT')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("connectors.to_svg", text = 'Export Connectors', icon = 'EXPORT')
layout.label('Select:')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("select.by_annotation", text = 'By Annotation', icon = 'BORDER_RECT')
layout.label('Analyze:')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("analyze.statistics", text = 'Get Statistics', icon = 'FILE_TICK')
layout.label('Calculate Similarity:')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator_context = 'INVOKE_DEFAULT'
row.operator("calc.similarity_modal", text = "Start Calculation", icon ='PARTICLE_PATH')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("calc.similarity_modal_settings", text = "Settings", icon ='MODIFIER')
row.operator("display.help", text = "", icon ='QUESTION').entry = 'color.by_similarity'
layout.label('Volumes:')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("export.volume", text = 'Export Mesh', icon = 'EXPORT')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("import.volume", text = 'Import Volume', icon = 'IMPORT')
layout.label('Animate:')
row = layout.row(align=True)
row.alignment = 'EXPAND'
row.operator("animate.history", text = 'History', icon = 'OUTLINER_DATA_CAMERA')
row.operator("display.help", text = "", icon ='QUESTION').entry = 'animate.history'
class VersionManager(bpy.types.PropertyGroup):
"""Class to hold version related properties
"""
current_version = bpy.props.StringProperty(name="Your Script Version", default="NA", description="Current Version of the Script you are using")
latest_version = bpy.props.StringProperty(name="Latest Version", default="NA", description="Latest Version on Github")
last_stable_version = bpy.props.StringProperty(name="Last Stable Version", default="NA", description="Last Stable Version of the Script")
message = bpy.props.StringProperty(name="Message", default="", description="Message from Github")
new_features = bpy.props.StringProperty(name="New Features", default="", description="New features in latest Version of the Script on Github")
your_catmaid_server = bpy.props.StringProperty(name="Your CATMAID Server Version", default='', description="Your CATMAID Server's Version")
tested_catmaid_version = bpy.props.StringProperty(name="Last tested CATMAID Version", default='', description="Last Version confirmed to Work with this Blender")
def compare_version(A, B):
""" Compare versions A and B. Returns True if version A >= B.
"""
# If any version is "NA" or None or "None", return False
if A in ['NA', None, 'None', ''] or B in ['NA', None, 'None', '']:
return False
try:
# Extract numerical versions from strings
if isinstance(A, str):
A = [int(v) for v in A.split('.')]
if isinstance(B, str):
B = [int(v) for v in B.split('.')]
except:
print('Version comparison failed:', A, B)
return False
# Make sure A and B match in length
A += [0] * max((len(B)-len(A)), 0)
B += [0] * max((len(A)-len(B)), 0)
for a,b in zip(A, B):
if a > b:
return True
elif a == b:
continue
elif a < b:
return False
# If they match exactly return True
return True
class get_version_info(Operator):
"""
Operator for Checking Addon Version on Github. Will be called when connection to CATMAID servers is attempted or when button 'check version' is invoked.
"""
bl_idname = "check.version"
bl_label = "Check Version on Github"
def execute(self, context):
self.check_version()
return{'FINISHED'}
def check_version(context):
#Read current version from bl_info and convert from tuple into float
print('Checking Version on Github...')
current_version = '.'.join([str(v) for v in bl_info['version']])
print('Current version of the Script: ', current_version)
try:
update_url = 'https://raw.githubusercontent.com/schlegelp/CATMAID-to-Blender/master/update.txt'
update_file = urllib.request.urlopen(update_url)
file_content = update_file.read().decode("utf-8")
latest_version = re.search('current_version.*?{(.*?)}',file_content).group(1)
last_stable = re.search('last_stable.*?{(.*?)}', file_content).group(1)
new_features = re.search('new_features.*?{(.*?)}',file_content).group(1)
message = re.search('message.*?{(.*?)}',file_content).group(1)
print('Latest version on Github: ', latest_version)
print('Last stable version: ', last_stable)
except:
print('Error fetching info on latest version')
#self.report({'ERROR'}, 'Error fetching latest info')
latest_version = 'NA'
last_stable = 'NA'
new_features = ''
message = ''
tested_catmaid_version = bl_info['for_catmaid_version']
print('This Script was tested with CATMAID Server Version: ', tested_catmaid_version)
try:
your_catmaid_server = remote_instance.fetch( remote_instance.djangourl('/version') )['SERVER_VERSION']
print('You are running CATMAID Server Version: ', your_catmaid_server)
except:
your_catmaid_server = 'Please connect...'
config = bpy.data.scenes[0].CONFIG_VersionManager
config.current_version = current_version
config.latest_version = latest_version
config.last_stable_version = last_stable
config.message = message
config.new_features = new_features
config.tested_catmaid_version = tested_catmaid_version
config.your_catmaid_server = your_catmaid_server
class CatmaidInstance:
""" A class giving access to a CATMAID instance.
"""
def __init__(self, server, authname, authpassword, authtoken):
self.server = server
self.authname = authname
self.authpassword = authpassword
self.authtoken = authtoken
self.opener = urllib.request.build_opener(urllib.request.HTTPRedirectHandler())
self._session = None
if requests:
self._session = requests.Session()
self._session.headers['X-Authorization'] = 'Token ' + authtoken
self._session.auth = (authname, authpassword)
def djangourl(self, path):
""" Expects the path to lead with a slash '/'. """
return self.server + path
def auth(self, request):
if self.authname:
base64string = base64.encodestring(('%s:%s' % (self.authname, self.authpassword)).encode()).decode().replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
if self.authtoken:
request.add_header("X-Authorization", "Token {}".format(self.authtoken))
def fetch(self, url, post=None):
""" Requires the url to connect to and the variables for POST, if any, in a dictionary."""
if self._session:
if post:
r = self._session.post(url, data=post)
else:
r = self._session.get(url)
# Check for errors
if r.status_code != 200:
# CATMAID internal server errors return useful error messages
if str(r.status_code).startswith('5'):
# Try extracting error:
try:
msg = r.json().get('error', 'No error message.')
det = r.json().get('detail', None)
except BaseException:
msg = r.reason
det = None
# Parse all other errors
else:
msg = r.reason
det = None
error = '{} Server Error: {} for url "{}"'.format(r.status_code,
msg,
r.url)
if det:
error += '. See above for details.'
print('Error details: {}'.format(det))
raise HTTPError(error)
return r.json()
else:
if post:
data = urllib.parse.urlencode(post)
data = data.encode('utf-8')
#If experiencing issue with [SSL: CERTIFICATE_VERIFY_FAILED] -> set unverifiable to True
#Warning: This makes the connection insecure!
r = urllib.request.Request(url, data=data, unverifiable=False)
else:
r = urllib.request.Request(url)
self.auth(r)
response = self.opener.open(r)
return json.loads(response.read().decode("utf-8"))
#Use to parse url for retrieving stack infos
def get_stack_info_url(self, pid, sid):
return self.djangourl("/" + str(pid) + "/stack/" + str(sid) + "/info")
#Use to parse url for retrieving skeleton nodes (no info on parents or synapses, does need post data)
def get_skeleton_nodes_url(self, pid):
return self.djangourl("/" + str(pid) + "/treenode/table/list")
#Use to parse url for retrieving connectivity (does need post data)
def get_connectivity_url(self, pid):
return self.djangourl("/" + str(pid) + "/skeletons/connectivity" )
#Use to parse url for retrieving info connectors (does need post data)
def get_connector_details_url(self, pid):
return self.djangourl("/" + str(pid) + "/connector/skeletons" )
#Use to parse url for retrieving info connectors (does need GET data)
def get_connectors_url(self, pid):
return self.djangourl("/" + str(pid) + "/connectors/" )
#Use to parse url for names for a list of skeleton ids (does need post data: pid, skid)
def get_neuronnames(self, pid):
return self.djangourl("/" + str(pid) + "/skeleton/neuronnames" )
#Get user list for project
def get_user_list_url(self):
return self.djangourl("/user-list" )
#Use to parse url for a SINGLE neuron (will also give you neuronid)
def get_single_neuronname(self, pid, skid):
return self.djangourl("/" + str(pid) + "/skeleton/" + str(skid) + "/neuronname" )
#Use to get skeletons review status
def get_review_status(self, pid):
return self.djangourl("/" + str(pid) + "/skeletons/review-status" )
#Use to get annotations for given neuron. DOES need skid as postdata
def get_neuron_annotations(self, pid):
return self.djangourl("/" + str(pid) + "/annotations/table-list" )
"""
ATTENTION!!!!: This does not seem to work anymore as of 20/10/2015 -> although it still exists in CATMAID code
use get_annotations_for_skid_list2
"""
#Use to get annotations for given neuron. DOES need skid as postdata
def get_annotations_for_skid_list(self, pid):
return self.djangourl("/" + str(pid) + "/annotations/skeletons/list" )
"""
!!!!
"""
#Does need postdata
def list_skeletons(self, pid):
return self.djangourl("/" + str(pid) + "/skeletons" )
#Use to get annotations for given neuron. DOES need skid as postdata
def get_annotations_for_skid_list2(self, pid):
return self.djangourl("/" + str(pid) + "/skeleton/annotationlist" )
#Use to parse url for retrieving list of all annotations (and their IDs!!!) (does NOT need post data)
def get_annotation_list(self, pid):
return self.djangourl("/" + str(pid) + "/annotations/" )
#Use to parse url for retrieving contributor statistics for given skeleton (does NOT need post data)
def get_contributions_url(self, pid, skid):
return self.djangourl("/" + str(pid) + "/skeleton/" + str(skid) + "/contributor_statistics" )
#Use to parse url for retrieving neurons with given annotation or name (does need post data)
def get_annotated_url(self, pid):
#return self.djangourl("/" + str(pid) + "/neuron/query-by-annotations" )
return self.djangourl("/" + str(pid) + "/annotations/query-targets" )
#Use to parse url for retrieving list of nodes (needs post data)
def get_node_list(self, pid):
return self.djangourl("/" + str(pid) + "/node/list" )
#Use to parse url for retrieving all info the 3D viewer gets (does NOT need post data)
#Returns, in JSON, [[nodes], [connectors], [tags]], with connectors and tags being empty when 0 == with_connectors and 0 == with_tags, respectively
def get_compact_skeleton_url(self, pid, skid, connector_flag = 1, tag_flag = 1):
return self.djangourl("/" + str(pid) + "/" + str(skid) + "/" + str(connector_flag) + "/" + str(tag_flag) + "/compact-skeleton")
def get_compact_details_url(self, pid, skid):
""" Similar to compact-skeleton but if 'with_history':True is passed as GET request, returned data will include all positions a nodes/connector has ever occupied plus the creation time and last modified.
"""
return self.djangourl("/" + str(pid) + "/skeletons/" + str(skid) + "/compact-detail")
#The difference between this function and the compact_skeleton function is that
#the connectors contain the whole chain from the skeleton of interest to the
#partner skeleton: contains [treenode_id, confidence_to_connector, connector_id, confidence_from_connector, connected_treenode_id, connected_skeleton_id, relation1, relation2]
#relation1 = 1 means presynaptic (this neuron is upstream), 0 means postsynaptic (this neuron is downstream)
def get_compact_arbor_url(self, pid, skid, nodes_flag = 1, connector_flag = 1, tag_flag = 1):
return self.djangourl("/" + str(pid) + "/" + str(skid) + "/" + str(nodes_flag) + "/" + str(connector_flag) + "/" + str(tag_flag) + "/compact-arbor")
#Use to parse url for retrieving edges between given skeleton ids (does need postdata)
#Returns list of edges: [source_skid, target_skid, weight]
def get_edges_url(self, pid):
return self.djangourl("/" + str(pid) + "/skeletongroup/skeletonlist_confidence_compartment_subgraph" )
def search_url(self,tag,pid):
return self.djangourl("/" + str(pid) + "/search?pid=" + str(pid) + "&substring=" + str(tag) )
#Use to get all skeletons of a given neuron (neuron_id)
def get_skeletons_from_neuron_id(self,neuron_id,pid):
return self.djangourl("/" + str(pid) + "/neuron/" + str(neuron_id) + '/get-all-skeletons' )
#Use to parse url for adding volumes
def add_volume(self, pid):
return self.djangourl("/" + str(pid) + "/volumes/add")
#Get list of all volumes in project
def get_volumes(self, pid):
return self.djangourl("/" + str(pid) + "/volumes/")
#Get details on a given volume
def get_volume_details(self, pid, volume_id):
return self.djangourl("/" + str(pid) + "/volumes/" + str(volume_id) )
def get_list_skeletons_url(self, pid):
""" Use to parse url for names for a list of skeleton ids (works with GET).
"""
return self.djangourl("/" + str(pid) + "/skeletons/")
def get_review_details_url(self, pid, skid):
""" Use to retrieve review status for every single node of a skeleton.
For some reason this needs to be fetched as POST (even though actual POST data is not necessary)
Returns list of arbors, the nodes contained and who has been reviewing them at what time
"""
return self.djangourl("/" + str(pid) + "/skeletons/" + str(skid) + "/review")
def get_review_details(x, remote_instance=None, max_threads=None):
""" Retrieve review status (reviewer + timestamp) for each node
of a given skeleton. Uses the review API.
Parameters
-----------
x : {int, str, CatmaidNeuron, CatmaidNeuronList, DataFrame}
Your options are either::
1. int or list of ints will be assumed to be skeleton IDs
2. str or list of str:
- if convertible to int, will be interpreted as x
- elif start with 'annotation:' will be assumed to be
annotations
- else, will be assumed to be neuron names
3. For CatmaidNeuron/List or pandas.DataFrames will try
to extract skeleton_id parameter
Returns
-------
dict
{ 'skid1' : [ (node_id,
most_recent_reviewer_login,
most_recent_review_datetime),
...],
'skid2' : ... }
"""
if remote_instance is None:
if 'remote_instance' in globals():
remote_instance = globals()['remote_instance']
else:
print('Please either pass a CATMAID instance or define globally as "remote_instance" ')
return
if not isinstance(x, (list, np.ndarray, set)):
x = [x]
urls = []
post_data = []
for s in x:
urls.append(remote_instance.get_review_details_url(project_id, s))
# For some reason this needs to fetched as POST (even though actual
# POST data is not necessary)
post_data.append({'placeholder': 0})
rdata = get_urls_threaded(urls, post_data, max_threads)
user_list = remote_instance.fetch( remote_instance.get_user_list_url() )
user_list = { k['id'] : k for k in user_list}
last_reviewer = {}
for i, neuron in enumerate(rdata):
this_neuron = []
for arbor in neuron:
this_neuron += [ (n['id'],
user_list[n['rids'][0][0]]['login'],
datetime.datetime.strptime(n['rids'][0][1][:16], '%Y-%m-%dT%H:%M'))
for n in arbor['sequence'] if n['rids']]
last_reviewer[x[i]] = this_neuron
return last_reviewer
def eval_skids(x):
""" Wrapper to evaluate parameters passed as skeleton IDs. Will turn
annotations and neuron names into skeleton IDs.
Parameters
----------
x : {int, str, CatmaidNeuron, CatmaidNeuronList, DataFrame}
Your options are either::
1. int or list of ints will be assumed to be skeleton IDs
2. str or list of str:
- if convertible to int, will be interpreted as x
- elif start with 'annotation:' will be assumed to be
annotations
- else, will be assumed to be neuron names
3. For CatmaidNeuron/List or pandas.DataFrames will try
to extract skeleton_id parameter
remote_instance : CatmaidInstance, optional
Returns
-------
list of str
list containing skeleton IDs as strings
"""
if ',' in x:
x = x.split(',')
if isinstance(x, (int, np.int64, np.int32, np.int)):
return [ str(x) ]
elif isinstance(x, (str, np.str)):
try:
int(x)
return [ str(x) ]
except:
if x.startswith('annotation:'):
return search_annotations(x[11:])
elif x.startswith('name:'):
return search_neuron_names(x[5:],allow_partial=False).skeleton_id.tolist()
else:
return search_neuron_names(x, allow_partial=False).skeleton_id.tolist()
elif isinstance(x, (list, np.ndarray)):
skids = []
for e in x:
temp = eval_skids(e)
if isinstance(temp, (list, np.ndarray)):
skids += temp
else:
skids.append(temp)
return list(set(skids))
else:
remote_instance.logger.error(
'Unable to extract x from type %s' % str(type(x)))
raise TypeError('Unable to extract x from type %s' % str(type(x)))
def search_neuron_names(tag, allow_partial = True):
""" Searches for neuron names. Returns a list of skeleton ids.
"""
search_url = remote_instance.get_annotated_url( project_id )
annotation_post = { 'name': str(tag) , 'rangey_start': 0, 'range_length':500, 'with_annotations':False }
results = remote_instance.fetch( search_url, annotation_post )
match = []
for e in results['entities']:
if allow_partial and e['type'] == 'neuron' and tag.lower() in e['name'].lower():
match += e['skeleton_ids']
if not allow_partial and e['type'] == 'neuron' and e['name'] == tag:
match += e['skeleton_ids']
return list( set(match) )
def search_annotations(annotations_to_retrieve, allow_partial=False, intersect=False):
""" Searches for annotations, returns list of skeleton IDs
"""
### Get annotation IDs
osd.show("Looking for Annotations...")
print('Looking for Annotations:', annotations_to_retrieve)
#bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)
print('Retrieving list of Annotations...')
an_list = remote_instance.fetch( remote_instance.get_annotation_list( project_id ) )
print('List of %i annotations retrieved.' % len(an_list['annotations']))
annotation_ids = []
annotation_names = []
if not allow_partial:
annotation_ids = [ x['id'] for x in an_list['annotations'] if x['name'] in annotations_to_retrieve ]
annotation_names = [ x['name'] for x in an_list['annotations'] if x['name'] in annotations_to_retrieve ]
else:
annotation_ids = [ x['id'] for x in an_list['annotations'] if True in [ y.lower() in x['name'].lower() for y in annotations_to_retrieve ] ]
annotation_names = [ x['name'] for x in an_list['annotations'] if True in [ y.lower() in x['name'].lower() for y in annotations_to_retrieve ] ]
if not annotation_ids:
return []
#Now retrieve annotated skids
print('Looking for Annotation(s) | %s | (id: %s)' % ( str(annotation_names), str(annotation_ids) ) )
#annotation_post = {'neuron_query_by_annotation': annotation_id, 'display_start': 0, 'display_length':500}
if intersect:
annotation_post = { 'rangey_start': 0, 'range_length':500, 'with_annotations':False }
for i,e in enumerate(annotation_ids):
key = 'annotated_with[%i]' % i
annotation_post[key] = e
remote_annotated_url = remote_instance.get_annotated_url( project_id )
neuron_list = [ str(n['skeleton_ids'][0]) for n in remote_instance.fetch( remote_annotated_url, annotation_post )['entities'] if n['type'] == 'neuron' ]
else:
neuron_list = []
for e in annotation_ids:
annotation_post = { 'annotated_with[0]': e, 'rangey_start': 0, 'range_length':500, 'with_annotations':False }
remote_annotated_url = remote_instance.get_annotated_url( project_id )
neuron_list += [ str(n['skeleton_ids'][0]) for n in remote_instance.fetch( remote_annotated_url, annotation_post )['entities'] if n['type'] == 'neuron' ]
annotated_skids = list(set(neuron_list))
print('Annotation(s) found for %i neurons' % len(annotated_skids))
neuron_names = get_neuronnames(annotated_skids)
return annotated_skids
def retrieve_skeleton_list( user=None, node_count=1, start_date=[], end_date=[], reviewed_by = None ):
""" Wrapper to retrieves a list of all skeletons that fit given parameters (see variables). If no parameters are provided, all existing skeletons are returned.
Parameters:
----------
remote_instance : class
Your CATMAID instance; either pass directly to function or define globally as 'remote_instance'.
user : integer
A single user_id.
node_count : integer
Minimum number of nodes.
start_date : list of integers [year, month, day]
Only consider neurons created after.
end_date : list of integers [year, month, day]
Only consider neurons created before.
Returns:
-------
skid_list : list of skeleton ids
"""
get_skeleton_list_GET_data = {'nodecount_gt':node_count}
if user:
get_skeleton_list_GET_data['created_by'] = user
if reviewed_by:
get_skeleton_list_GET_data['reviewed_by'] = reviewed_by
if start_date and end_date:
get_skeleton_list_GET_data['from'] = ''.join( [ str(d) for d in start_date ] )
get_skeleton_list_GET_data['to'] = ''.join( [ str(d) for d in end_date ] )
remote_get_list_url = remote_instance.get_list_skeletons_url( 1 )
remote_get_list_url += '?%s' % urllib.parse.urlencode(get_skeleton_list_GET_data)
skid_list = remote_instance.fetch ( remote_get_list_url)
return skid_list
def get_annotations_from_list (skids, remote_instance):
""" Takes list of skids and retrieves their annotations. Note: It seems like this URL does not process more than 250 skids at a time!
Parameters
----------
skids : list of skeleton ids
remote_instance : CATMAID instance; either pass directly to function or define globally as 'remote_instance'
Returns
-------
dict: annotation_list = {skid1 : [annotation1,annotation2,....], skid2: []}
"""
remote_get_annotations_url = remote_instance.get_annotations_for_skid_list2( project_id )
get_annotations_postdata = {'metaannotations':0,'neuronnames':0}
for i in range(len(skids)):
key = 'skeleton_ids[%i]' % i
get_annotations_postdata[key] = str(skids[i])
print('Asking for %i skeletons annotations (Project ID: %i)' % (len(get_annotations_postdata),project_id), end = ' ')
annotation_list_temp = remote_instance.fetch( remote_get_annotations_url , get_annotations_postdata )
annotation_list = {}
for skid in annotation_list_temp['skeletons']:
annotation_list[skid] = []
for entry in annotation_list_temp['skeletons'][skid]['annotations']:
annotation_id = entry['id']
annotation_list[skid].append(annotation_list_temp['annotations'][str(annotation_id)])
print('Annotations for %i neurons retrieved' % len(annotation_list))
return(annotation_list)
def retrieve_connectivity (skids, remote_instance = None, threshold = 1):
""" Wrapper to retrieve the synaptic partners to neurons of interest
Parameters:
----------
skids : list of skeleton ids
remote_instance : CATMAID instance; either pass directly to function or define globally as 'remote_instance'
threshold : does not seem to have any effect on CATMAID API and is therefore filtered afterwards. This threshold is applied to the total number of synapses. (optional, default = 1)
Returns:
-------
filtered connectivity: {'incoming': { skid1: { 'num_nodes': XXXX, 'skids':{ 'skid3':n_snypases, 'skid4': n_synapses } } , skid2:{}, ... }, 'outgoing': { } }
"""
if remote_instance is None:
if 'remote_instance' in globals():
remote_instance = globals()['remote_instance']
else:
print('Please either pass a CATMAID instance or define globally as "remote_instance" ')
return
remote_connectivity_url = remote_instance.get_connectivity_url( 1 )
connectivity_post = {}
connectivity_post['boolean_op'] = 'OR'
i = 0
for skid in skids:
tag = 'source_skeleton_ids[%i]' %i
connectivity_post[tag] = skid
i +=1
connectivity_data = remote_instance.fetch( remote_connectivity_url , connectivity_post )
#As of 08/2015, # of synapses is returned as list of nodes with 0-5 confidence: {'skid': [0,1,2,3,4,5]}
#This is being collapsed into a single value before returning it:
for direction in ['incoming','outgoing']:
pop = []
for entry in connectivity_data[direction]:
if sum( [ sum(connectivity_data[direction][entry]['skids'][n]) for n in connectivity_data[direction][entry]['skids'] ] ) >= threshold:
for skid in connectivity_data[direction][entry]['skids']:
connectivity_data[direction][entry]['skids'][skid] = sum(connectivity_data[direction][entry]['skids'][skid])
else:
pop.append(entry)
for n in pop:
connectivity_data[direction].pop(n)
return(connectivity_data)
def get_partners (skids, remote_instance, hops, upstream=True, downstream=True):
""" Retrieves partners of given skids over several hops.
Parameters:
----------
skids : list of skeleton ids
remote_instance : CATMAID instance
either pass directly to function or define globally as 'remote_instance'
hops : integer
number of hops from the original skeleton to check
upstream/downstream : boolean
If true, this direction will be checked. I.e. hops = 2 and downstream = False will return inputs and inputs of inputs
Returns:
-------
partners : dict
{ 'incoming': list[ [hop1 connectivity data],[hop 2 connectivity data], ... ] , 'outgoing': list[ [hop1 connectivity data],[hop 2 connectivity data], ... ] }
"""
#By seperating up and downstream retrieval we make sure that we don't circle back in the second hop
#I.e. we only want inputs of inputs and NOT inputs+outputs of inputs
skids_upstream_to_retrieve = skids
skids_downstream_to_retrieve = skids
partners = {}
partners['incoming'] = []
partners['outgoing'] = []
skids_already_seen = {}
remote_connectivity_url = remote_instance.get_connectivity_url( project_id )
for hop in range(hops):
upstream_partners_temp = {}
connectivity_post = {}
#connectivity_post['threshold'] = 1
connectivity_post['boolean_op'] = 'OR'
if upstream is True:
for i in range(len(skids_upstream_to_retrieve)):
tag = 'source_skeleton_ids[%i]' % i
connectivity_post[tag] = skids_upstream_to_retrieve[i]
print( "Retrieving Upstream Partners for %i neurons [%i. hop]..." % (len(skids_upstream_to_retrieve),hop+1))
connectivity_data = []
connectivity_data = remote_instance.fetch( remote_connectivity_url , connectivity_post )
print("Done.")
new_skids_upstream_to_retrieve = []
for skid in connectivity_data['incoming']:
upstream_partners_temp[skid] = connectivity_data['incoming'][skid]
#Make sure we don't do circles (connection is still added though!):
#Unneccessary if we are already at the last hop
if skid not in skids_upstream_to_retrieve:
new_skids_upstream_to_retrieve.append(skid)
if skid in skids_already_seen:
print('Potential circle detected! %s between hops: %s and %i upstream' % (skid,skids_already_seen[skid],hop))
skids_already_seen[skid] += 'and' + str(hop) + ' upstream'
else:
skids_already_seen[skid] = str(hop) + ' upstream'
#Set skids to retrieve for next hop
skids_upstream_to_retrieve = new_skids_upstream_to_retrieve
partners['incoming'].append(upstream_partners_temp)
connectivity_post = {}
connectivity_post['threshold'] = 1
connectivity_post['boolean_op'] = 'OR'
downstream_partners_temp = {}
if downstream is True:
for i in range(len(skids_downstream_to_retrieve)):
tag = 'source_skeleton_ids[%i]' % i
connectivity_post[tag] = skids_downstream_to_retrieve[i]
print( "Retrieving Downstream Partners for %i neurons [%i. hop]..." % (len(skids_downstream_to_retrieve),hop+1))
connectivity_data = []
connectivity_data = remote_instance.fetch( remote_connectivity_url , connectivity_post )
print("Done!")
new_skids_downstream_to_retrieve = []
for skid in connectivity_data['outgoing']:
downstream_partners_temp[skid] = connectivity_data['outgoing'][skid]
#Make sure we don't do circles (connection is still added though!):
#Unneccessary if we are already at the last hop
if skid not in skids_downstream_to_retrieve:
new_skids_downstream_to_retrieve.append(skid)
if skid in skids_already_seen:
print('Potential circle detected! %s between hops: %s and %i downstream' % (skid,skids_already_seen[skid],hop))
skids_already_seen[skid] += 'and' + str(hop) + ' downstream'
else:
skids_already_seen[skid] = str(hop) + ' downstream'
#Set skids to retrieve for next hop
skids_downstream_to_retrieve = new_skids_downstream_to_retrieve
partners['outgoing'].append(downstream_partners_temp)
return(partners)
def get_user_ids(users):
""" Wrapper to retrieve user ids for a list of logins
Parameters:
-----------
users : list of strings
last names or user ids
Returns:
-------
user_ids : list of integers
"""
user_ids = []
user_list = remote_instance.fetch ( remote_instance.get_user_list_url() )
for u in users: