-
Notifications
You must be signed in to change notification settings - Fork 1
/
pybot.py
executable file
·1634 lines (1406 loc) · 76.9 KB
/
pybot.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
"""
Catbot (https://github.com/flyconnectome/catbot) is a Slack bot that interfaces with CATMAID and ZOTERO
Copyright (C) 2017 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 matplotlib
#Switch a non-interactive, PNG-only backend. On Linux Tkinter, the default backend, causes trouble.
matplotlib.use('AGG')
#Pyplot has to imported AFTER setting the backend!
import matplotlib.pyplot as plt
import time, re, threading, random, json, sys, subprocess, shelve, os
import rpy2.robjects as robjects
import logging
from slackclient import SlackClient
from tabulate import tabulate
from rpy2.robjects.packages import importr
from pyzotero import zotero
from datetime import datetime, date, timedelta
from websocket import WebSocketConnectionClosedException
import pymaid
from pymaid.plotting import plot2d
from pymaid import (CatmaidInstance,
get_review,
get_neuron,
get_partners,
get_names,
neuron_exists,
get_skids_by_name,
get_skids_by_annotation,
get_annotations,
url_to_coordinates,
eval_skids)
class subscription_manager(threading.Thread):
""" Class to process subscriptions to neurons
"""
def __init__(self, slack_client, command, channel, user, global_update = False):
try:
self.command = command.lower()
self.raw_command = command
self.channel = channel
self.slack_client = slack_client
self.global_update = global_update
self.user = user
self.id = random.randint(1,99999)
threading.Thread.__init__(self)
except Exception as e:
logger.error('Failed to initiate thread for ' + self.command, exc_info = True)
def join(self):
try:
threading.Thread.join(self)
logger.debug('Thread %i closed' % self.id )
return None
except Exception as e:
logger.error('Failed to join thread for ' + self.url, exc_info = True )
return None
def process_neurons( self, skids ):
"""
Retrieves data for neurons from the CATMAID server and extracts relevant information
Parameters:
----------
skids : skeleton IDs to check
Returns:
-------
changes : {skid: { value : [ old, new ] }}
skdata : skeleton data for all neurons (order as in <skids>)
"""
#Retrieve relevant data from Catmaid server
skdata = get_neuron(skids, remote_instance=remote_instance)
connectivity = get_partners(skids, remote_instance=remote_instance,
min_size = 500)
annotations = get_annotations(skids, remote_instance=remote_instance)
r_status = get_review(skids, remote_instance=remote_instance).set_index('skeleton_id')
new_data = {}
logger.info('Extracting data...')
#Extract data
for neuron in skdata.itertuples():
if 'ends' in neuron.tags:
closed_ends = len( neuron.tags['ends'] )
else:
closed_ends = 0
if 'uncertain_ends' in neuron.tags:
uncertain_ends = len( neuron.tags['uncertain_end'] )
else:
uncertain_ends = 0
open_ends = neuron.nodes[ neuron.nodes.type == 'end' ].shape[0] - closed_ends - uncertain_ends
try:
this_an = annotations[ str(s) ]
except:
this_an = []
#First collect all synaptically connected neurons
all_con = { n : { 'upstream' : '-', 'downstream' : '-' } for n in connectivity[ connectivity[ neuron.skeleton_id ] > 0 ].skeleton_id.unique() }
for n in connectivity[ connectivity[ neuron.skeleton_id ] > 0 ][ [ 'skeleton_id', 'relation', neuron.skeleton_id ] ].itertuples():
all_con[ n.skeleton_id] [ n.relation ] = n[ 2 ]
#Don't forget to update basic_values when editing database entries!
new_data[ neuron.skeleton_id ] = { 'name' : neuron.neuron_name,
'branch_points' : neuron.nodes[ neuron.nodes.type == 'branch' ].shape[0],
'n_nodes' : neuron.nodes.shape[0],
'pre_synapses' : neuron.connectors[ neuron.connectors.relation == 0 ].shape[0],
'post_synapses' : neuron.connectors[ neuron.connectors.relation == 1 ].shape[0],
'open_ends' : open_ends,
'synaptic_partners' : all_con,
'last_update' : str( date.today() ),
'last_edited_by' : 'unknown',
'annotations' : this_an,
'review_status' : r_status.ix[ neuron.skeleton_id ].percent_reviewed
}
return new_data, skdata
def run(self):
"""
Structure of subscription database:
{ 'users': {
'user_id' : {
'subscriptions': [ neuronA, neuronB, neuronC ] ,
'daily_updates' : True/False,
'neurons' : { skid: {
'name' : str(),
'branch_points' : int(),
'n_nodes' : inte(),
'pre_synapses' : int(),
'post_synapses' : int(),
'open_ends' : int(),
'upstream_partners' : { skid: n_synapses },
'downstream_partners' : { skid: n_synapses },
'last_update' : timestamp_of_last_update,
'last_edited_by' : user_id,
'annotations' : list(),
'review_status' : int()
}
}
}
}
"""
basic_values = ['name','branch_points','n_nodes','pre_synapses','post_synapses','open_ends', 'review_status']
logger.info('Started new thread %i for command <%s> by user <%s>' % (self.id, self.command, self.user ) )
try:
data = shelve.open('subscriptiondb')
except:
if self.user != None:
self.slack_client.api_call("chat.postMessage", channel='@' + self.user,
text='Unable to open subscription database!', as_user=True)
else:
logger.error('Unable to open subscription database.')
return
skids = parse_neurons( self.raw_command )
#If db is fresh:
if len(data) == 0:
data['users'] = {}
#If user not yet in database, add entry
if self.user not in data['users'] and self.user != None:
#Have to do this explicitedly - otherwise shelve won't update
users = data['users']
users[self.user] = { 'subscriptions' : [],
'daily_updates' : True,
'neurons': {} }
data['users'] = users
#Now execture user command
if 'list' in self.command:
#List current subscriptions
neuron_names = get_names(data['users'][self.user]['subscriptions'],
remote_instance=remote_instance)
if neuron_names:
response = 'You are currently subscribed to the following neurons: \n'
response += '```' + tabulate( [ (neuron_names[str(s)], '#'+str(s) ) for s in data['users'][self.user]['subscriptions'] ] ) + '```'
else:
response = 'Currently, I do not have any subscriptions for you!'
if 'new' in self.command:
#Add new subscriptions
if skids:
new_data, skdata = self.process_neurons( [ str(s) for s in skids if s not in data['users'][self.user]['neurons'] ] )
users = data['users']
users[self.user]['subscriptions'] += skids
users[self.user]['subscriptions'] = list ( set( users[self.user]['subscriptions'] ) )
data['users'] = users
old_data = data['users']
old_data[self.user]['neurons'].update( new_data )
data['users'] = old_data
response = 'Thanks! I have subscribed you to `' + ' #'.join( [ str(s )for s in skids ] ) + '`'
else:
response = 'Please give me at least a single neuron to subscribe you to!'
if 'auto' in self.command:
users = data['users']
#Switch
users[self.user]['daily_updates'] = users[self.user]['daily_updates'] == False
data['users'] = users
if data['users'][self.user]['daily_updates'] is True:
response = 'Thanks! You will now automatically receive daily updates for your subscribed neurons.'
else:
response = 'Thanks! You will no longer receive daily updates.'
if 'delete' in self.command:
#Delete subscriptions
if skids:
response = 'Thanks! I succesfully unsubscribed you from neuron(s) ```'
for s in skids:
try:
users = data['users']
users[self.user]['subscriptions'].remove( s )
data['users'] = users
response += +'#' + str(s) + ' '
except:
pass
response += '```'
else:
response = 'Please provide me at least a single neuron to subscribe you to!'
#IDEA: PRINT CHANGES (+100, -100) instead of new/old?
#ADD CHANGES IN ANNOTATIONS
#MAKE SYNAPTIC PARTNERS CLICKY? like this: <http://www.zapier.com|Text to make into a link>
if 'update' in self.command or self.global_update is True:
logger.debug('Pushing updates')
if self.global_update is True:
users_to_notify = [ u for u in data['users'] if data['users'][u]['daily_updates'] is True ]
logger.debug('Global update! ' + str(users_to_notify))
neurons_to_process = []
for u in data['users']:
neurons_to_process += [ str(n) for n in data['users'][u]['neurons'] ]
else:
ts = self.slack_client.api_call("chat.postMessage", channel='@' + self.user,
text='Got it! Collecting intel - please wait...', as_user=True)['ts']
users_to_notify = [ self.user ]
neurons_to_process = [ str(s) for s in data['users'][self.user]['subscriptions'] ]
#Gather new data here - this costs time!
new_data,skdata = self.process_neurons ( neurons_to_process )
for u in users_to_notify:
not_changed = []
response = ''
if not skids:
neurons_to_update = [ str(s) for s in data['users'][u]['subscriptions'] ]
else:
neurons_to_update = [ str(s) for s in skids ]
for n in neurons_to_update:
n = str(n)
#Changes are sorted into basic values and more complicated stuff (i.e. synaptic partners)
changes = {
'basic': {},
'synaptic_partners': {},
'new_annotations': [],
'annotations': { 'new': [],
'gone': []
}
}
#Search for change in basic values
for e in basic_values:
#If value is new, skip it for now and just write it back
if e not in data['users'][u]['neurons'][n]:
continue
if new_data[n][e] != data['users'][u]['neurons'][n][e]:
changes['basic'][e] = [ new_data[n][e] , data['users'][u]['neurons'][n][e] ]
#Search for changes in values that are lists (i.e. up- and downstream partners)
for e in new_data[n]['synaptic_partners']:
try:
if new_data[n]['synaptic_partners'][e] != data['users'][u]['neurons'][n]['synaptic_partners'][e]:
changes['synaptic_partners'][e] = [ new_data[n]['synaptic_partners'][e], data['users'][u]['neurons'][n]['synaptic_partners'][e] ]
except:
#When partner is entirely new
changes['synaptic_partners'][e] = [ new_data[n]['synaptic_partners'][e], {'incoming':'-', 'outgoing': '- '} ]
#Search for partners that have vanished
for e in data['users'][u]['neurons'][n]['synaptic_partners']:
try:
if new_data[n]['synaptic_partners'][e] != data['users'][u]['neurons'][n]['synaptic_partners'][e]:
changes['synaptic_partners'][e] = [ new_data[n]['synaptic_partners'][e], data['users'][u]['neurons'][n]['synaptic_partners'][e] ]
except:
changes['synaptic_partners'][e] = [ {'incoming':'-', 'outgoing': '- '} , data['users'][u]['neurons'][n]['synaptic_partners'][e] ]
try:
#Find new annotations
for e in new_data[n]['annotations']:
if e not in data['users'][u]['neurons'][n]['annotations']:
changes['annotations']['new'].append(e)
#Find annotations that have vanished:
for e in data['users'][u]['neurons'][n]['annotations']:
if e not in new_data[n]['annotations']:
changes['annotations']['gone'].append(e)
except:
#E.g. if annotations have not yet been tracked in the old dataset
pass
#If changes have been found, generate response
if changes['basic'] or changes['synaptic_partners'] or changes['annotations']['new'] or changes['annotations']['gone']:
nodes = skdata.set_index('skeleton_id').ix[ str(n) ].nodes
root_index = nodes [ nodes.type == 'root' ].index[0]
root = nodes.ix[ root_index ]
#root = [nd for nd in skdata[ neurons_to_process.index(n) ][0] if nd[1] == None][0]
url = url_to_coordinates((root.x, root.y, root.z),
stack_id=5,
tool='tracingtool',
active_skeleton_id=n,
remote_instance=remote_instance,
active_node_id=root[0])
link = '<' + url + '|' + new_data[n]['name'] + '>'
response += '%s - #%s (changes since %s) \n```' % ( link , str(n), data['users'][u]['neurons'][n]['last_update'] )
else:
not_changed.append(n)
#Basic values first
if changes['basic']:
if True in [ e in changes['basic'] for e in basic_values ]:
table = [ [ 'Value', 'New', 'Old' ] ] + [ [ e, changes['basic'][e][0], changes['basic'][e][1] ] for e in basic_values if e in changes['basic'] ]
response += tabulate(table) + '\n'
if changes['annotations']['new']:
response += 'New annotations: %s \n' % '; '.join(changes['annotations']['new'])
if changes['annotations']['gone']:
response += 'Deleted annotations: %s \n' % '; '.join(changes['annotations']['gone'])
#Now connectivity
if changes['synaptic_partners']:
partner_names = get_names(list(changes['synaptic_partners'].keys()),
remote_instance=remote_instance)
#If partner does not exist anymore:
partner_names.update( { e:'not found' for e in list( changes['synaptic_partners'].keys() ) if e not in partner_names } )
response += 'Synaptic partners:\n'
table = [ [ 'Name', 'SKID', 'Synapses from (new/old)', 'Synapses to (new/old)' ] ]
table += [ [ partner_names[e], e, str(changes['synaptic_partners'][e][0]['incoming'])+'/'+str(changes['synaptic_partners'][e][1]['incoming']), str(changes['synaptic_partners'][e][0]['outgoing'])+'/'+str(changes['synaptic_partners'][e][1]['outgoing']), ] for e in changes['synaptic_partners'] ]
response += tabulate(table) + '\n'
if changes['basic'] or changes['synaptic_partners'] or changes['annotations']['new'] or changes['annotations']['gone']:
response += '```\n'
if response:
self.slack_client.api_call("chat.postMessage", channel='@' + u,
text= response , as_user=True)
if not_changed:
self.slack_client.api_call("chat.postMessage", channel='@' + u,
text= 'No changes for neurons `' + ', '.join(not_changed) + '`', as_user=True)
#Reset response
response = ''
else:
logger.debug( 'No changes for user ' + u )
self.slack_client.api_call("chat.postMessage", channel= '@' + u,
text='None of the neurons you are subscribed to have changed recently!', as_user=True)
#Write back changes to DB
users = data['users']
users[u]['neurons'].update(new_data)
data['users'] = users
try:
data.close()
logger.debug('Database update successful')
if self.user != None:
self.slack_client.api_call("chat.postMessage", channel='@' + self.user,
text=response, as_user=True)
else:
logger.debug('User is None: ' + response)
except:
logger.error('Failed to update database')
if self.user != None:
self.slack_client.api_call("chat.postMessage", channel='@' + self.user,
text='Oops! Something went wrong. If you made any changes to your subscriptions, please try again.', as_user=True)
else:
logger.debug('User is None: ' + response)
return
class return_review_status(threading.Thread):
""" Class to process incoming review-status request
"""
def __init__(self, slack_client ,command,channel):
try:
self.command = command.lower()
self.raw_command = command
self.channel = channel
self.slack_client = slack_client
self.id = random.randint(1,99999)
threading.Thread.__init__(self)
except Exception as e:
logger.error('Failed to initiate thread for ' + self.command,
exc_info=True)
def join(self):
try:
threading.Thread.join(self)
logger.debug('Thread %i closed' % self.id )
return None
except Exception as e:
logger.error('Failed to join thread for ' + self.url,
exc_info=True)
return None
def run(self):
""" Extracts skids from command and returns these neurons review-status.
"""
logger.debug('Started new thread %i for command <%s>' % (self.id, self.command ) )
skids = parse_neurons(self.raw_command)
ts = self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text='Got it! Collecting intel - '
'please wait...',
as_user=True)['ts']
for s in skids:
if not neuron_exists(s, remote_instance=remote_instance):
response = "I'm sorry - the neuron #%s does not seem to " \
"exists. Please try again." % s
self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text=response,
as_user=True)
return
if not skids:
response = 'Please provide neurons as *#skid*, *annotation=" "* ' \
'or *name=" "*! For example: _@catbot review-status ' \
'#957684_'
else:
r_status = get_review(skids, remote_instance=remote_instance)
response = "This is the current review status:\n ```{}``` ".format(r_status.to_string())
self.slack_client.api_call("chat.delete",
channel = self.channel,
ts = ts)
if response:
self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text=response, as_user=True)
return
class return_plot_neuron(threading.Thread):
""" Class to process incoming plot neuron request
"""
def __init__(self, slack_client ,command,channel):
try:
self.command = command.lower()
self.raw_command = command
self.channel = channel
self.slack_client = slack_client
self.id = random.randint(1,99999)
threading.Thread.__init__(self)
except Exception as e:
logger.error('Failed to initiate thread for ' + self.command,
exc_info=True)
def join(self):
try:
threading.Thread.join(self)
logger.debug('Thread %i closed' % self.id )
return None
except Exception as e:
logger.error('Failed to join thread for ' + self.url,
exc_info=True)
return None
def run(self):
""" Extracts skids from command and generates + uploads a file
"""
logger.debug('Started new thread %i for command <%s>' % (self.id,
self.command))
skids = parse_neurons(self.raw_command)
if not skids:
response = 'Please provide neurons as *#skid*, *annotation=" "* ' \
'or *name=" "*! For example: _@catbot plot-neuron ' \
'#957684_'
else:
for s in skids:
if not neuron_exists(s, remote_instance=remote_instance):
response = "I'm sorry - the neuron #%s does not seem to " \
"exists. Please try again." % s
self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text=response, as_user=True)
return
ts = self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text='Got it! Generating plot - '
'please wait...',
as_user=True)['ts']
# Get all volumes
vlist = pymaid.get_volume(remote_instance=remote_instance)
vlist = vlist.name.values
# Find the volumes we are supposed to plot
v2plot = ['v14.neuropil'] + [v for v in vlist if v in self.command]
vols = pymaid.get_volume(v2plot, remote_instance=remote_instance)
if not isinstance(vols, dict):
vols = {vols.name : vols}
vols['v14.neuropil'].color = (250, 250, 250, .3)
# Find out if colors for volumes are specified:
for v in vols:
if re.search('{v}=((.*))', self.command):
vols[v].color = re.search('{v}=((.*))', self.command).group(1)
try:
fig, ax = plot2d(skids + list(vols.values()),
method='3d_complex',
remote_instance=remote_instance)
except Exception as e:
self.slack_client.api_call("chat.delete",
channel = self.channel,
ts = ts
)
logger.error('Error in plotneuron()', exc_info = True)
self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text='Oops - something went wrong '
'while trying to plot your '
'neuron(s).',
as_user=True)
return
#Add legend if more than one neuron
if len(skids) > 1:
plt.legend()
#Check if output directory exists
if not os.path.isdir( 'renderings' ):
os.makedirs( 'renderings' )
#Save the figure
plt.savefig('renderings/neuron_plot.png',
transparent=False, dpi=300)
#Delete stand-by message
self.slack_client.api_call("chat.delete",
channel=self.channel,
ts=ts)
#Upload neuron plot
with open('renderings/neuron_plot.png', 'rb') as f:
self.slack_client.api_call("files.upload",
channels=self.channel,
file = f,
title = 'Neuron plot',
initial_comment = 'Neurons #%s' % ' #'.join([str(s) for s in skids])
)
response = ''
if response:
self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text=response, as_user=True)
return
class return_connectivity(threading.Thread):
""" Class to process incoming connectivity requests
"""
def __init__(self, slack_client ,command,channel):
try:
self.command = command.lower()
self.raw_command = command
self.channel = channel
self.slack_client = slack_client
self.id = random.randint(1,99999)
threading.Thread.__init__(self)
except Exception as e:
logger.error('Failed to initiate thread for ' + self.command,
exc_info = True)
def join(self):
try:
threading.Thread.join(self)
logger.debug('Thread %i closed' % self.id )
return None
except Exception as e:
logger.error('Failed to join thread for ' + self.url,
exc_info=True)
return None
def run(self):
""" Returns urls for a list of neurons
"""
skids = parse_neurons( self.raw_command )
logger.debug('Started new thread %i for command <%s>' % (self.id,
self.command))
for s in skids:
if not neuron_exists(s, remote_instance=remote_instance):
response = "I'm sorry - the neuron #%s does not seem to " \
"exists. Please try again." % s
self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text=response, as_user=True)
return
self.command = self.command.replace('”','"')
try:
thresh = int(re.search('threshold=(\d+)',self.command).group(1))
except:
thresh = 1
try:
filt = re.search('filter="(.*?)"',self.command).group(1).split(',')
logger.debug('Filtering partners for: ' + str(filt) )
except:
filt = []
directions = []
if 'incoming' in self.command or 'upstream' in self.command:
directions.append('upstream')
if 'outgoing' in self.command or 'downstream' in self.command:
directions.append('downstream')
if not directions:
directions = ['upstream', 'downstream']
if not skids:
response = 'Please provide neurons as `#skid`, `annotation=" "` ' \
'or `name=" "`! For example: `@catbot partners #957684`'
else:
cn = get_partners(skids,
remote_instance=remote_instance,
threshold=thresh)
attachments = []
rel_colors = {'upstream': '#2874A6',
'downstream': '#C0392B',
'gapjunction': '#16A085',
'attachment': '#F1C40F'}
for d in directions:
this_cn = cn[cn.relation==d].drop(['relation', 'total', 'num_nodes'], axis=1)
this_at = dict(title='{} partners'.format(d),
text='```{}```'.format(this_cn.iloc[0:70].reset_index(drop=True).to_string()),
mrkdwn='true',
color=rel_colors[d],
footer='Truncated (too many neurons)!!!' if this_cn.shape[0] > 70 else '')
attachments.append(this_at)
self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text='Here are the partners of neurons'
' you requested:',
attachments=attachments,
as_user=True)
return ''
class return_url(threading.Thread):
""" Class to process incoming url to neuron request
"""
def __init__(self, slack_client ,command,channel):
try:
self.command = command.lower()
self.raw_command = command
self.channel = channel
self.slack_client = slack_client
self.id = random.randint(1,99999)
threading.Thread.__init__(self)
except Exception as e:
logger.error('Failed to initiate thread for ' + self.command,
exc_info=True)
def join(self):
try:
threading.Thread.join(self)
logger.debug('Thread %i closed' % self.id )
return None
except Exception as e:
logger.error('Failed to join thread for ' + self.url,
exc_info=True)
return None
def run(self):
""" Returns urls for a list of neurons
"""
skids = parse_neurons(self.raw_command)
logger.debug('Started new thread %i for command <%s>' % (self.id,
self.command))
for s in skids:
if not neuron_exists(s, remote_instance=remote_instance):
response = "I'm sorry - the neuron #%s does not seem to " \
"exists. Please try again." % s
self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text=response,
as_user=True)
return
if not skids:
response = 'Please provide neurons as `#skid`, `annotation=" "` ' \
'or `name=" "`! For example: `@catbot plot-neuron #957684`'
else:
response = 'Here are URLs to the neurons you have provided!'
skdata = get_neuron(skids, remote_instance=remote_instance,
connector_flag=0, tag_flag=0,
get_history=False)
skdata = pymaid.CatmaidNeuronList(skdata)
for neuron in skdata:
root = neuron.nodes[neuron.nodes.type=='root']
url = url_to_coordinates(root,
stack_id=5,
tool='tracingtool',
active_skeleton_id=neuron.skeleton_id,
active_node_id=root.treenode_id.values,
remote_instance=remote_instance)
for u in url:
response += '\n *#%s*: %s' % (neuron.skeleton_id, u)
if response:
self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text=response, as_user=True)
return response
class return_zotero(threading.Thread):
""" Class to process requests to access Zotero
"""
def __init__(self, slack_client ,command,channel):
try:
self.command = command.lower()
self.raw_command = command
self.channel = channel
self.slack_client = slack_client
self.id = random.randint(1,99999)
threading.Thread.__init__(self)
except Exception as e:
logger.error('Failed to initiate thread for ' + self.command,
exc_info=True)
def join(self):
try:
threading.Thread.join(self)
logger.debug('Thread %i closed' % self.id )
return None
except Exception as e:
logger.error('Failed to join thread for ' + self.url,
exc_info=True)
return None
def run(self):
""" Lists all available commands and their syntax.
"""
logger.debug('Started new thread %i for command <%s>' % (self.id,
self.command))
#First extract tags to search for
command = self.command.replace('zotero', '')
tags = command.split(' ')
if '' in tags:
tags.remove('')
ts = self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text='Searching Zotero database. '
'Please hold...',
as_user=True)['ts']
#Retrieve all items in library
items = zot.everything ( zot.items() )
pdf_files = [ i for i in items if i['data']['itemType'] == 'attachment' and i['data']['title'] == 'Full Text PDF' ]
logger.debug('Searching %i Zotero items for:' % len(items))
logger.debug(tags)
self.slack_client.api_call("chat.delete",
channel=self.channel,
ts=ts)
if 'file' in tags:
dl_file = True
tags.remove('file')
if len(tags) > 1:
self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text='If you want me to grab you a '
'PDF, please give me a single '
'zotero key: `@catbot zotero '
'file <ZOTERO-ID>`',
as_user=True)
elif len(tags) == 1:
this_item = [f for f in pdf_files if f['data']['parentItem'].lower() == tags[0]]
if this_item:
filename = this_item[0]['data']['filename']
zot.dump( this_item[0]['key'] , filename )
with open( filename , 'rb') as f:
self.slack_client.api_call("files.upload",
channels=self.channel,
file = f,
title = filename,
initial_comment = '')
return
else:
self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text="Oops! I can't seem to "
"find a PDF to the Zotero "
"key you have given me...",
as_user=True)
return
else:
dl_file = False
results = []
for e in items:
include = []
for t in tags:
this_tag = False
#Try/Except is important because some entries aren't articles
try:
if t in e['data']['date']:
this_tag = True
logger.debug('Found tag %s in %s' % ( t, e['data']['date'] ) )
elif t.lower() in [ a['lastName'].lower() for a in e['data']['creators']]:
this_tag = True
logger.debug('Found tag %s in %s' % ( t, str([ a['lastName'].lower() for a in e['data']['creators']]) ) )
elif t.lower() in e['data']['title'].lower():
this_tag = True
logger.debug('Found tag %s in %s' % ( t, e['data']['title'].lower() ) )
elif True in [ t.lower() in a['tag'].lower() for a in e['data']['tags'] ]:
this_tag = True
logger.debug('Found tag %s in %s (%s)' % ( t, [ a['tag'].lower() for a in e['data']['tags'] ], [ t.lower() in a['tag'].lower() for a in e['data']['tags'] ] ) )
except:
pass
include.append( this_tag )
if False not in include:
logger.debug( str(tags) + str(include) + e['data']['date'] )
results.append( e )
if results:
response = 'Here are the publications matching your criteria:\n```'
response += 'Author\tJournal\tDate\tTitle\tDOI\tUrl\t(Zotero ID)\n'
for e in results:
try:
doi_url = '- http://dx.doi.org/' + e['data']['DOI']
except:
doi_url = ''
authors = [ a['lastName'] for a in e['data']['creators'] ]
date = e['data']['date']
journal = e['data']['journalAbbreviation']
title = e['data']['title']
zot_key = e['key']
if len(e['data']['creators']) > 2:
response += '%s et al., %s (%s): %s %s (%s)\n\n' % ( authors[0], journal, date, title , doi_url, zot_key )
elif len(e['data']['creators']) == 2:
response += '%s and %s, %s (%s): %s %s (%s)\n\n' % ( authors[0], authors[1] , journal, date, title , doi_url, zot_key )
elif len(e['data']['creators']) == 1:
response += '%s, %s (%s): %s %s (%s)\n\n' % ( authors[0], journal, date, title , doi_url, zot_key )
response += '```\n'
response += 'Use `@catbot zotero file <ZOTERO-ID>` if you want ' \
'me to grab you the PDF!'
else:
response = 'Sorry, I could not find anything matching your ' \
'criteria!'
self.slack_client.api_call("chat.postMessage",
channel=self.channel,
text=response, as_user=True)
return
class return_help(threading.Thread):
""" Class to process incoming help request
"""
def __init__(self, slack_client ,command,channel):
try:
self.command = command.lower()
self.raw_command = command
self.channel = channel
self.slack_client = slack_client
self.id = random.randint(1,99999)
threading.Thread.__init__(self)
except Exception as e:
logger.error('Failed to initiate thread for ' + self.command,
exc_info=True)
def join(self):
try:
threading.Thread.join(self)
logger.debug('Thread %i closed' % self.id )
return None
except Exception as e:
logger.error('Failed to join thread for ' + self.url,
exc_info = True)
return None
def run(self):
""" Lists all available commands and their syntax.
"""
logger.debug('Started new thread %i for command <%s>' % (self.id, self.command))
if 'partners' in self.command:
response = '`partners` returns the synaptic partners for a list of <neurons>. You can pass me keywords to filter the list: \n'
response += '1. Add `incoming` or `outgoing` to limit results to up- or downstream partners \n'
response += '2. Add `filter="tag1,tag2"` to filter results for neuron names (case-insensitive, non-intersecting)\n'
response += '3. Add `threshold=3` to filter partners for a minimum number of synapses\n'
elif 'nblast-fafb' in self.command:
response = '`nblast-fafb` blasts the provided neuron against the nightly dump of FAFB neurons. Use combinations of the following optional arguments to refine: \n'
response += '1. Use `nblast-fafb <neuron> mirror` to mirror neuron before nblasting (if you are looking for the left version of your neuron). \n'
response += '2. Use `nblast-fafb <neuron> hits=N` to return the top N hits in the 3D plot. Default is 3\n'
response += '4. Use `nblast-fafb <neuron> cores=N` to set the number of CPU cores used to nblast. Default is 8\n'
response += '5. Use `nblast-fafb <neuron> prefermu` to sort hits by reverse score (muscore) rather than forward score\n'
response += '6. Use `nblast-fafb <neuron> usealpha` to make nblast value backbones higher than smaller neurites\n'
elif 'nblast' in self.command:
response = '`nblast` blasts the provided neuron against the flycircuit database. Use combinations of the following optional arguments to refine: \n'
response += '1. Use `nblast <neuron> nomirror` to prevent mirroring of neurons before nblasting (i.e. if cellbody is already on the flys left). \n'
response += '2. Use `nblast <neuron> hits=N` to return the top N hits in the 3D plot. Default is 3\n'
response += '3. Use `nblast <neuron> gmrdb` to nblast against Janelia GMR lines \n'
response += '4. Use `nblast <neuron> cores=N` to set the number of CPU cores used to nblast. Default is 8\n'
response += '5. Use `nblast <neuron> prefermu` to sort hits by reverse score (muscore) rather than forward score\n'
response += '6. Use `nblast <neuron> usealpha` to make nblast value backbones higher than smaller neurites\n'
elif 'neurondb' in self.command:
response = '`neurondb` lets you access and edit the neuron database. \n'
response += 'I am using skeleton IDs as unique identifiers -> you can search for names/annotations/etc but I need a SKID when you want to add/edit an entry! \n'
response += '1. Use `neurondb list` to get a list of all neurons in the database. \n'
response += '2. Use `neurondb search <tag1> <tag2> ...` to search for hits in the database. \n'
response += '3. Use `neurondb show <single neuron>` to show a summary for those skeleton ids. \n'
response += '4. Use `neurondb edit <single neuron> name="MVP2" comments="awesome neuron"` to edit entries. \n'
response += ' For list entries such as <comments> or <neuropils> you can use "comments=comment1;comment2;comment3" to add multiple entries at a time. \n'
response += '5. To delete specific comments/tags use e.g. `neurondb *delete* comments=<index>` to remove the <index> (e.g. 1 = first) comment. \n'
elif 'subscription' in self.command:
response = '`subscription` lets you flag neurons of interest and I will keep you informed when they are modified. \n'
response += 'By default you will automatically receive daily updates (in the morning) \n'
response += 'but you can use `update` at any time to get an unscheduled summary.'
response += '1. Use `subscription list` to get a list of all neurons you are currently subscribed to. \n'
response += '2. Use `subscription new <neuron(s)>` to subscribe to neurons. \n'
response += '3. Use `subscription update` to get an unscheduled summary of changes. Unless you also provide <neurons>, you will get all subscriptions. \n'
response += '4. Use `subscription delete <neuron(s)>` to unsubscribe to neurons. \n'
elif 'plot' in self.command:
response = '`plot` lets you plot neurons of interest. \n'
response += '1. Use `plot <neuron(s)> neuropil1 neuropil2` to make me plot neuropils. \n'
response += '2. Use `plot <neuron(s)> neuropil1=(r,g,b) neuropil2=(r,g,b)` to give neuropils specific colors (`r`,`g`,`b` must be range 0-1). \n'
response += 'Currently, I can offer these neuropils: `MB`, `SIP` ,`AL`, `CRE`, `SLP`, `LH` \n'
else:
functions = [
'`neurondb` : accesses the neuron database. Use `@catbot help neurondb` to learn more.',