-
-
Notifications
You must be signed in to change notification settings - Fork 216
/
server.py
executable file
·1718 lines (1344 loc) · 54.6 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Keep the data of trees and present a REST api to talk
to the world.
REST call examples:
GET /trees Get all trees
GET /trees/{id} Get the tree information identified by "id"
POST /trees Create a new tree
PUT /trees/{id} Update the tree information identified by "id"
DELETE /trees/{id} Delete tree by "id"
"""
import os
import re
import platform
from subprocess import Popen, DEVNULL
from threading import Thread
import socket
from importlib import reload as module_reload
from math import pi, inf
from time import time, sleep
from datetime import datetime
from collections import defaultdict, namedtuple
from copy import copy, deepcopy
from dataclasses import dataclass
import gzip, bz2, zipfile, tarfile
import json
import _pickle as pickle
import shutil
import logging
import brotli
from bottle import (
get, post, put, redirect, static_file,
BaseRequest, request, response, error, abort, HTTPError, run)
BaseRequest.MEMFILE_MAX = 50 * 1024 * 1024 # maximum upload size (in bytes)
from ete4 import Tree
from ete4.parser import newick
from ete4.smartview import TreeStyle, layout_modules
from ete4.parser import ete_format, nexus
from ete4.core import operations as ops
from ete4.smartview.renderer import drawer as drawer_module
from ete4 import treematcher as tm
class GlobalStuff:
pass # class to store data
# Make sure we send the errors as json too.
@error(400)
@error(404)
def json_error(error):
response.content_type = 'application/json'
return json.dumps({'message': error.body})
def req_json():
"""Return what request.json would return, but gracefully aborting."""
try:
return json.loads(request.body.read())
except json.JSONDecodeError as e:
abort(400, f'bad json content: {e}')
def nice_html(content, title='Tree Explorer'):
return f"""
<!DOCTYPE html>
<html><head><title>{title}</title>
<link rel="icon" type="image/png" href="/static/icon.png">
<link rel="stylesheet" href="/static/upload.css"></head>
<body><div class="centered">{content}</div></body></html>"""
# call initialize() to fill it up
app = None
g_threads = {}
# Dataclass containing info specific to each tree
@dataclass
class TreeData:
tree: Tree = None
name: str = None
style: TreeStyle = None
nodestyles: dict = None
include_props: list = None
exclude_props: list = None
layouts: list = None
timer: float = None
ultrametric: bool = False
initialized: bool = False
selected: dict = None
active: namedtuple = None # active nodes
searches: dict = None
# Routes.
@get('/')
def callback():
if app.trees:
if len(app.trees) == 1:
name = list(t.name for t in app.trees.values())[0]
redirect(f'/static/gui.html?tree={name}')
else:
trees = '\n'.join('<li><a href="/static/gui.html?tree='
f'{t.name}">{t.name}</li>' for t in app.trees.values())
return nice_html(f'<h1>Loaded Trees</h1><ul>\n{trees}\n</ul>')
else:
return nice_html("""<h1>ETE</h1>
<p>No trees loaded.</p>
<p>See the <a href="/help">help page</a> for more information.</p>""")
@get('/help')
def callback():
return nice_html("""<h1>Help</h1>
You can go to the <a href="/static/upload.html">upload page</a>, see
a <a href="/">list of loaded trees</a>, or
<a href="http://etetoolkit.org/">consult the documentation</a>.""")
@get('/static/<path:path>')
def callback(path):
DIR = os.path.dirname(os.path.abspath(__file__))
return static_file(path, f'{DIR}/static')
@get('/drawers/<name>/<tree_id>')
def callback(name, tree_id):
"""Return type (rect/circ) and number of panels of the drawer."""
try:
tree_id, _ = get_tid(tree_id)
# NOTE: Apparently we need to know the tree_id we are
# referring to because it checks if there are aligned faces in
# it to see if we are using a DrawerAlignX drawer (instead of
# DrawerX).
tree_layouts = sum(app.trees[int(tree_id)].layouts.values(), [])
if (name not in ['Rect', 'Circ'] and
any(getattr(ly, 'aligned_faces', False) and ly.active
for ly in tree_layouts)):
name = 'Align' + name
# TODO: We probably want to get rid of all this.
drawer_class = next(d for d in drawer_module.get_drawers()
if d.__name__[len('Drawer'):] == name)
return {'type': drawer_class.TYPE,
'npanels': drawer_class.NPANELS}
except StopIteration:
abort(400, f'not a valid drawer: {name}')
@get('/layouts')
def callback():
# Return dict that, for every layout module, has a dict with the
# names of its layouts and whether they are active or not.
app.trees.pop('default', None) # FIXME: Why do we do this??
return {'default': {layout.name: layout.active
for layout in app.default_layouts if layout.name}}
# The response will look like:
# {
# "default": {
# "Branch length": true,
# "Branch support": true,
# "Leaf name": true,
# "Number of leaves": false
# }
# }
@get('/layouts/list')
def callback():
return {module: [[ly.name, ly.description] for ly in layouts if ly.name]
for module, layouts in app.avail_layouts.items()}
# The response will look like:
# {"context_layouts": [["Genomic context", ""]],
# "domain_layouts": [["Pfam domains", ""], ["Smart domains",""]],
# ...
# "staple_layouts": [["Barplot_None_None", ""]]}
@get('/layouts/<tree_id>')
def callback(tree_id):
# Return dict that, for every layout module in the tree, has a dict
# with the names of its layouts and whether they are active or not.
tid, _ = get_tid(tree_id)
tree_layouts = app.trees[tid].layouts
layouts = {}
for module, lys in tree_layouts.items():
layouts[module] = {l.name: l.active for l in lys if l.name}
return layouts
# The response will look like:
# {
# "default": {
# "Branch length": true,
# "Branch support": true,
# "Leaf name": true,
# "Number of leaves": false
# }
# }
@put('/layouts/update')
def callback():
update_app_available_layouts()
@get('/trees')
def callback():
if app.safe_mode:
abort(404, 'invalid path /trees in safe_mode mode')
response.content_type = 'application/json'
return json.dumps([{'id': tid, 'name': tdata.name}
for tid, tdata in app.trees.items()])
def touch_and_get(tree_id):
"""Load tree, update its timer, and return the tree data object and subtree."""
tid, subtree = get_tid(tree_id)
load_tree(tree_id) # load if it was not loaded in memory
tree_data = app.trees[tid]
tree_data.timer = time() # update the tree's timer
return tree_data, subtree
@get('/trees/<tree_id>')
def callback(tree_id):
if app.safe_mode:
abort(404, f'invalid path /trees/{tree_id} in safe_mode mode')
tree_data, subtree = touch_and_get(tree_id)
props = set()
for node in tree_data.tree[subtree].traverse():
props |= {k for k in node.props if not k.startswith('_')}
return {'name': tree_data.name, 'props': list(props)}
@get('/trees/<tree_id>/nodeinfo')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
return tree_data.tree[subtree].props
@get('/trees/<tree_id>/nodestyle')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
response.content_type = 'application/json'
return json.dumps(tree_data.tree[subtree].sm_style)
@get('/trees/<tree_id>/editable_props')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
return {k: v for k, v in tree_data.tree[subtree].props.items()
if k not in ['tooltip', 'hyperlink'] and type(v) in [int, float, str]}
# TODO: Document what the hell is going on here.
@get('/trees/<tree_id>/name')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
response.content_type = 'application/json'
return json.dumps(tree_data.name)
@get('/trees/<tree_id>/newick')
def callback(tree_id):
MAX_MB = 200
response.content_type = 'application/json'
return json.dumps(get_newick(tree_id, MAX_MB))
@get('/trees/<tree_id>/seq')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
def fasta(node):
name = node.name if node.name else ','.join(map(str, node.id))
return '>' + name + '\n' + node.props['seq']
response.content_type = 'application/json'
return json.dumps('\n'.join(fasta(leaf) for leaf in tree_data.tree[subtree].leaves()
if leaf.props.get('seq')))
@get('/trees/<tree_id>/nseq')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
response.content_type = 'application/json'
return json.dumps(sum(1 for leaf in tree_data.tree[subtree].leaves() if leaf.props.get('seq')))
@get('/trees/<tree_id>/all_selections')
def callback(tree_id):
tree_data, _ = touch_and_get(tree_id)
return {'selected': {name: {'nresults': len(results), 'nparents': len(parents)}
for name, (results, parents) in (tree_data.selected or {}).items()}}
@get('/trees/<tree_id>/selections')
def callback(tree_id):
return {'selections': get_selections(tree_id)}
@get('/trees/<tree_id>/select')
def callback(tree_id):
nresults, nparents = store_selection(tree_id, request.query)
return {'message': 'ok', 'nresults': nresults, 'nparents': nparents}
@get('/trees/<tree_id>/unselect')
def callback(tree_id):
removed = unselect_node(tree_id, request.query)
return {'message': 'ok' if removed else 'selection not found'}
@get('/trees/<tree_id>/remove_selection')
def callback(tree_id):
removed = remove_selection(tree_id, request.query)
return {'message': 'ok' if removed else 'selection not found'}
@get('/trees/<tree_id>/change_selection_name')
def callback(tree_id):
change_selection_name(tree_id, request.query)
return {'message': 'ok'}
@get('/trees/<tree_id>/selection/info')
def callback(tree_id):
tree_data, _ = touch_and_get(tree_id)
return get_selection_info(tree_data, request.query)
@get('/trees/<tree_id>/search_to_selection')
def callback(tree_id):
search_to_selection(tree_id, request.query)
return {'message': 'ok'}
@get('/trees/<tree_id>/prune_by_selection')
def callback(tree_id):
prune_by_selection(tree_id, request.query)
return {'message': 'ok'}
@get('/trees/<tree_id>/active')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
node = tree_data.tree[subtree]
response.content_type = 'application/json'
if get_active_clade(node, tree_data.active.clades.results):
return json.dumps('active_clade')
elif node in tree_data.active.nodes.results:
return json.dumps('active_node')
else:
return json.dumps('')
@get('/trees/<tree_id>/activate_node')
def callback(tree_id):
activate_node(tree_id)
return {'message': 'ok'}
@get('/trees/<tree_id>/deactivate_node')
def callback(tree_id):
deactivate_node(tree_id)
return {'message': 'ok'}
@get('/trees/<tree_id>/activate_clade')
def callback(tree_id):
activate_clade(tree_id)
return {'message': 'ok'}
@get('/trees/<tree_id>/deactivate_clade')
def callback(tree_id):
deactivate_clade(tree_id)
return {'message': 'ok'}
@get('/trees/<tree_id>/store_active_nodes')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
nresults, nparents = store_active(tree_data, 0, request.query)
return {'message': 'ok', 'nresults': nresults, 'nparents': nparents}
@get('/trees/<tree_id>/store_active_clades')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
nresults, nparents = store_active(tree_data, 1, request.query)
return {'message': 'ok', 'nresults': nresults, 'nparents': nparents}
@get('/trees/<tree_id>/remove_active_nodes')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
remove_active(tree_data, 0)
return {'message': 'ok'}
@get('/trees/<tree_id>/remove_active_clades')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
remove_active(tree_data, 1)
return {'message': 'ok'}
@get('/trees/<tree_id>/all_active')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
return {
'nodes': get_nodes_info(tree_data.active.nodes.results, ['*']),
'clades': get_nodes_info(tree_data.active.clades.results, ['*']),
}
@get('/trees/<tree_id>/all_active_leaves')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
active_leaves = set(n for n in tree_data.active.nodes.results if n.is_leaf)
for n in tree_data.active.clades.results:
active_leaves.update(set(n.leaves()))
return get_nodes_info(active_leaves, ['*'])
# Searches
@get('/trees/<tree_id>/searches')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
return {'searches': {text: {'nresults': len(results), 'nparents': len(parents)}
for text, (results, parents) in (tree_data.searches or {}).items()}}
@get('/trees/<tree_id>/search')
def callback(tree_id):
nresults, nparents = store_search(tree_id, request.query)
return {'message': 'ok', 'nresults': nresults, 'nparents': nparents}
@get('/trees/<tree_id>/remove_search')
def callback(tree_id):
removed = remove_search(tree_id, request.query)
return {'message': 'ok' if removed else 'search not found'}
# Find
@get('/trees/<tree_id>/find')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
node = find_node(tree_data.tree, request.query)
node_id = ','.join(map(str, node.id))
return {'id': node_id}
@get('/trees/<tree_id>/draw')
def callback(tree_id):
try:
drawer = get_drawer(tree_id, request.query)
graphics = json.dumps(list(drawer.draw())).encode('utf8')
response.content_type = 'application/json'
if app.compress:
response.add_header('Content-Encoding', 'br')
return brotli.compress(graphics)
else:
return graphics
except (AssertionError, SyntaxError) as e:
abort(400, f'when drawing: {e}')
@get('/trees/<tree_id>/size')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
width, height = tree_data.tree[subtree].size
return {'width': width, 'height': height}
@get('/trees/<tree_id>/collapse_size')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
response.content_type = 'application/json'
return json.dumps(tree_data.style.collapse_size)
@get('/trees/<tree_id>/properties')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
props = set()
for node in tree_data.tree[subtree].traverse():
props |= node.props.keys()
response.content_type = 'application/json'
return json.dumps(list(props))
@get('/trees/<tree_id>/properties/<pname>')
def callback(tree_id, pname):
return get_stats(tree_id, pname)
@get('/trees/<tree_id>/nodecount')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
tnodes = tleaves = 0
for node in tree_data.tree[subtree].traverse():
tnodes += 1
if node.is_leaf:
tleaves += 1
return {'tnodes': tnodes, 'tleaves': tleaves}
@get('/trees/<tree_id>/ultrametric')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
response.content_type = 'application/json'
return json.dumps(tree_data.ultrametric)
@post('/trees')
def callback():
ids = add_trees_from_request()
response.status = 201
return {'message': 'ok', 'ids': ids}
@put('/trees/<tree_id>/sort')
def callback(tree_id):
node_id, key_text, reverse = req_json()
sort(tree_id, node_id, key_text, reverse)
return {'message': 'ok'}
@put('/trees/<tree_id>/set_outgroup')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
if subtree:
abort(400, 'operation not allowed with subtree')
node_id = req_json()
tree_data.tree.set_outgroup(tree_data.tree[node_id])
ops.update_sizes_all(tree_data.tree)
return {'message': 'ok'}
@put('/trees/<tree_id>/move')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
try:
node_id, shift = req_json()
ops.move(tree_data.tree[subtree][node_id], shift)
return {'message': 'ok'}
except AssertionError as e:
abort(400, f'cannot move {node_id}: {e}')
@put('/trees/<tree_id>/remove')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
try:
node_id = req_json()
ops.remove(tree_data.tree[subtree][node_id])
ops.update_sizes_all(tree_data.tree)
return {'message': 'ok'}
except AssertionError as e:
abort(400, f'cannot remove {node_id}: {e}')
@put('/trees/<tree_id>/rename')
def callback(tree_id):
try:
tree_data, subtree = touch_and_get(tree_id)
node_id, name = req_json()
tree_data.tree[subtree][node_id].name = name
return {'message': 'ok'}
except AssertionError as e:
abort(400, f'cannot rename {node_id}: {e}')
@put('/trees/<tree_id>/edit')
def callback(tree_id):
try:
tree_data, subtree = touch_and_get(tree_id)
node_id, content = req_json()
node = tree_data.tree[subtree][node_id]
node.props = newick.get_props(content, is_leaf=True)
ops.update_sizes_all(tree_data.tree)
return {'message': 'ok'}
except (AssertionError, newick.NewickError) as e:
abort(400, f'cannot edit {node_id}: {e}')
@put('/trees/<tree_id>/to_dendrogram')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
node_id = req_json()
ops.to_dendrogram(tree_data.tree[subtree][node_id])
ops.update_sizes_all(tree_data.tree)
return {'message': 'ok'}
@put('/trees/<tree_id>/to_ultrametric')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
try:
node_id = req_json()
ops.to_ultrametric(tree_data.tree[subtree][node_id])
ops.update_sizes_all(tree_data.tree)
return {'message': 'ok'}
except AssertionError as e:
abort(400, f'cannot convert to ultrametric {tree_id}: {e}')
@put('/trees/<tree_id>/update_props')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
try:
node = tree_data.tree[subtree]
update_node_props(node, req_json())
return {'message': 'ok'}
except AssertionError as e:
abort(400, f'cannot update props of {node_id}: {e}')
@put('/trees/<tree_id>/update_nodestyle')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
try:
node = tree_data.tree[subtree]
update_node_style(node, req_json().copy())
tree_data.nodestyles[node] = req_json().copy()
return {'message': 'ok'}
except AssertionError as e:
abort(400, f'cannot update style of {node_id}: {e}')
@put('/trees/<tree_id>/reinitialize')
def callback(tree_id):
tree_data, subtree = touch_and_get(tree_id)
tree_data.initialized = False
ops.update_sizes_all(tree_data.tree)
return {'message': 'ok'}
@put('/trees/<tree_id>/reload')
def callback(tree_id):
_, subtree = touch_and_get(tree_id)
if subtree:
abort(400, 'operation not allowed with subtree')
app.trees.pop(tree_id, None) # avoid possible key-error
return {'message': 'ok'}
# Auxiliary functions.
def initialize_tree_style(tree_data):
# Save aligned_grid_dxs to add them later.
aligned_grid_dxs = deepcopy(tree_data.style.aligned_grid_dxs)
tree_data.style = TreeStyle()
tree_data.style.aligned_grid_dxs = aligned_grid_dxs
# Layout pre-render
for layouts in tree_data.layouts.values():
for layout in layouts:
if layout.active:
layout.set_tree_style(tree_data.tree, tree_data.style)
# A terrible way of saying something that should be like:
# tree_data.style.update(layout.tree_style)
tree_data.initialized = True
def load_tree(tree_id):
"Add tree to app.trees and initialize it if not there, and return it"
try:
tid, subtree = get_tid(tree_id)
if tid in app.trees:
tree_data = app.trees[tid]
# Reinitialize if layouts have to be reapplied
if not tree_data.initialized:
initialize_tree_style(tree_data)
for node in tree_data.tree[subtree].traverse():
node.is_initialized = False
node._smfaces = None
node._collapsed_faces = None
node._sm_style = None
for node, args in tree_data.nodestyles.items():
update_node_style(node, args.copy())
return tree_data.tree[subtree]
else:
tree_data = app.trees[tid] = retrieve_tree_data(tid)
if tree_data.ultrametric:
tree_data.tree.to_ultrametric()
ops.update_sizes_all(tree_data.tree)
initialize_tree_style(tree_data)
return tree_data.tree[subtree]
except (AssertionError, IndexError):
abort(404, f'unknown tree id {tree_id}')
def load_tree_from_newick(tid, nw):
"""Load tree into memory from newick"""
t = Tree(nw)
ops.update_sizes_all(t)
return t
def retrieve_layouts(layouts):
layouts = layouts or []
tree_layouts = defaultdict(list)
for ly in layouts:
name_split = ly.split(':')
if len(name_split) not in (2, 3):
continue
if len(name_split) == 2:
key, ly_name = name_split
active = None
elif len(name_split) == 3:
key, ly_name, active = name_split
active = True if active == "on" else False
avail = deepcopy(app.avail_layouts.get(key, []))
if ly_name == '*':
if active is not None:
for ly in avail:
ly.active = active
tree_layouts[key] = avail
else:
match = next((ly for ly in avail if ly.name == ly_name ), None)
if match:
if active is not None:
match.active = active
tree_layouts[key].append(match)
# Add default layouts
tree_layouts["default"] = deepcopy(app.default_layouts)
return dict(tree_layouts)
def retrieve_tree_data(tid):
"""Retrieve and return tree data from file.
It retrieves all that from a previously saved pickle file in /tmp."""
# Called when tree has been deleted from memory.
try:
tree_data = pickle.load(open(f'/tmp/{tid}.pickle', 'rb'))
except (FileNotFoundError, EOFError, pickle.UnpicklingError) as e:
print(f'Tree {tid} cannot be recovered from disk. Loading placeholder.')
tree_data = TreeData()
tree_data.name = 'Placeholder tree'
tree_data.tree = Tree('(could,not,load,tree);')
ops.update_sizes_all(tree_data.tree)
tree_data.style = copy_style(TreeStyle())
tree_data.layouts = retrieve_layouts(tree_data.layouts)
tree_data.active = drawer_module.get_empty_active()
tree_data.timer = time() # to track if it is active
return tree_data
def get_drawer(tree_id, args):
"Return the drawer initialized as specified in the args"
valid_keys = ['x', 'y', 'w', 'h', 'panel', 'zx', 'zy', 'za',
'drawer', 'min_size',
'layouts', 'ultrametric', 'collapsed_ids',
'rmin', 'amin', 'amax']
try:
assert all(k in valid_keys for k in args.keys()), 'invalid keys'
get = lambda x, default: float(args.get(x, default)) # shortcut
viewport = ([get(k, 0) for k in ['x', 'y', 'w', 'h']]
if all(k in args for k in ['x', 'y', 'w', 'h']) else None)
assert viewport is None or (viewport[2] > 0 and viewport[3] > 0), \
'invalid viewport' # width and height must be > 0
panel = get('panel', 0)
zoom = (get('zx', 1), get('zy', 1), get('za', 1))
assert zoom[0] > 0 and zoom[1] > 0 and zoom[2] > 0, 'zoom must be > 0'
load_tree(tree_id) # in case it went out of memory
tid, _ = get_tid(tree_id)
tree_data = app.trees[tid]
active_layouts = args.get('layouts')
if active_layouts != None:
update_layouts(active_layouts, tid)
layouts = set(ly for ly in sum(tree_data.layouts.values(), []) if ly.active)
drawer_name = args.get('drawer', 'RectFaces')
# Automatically provide aligned drawer when necessary
if drawer_name not in ['Rect', 'Circ'] and\
any(getattr(ly, 'aligned_faces', False) for ly in layouts):
drawer_name = 'Align' + drawer_name
drawer_class = next((d for d in drawer_module.get_drawers()
if d.__name__[len('Drawer'):] == drawer_name), None)
drawer_class.COLLAPSE_SIZE = get('min_size', 6)
assert drawer_class.COLLAPSE_SIZE > 0, 'min_size must be > 0'
limits = (None if not drawer_name.startswith('Circ') else
(get('rmin', 0), 0,
get('amin', -180) * pi/180, get('amax', 180) * pi/180))
collapsed_ids = set(tuple(int(i) for i in node_id.split(',') if i != '')
for node_id in json.loads(args.get('collapsed_ids', '[]')))
ultrametric = args.get('ultrametric') == '1' # asked for ultrametric?
if ultrametric and not tree_data.ultrametric: # change to on
tree_data.tree.to_ultrametric()
ops.update_sizes_all(tree_data.tree)
initialize_tree_style(tree_data)
tree_data.ultrametric = ultrametric
elif not ultrametric and tree_data.ultrametric: # change to off
app.trees.pop(tid, None) # delete from memory
# Forces it to be reloaded from disk next time it is accessed.
active = tree_data.active
selected = tree_data.selected
searches = tree_data.searches
return drawer_class(
load_tree(tree_id), viewport, panel, zoom,
limits, collapsed_ids, active, selected, searches,
layouts, tree_data.style, tree_data.include_props, tree_data.exclude_props)
# bypass errors for now...
except StopIteration as error:
abort(400, f'not a valid drawer: {drawer_name}')
except (ValueError, AssertionError) as e:
abort(400, str(e))
def get_newick(tree_id, max_mb):
"Return the newick representation of the given tree"
nw = load_tree(tree_id).write()
size_mb = len(nw) / 1e6
if size_mb > max_mb:
abort(400, 'newick too big (%.3g MB)' % size_mb)
return nw
def remove_search(tid, args):
"Remove search"
if 'text' not in args:
abort(400, 'missing search text')
searches = app.trees[int(tid)].searches
text = args.pop('text').strip()
return searches.pop(text, None)
def store_search(tree_id, args):
"Store the results and parents of a search and return their numbers"
if 'text' not in args:
abort(400, 'missing search text')
text = args.pop('text').strip()
func = get_search_function(text)
try:
results = set(node for node in load_tree(tree_id).traverse() if func(node))
if len(results) == 0:
return 0, 0
parents = get_parents(results)
tid, _ = get_tid(tree_id)
app.trees[tid].searches[text] = (results, parents)
return len(results), len(parents)
except Exception as e:
abort(400, f'evaluating expression: {e}')
def find_node(tree, args):
if 'text' not in args:
abort(400, 'missing search text')
text = args.pop('text').strip()
func = get_search_function(text)
try:
return next((node for node in tree.traverse() if func(node)), None)
except Exception as e:
abort(400, f'evaluating expression: {e}')
def get_selections(tree_id):
tid, subtree = get_tid(tree_id)
tree_data = app.trees[tid]
node = tree_data.tree[subtree]
return [name for name, (results, _) in tree_data.selected.items() if node in results]
def update_node_props(node, args):
for prop, value in node.props.items():
newvalue = args.pop(prop, "").strip()
if newvalue:
try: # convert to proper type
newvalue = type(value)(newvalue)
except:
abort(400, f'property {prop} should be of type {type(value)}')
node.add_prop(prop, newvalue)
def update_node_style(node, args):
newstyle = {}
for prop, value in dict(node.sm_style).items():
newvalue = args.pop(prop, "").strip()
if newvalue:
try: # convert to proper type
newvalue = type(value)(newvalue)
except:
abort(400, f'property {prop} should be of type {type(value)}')
else:
newstyle[prop] = newvalue
extend_to_descendants = args.pop("extend_to_descendants", None)
if extend_to_descendants:
nodes = node.traverse()
else:
nodes = [ node ]
for node in nodes:
for key, value in newstyle.items():
node.sm_style[key] = value
def get_nodes_info(nodes, props):
no_props = len(props) == 1 and props[0] == ''
if 'id' in props or no_props or '*' in props:
node_ids = [ ",".join(map(str, node.id))
for node in nodes ]
if no_props:
return node_ids
nodes_info = []
for idx, node in enumerate(nodes):
if props[0] == "*":
node_id = node_ids[idx]
nodes_info.append({'id': node_id })
else:
node_p = { p: node.props.get(p) for p in props }
if 'id' in props:
node_p['id'] = node_ids[idx]
nodes_info.append(node_p)
return nodes_info
def get_selection_info(tree_data, args):
"Get selection info from their nodes"
if 'text' not in args:
abort(400, 'missing selection text')
name = args.pop('text').strip()
nodes = tree_data.selected.get(name, [[]])[0]
props = args.pop('props', '').strip().split(',')
return get_nodes_info(nodes, props)
def remove_selection(tid, args):
"Remove selection"
if 'text' not in args:
abort(400, 'missing selection text')
name = args.pop('text').strip()
return app.trees[int(tid)].selected.pop(name, None)
def change_selection_name(tid, args):
if 'name' not in args or 'newname' not in args:
abort(400, 'missing renaming parameters')
name = args.pop('name').strip()
selected = app.trees[int(tid)].selected
if name not in selected.keys():
abort(400, f'selection {name} does not exist')
new_name = args.pop('newname').strip()
selected[new_name] = selected[name]
selected.pop(name)
def unselect_node(tree_id, args):
tid, subtree = get_tid(tree_id)
tree_data = app.trees[tid]
node = tree_data.tree[subtree]
name = args.pop('text', '').strip()
if name in tree_data.selected.keys():
selections = {name: tree_data.selected[name]}
else:
selections = dict(tree_data.selected) # copy all
removed = False
for name, (results, parents) in selections.items():
nresults = len(results)
results.discard(node)
if len(results) == 0: