forked from biopython/biopython
-
Notifications
You must be signed in to change notification settings - Fork 6
/
_CircularDrawer.py
1725 lines (1583 loc) · 67 KB
/
_CircularDrawer.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
# Copyright 2003-2008 by Leighton Pritchard. All rights reserved.
# Revisions copyright 2008-2017 by Peter Cock.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
#
# Contact: Leighton Pritchard, The James Hutton Institute,
# Invergowrie, Dundee, Scotland, DD2 5DA, UK
# Leighton.Pritchard@hutton.ac.uk
################################################################################
"""CircularDrawer module for GenomeDiagram."""
# ReportLab imports
from reportlab.graphics.shapes import Drawing, String, Group, Line, Circle, Polygon
from reportlab.lib import colors
from reportlab.graphics.shapes import ArcPath
# GenomeDiagram imports
from ._AbstractDrawer import AbstractDrawer, draw_polygon, intermediate_points
from ._AbstractDrawer import _stroke_and_fill_colors
from ._FeatureSet import FeatureSet
from ._GraphSet import GraphSet
from math import pi, cos, sin
class CircularDrawer(AbstractDrawer):
"""Object for drawing circular diagrams.
Attributes:
- tracklines Boolean for whether to draw lines dilineating tracks
- pagesize Tuple describing the size of the page in pixels
- x0 Float X co-ord for leftmost point of drawable area
- xlim Float X co-ord for rightmost point of drawable area
- y0 Float Y co-ord for lowest point of drawable area
- ylim Float Y co-ord for topmost point of drawable area
- pagewidth Float pixel width of drawable area
- pageheight Float pixel height of drawable area
- xcenter Float X co-ord of center of drawable area
- ycenter Float Y co-ord of center of drawable area
- start Int, base to start drawing from
- end Int, base to stop drawing at
- length Size of sequence to be drawn
- track_size Float (0->1) the proportion of the track height to draw in
- drawing Drawing canvas
- drawn_tracks List of ints denoting which tracks are to be drawn
- current_track_level Int denoting which track is currently being drawn
- track_offsets Dictionary of number of pixels that each track top,
center and bottom is offset from the base of a fragment, keyed by track
- sweep Float (0->1) the proportion of the circle circumference to
use for the diagram
- cross_track_links List of tuples each with four entries (track A,
feature A, track B, feature B) to be linked.
"""
def __init__(
self,
parent=None,
pagesize="A3",
orientation="landscape",
x=0.05,
y=0.05,
xl=None,
xr=None,
yt=None,
yb=None,
start=None,
end=None,
tracklines=0,
track_size=0.75,
circular=1,
circle_core=0.0,
cross_track_links=None,
):
"""Create CircularDrawer object.
Arguments:
- parent Diagram object containing the data that the drawer
draws
- pagesize String describing the ISO size of the image, or a tuple
of pixels
- orientation String describing the required orientation of the
final drawing ('landscape' or 'portrait')
- x Float (0->1) describing the relative size of the X
margins to the page
- y Float (0->1) describing the relative size of the Y
margins to the page
- xl Float (0->1) describing the relative size of the left X
margin to the page (overrides x)
- xl Float (0->1) describing the relative size of the left X
margin to the page (overrides x)
- xr Float (0->1) describing the relative size of the right X
margin to the page (overrides x)
- yt Float (0->1) describing the relative size of the top Y
margin to the page (overrides y)
- yb Float (0->1) describing the relative size of the lower Y
margin to the page (overrides y)
- start Int, the position to begin drawing the diagram at
- end Int, the position to stop drawing the diagram at
- tracklines Boolean flag to show (or not) lines delineating tracks
on the diagram
- track_size The proportion of the available track height that
should be taken up in drawing
- circular Boolean flaw to show whether the passed sequence is
circular or not
- circle_core The proportion of the available radius to leave
empty at the center of a circular diagram (0 to 1).
- cross_track_links List of tuples each with four entries (track A,
feature A, track B, feature B) to be linked.
"""
# Use the superclass' instantiation method
AbstractDrawer.__init__(
self,
parent,
pagesize,
orientation,
x,
y,
xl,
xr,
yt,
yb,
start,
end,
tracklines,
cross_track_links,
)
# Useful measurements on the page
self.track_size = track_size
self.circle_core = circle_core
# Determine proportion of circumference around which information will be drawn
if not circular:
self.sweep = 0.9
else:
self.sweep = 1.0
def set_track_heights(self):
"""Initialize track heights.
Since tracks may not be of identical heights, the bottom and top
radius for each track is stored in a dictionary - self.track_radii,
keyed by track number
"""
bot_track = min(min(self.drawn_tracks), 1)
top_track = max(self.drawn_tracks) # The 'highest' track to draw
trackunit_sum = 0 # Total number of 'units' taken up by all tracks
trackunits = {} # Start and & units for each track keyed by track number
heightholder = 0 # placeholder variable
for track in range(bot_track, top_track + 1): # track numbers to 'draw'
try:
trackheight = self._parent[track].height # Get track height
except Exception: # TODO: ValueError? IndexError?
trackheight = 1
trackunit_sum += trackheight # increment total track unit height
trackunits[track] = (heightholder, heightholder + trackheight)
heightholder += trackheight # move to next height
max_radius = 0.5 * min(self.pagewidth, self.pageheight)
trackunit_height = max_radius * (1 - self.circle_core) / trackunit_sum
track_core = max_radius * self.circle_core
# Calculate top and bottom radii for each track
self.track_radii = {} # The inner, outer and center radii for each track
track_crop = (
trackunit_height * (1 - self.track_size) / 2.0
) # 'step back' in pixels
for track in trackunits:
top = trackunits[track][1] * trackunit_height - track_crop + track_core
btm = trackunits[track][0] * trackunit_height + track_crop + track_core
ctr = btm + (top - btm) / 2.0
self.track_radii[track] = (btm, ctr, top)
def draw(self):
"""Draw a circular diagram of the stored data."""
# Instantiate the drawing canvas
self.drawing = Drawing(self.pagesize[0], self.pagesize[1])
feature_elements = [] # holds feature elements
feature_labels = [] # holds feature labels
greytrack_bgs = [] # holds track background
greytrack_labels = [] # holds track foreground labels
scale_axes = [] # holds scale axes
scale_labels = [] # holds scale axis labels
# Get tracks to be drawn and set track sizes
self.drawn_tracks = self._parent.get_drawn_levels()
self.set_track_heights()
# Go through each track in the parent (if it is to be drawn) one by
# one and collate the data as drawing elements
for track_level in self._parent.get_drawn_levels():
self.current_track_level = track_level
track = self._parent[track_level]
gbgs, glabels = self.draw_greytrack(track) # Greytracks
greytrack_bgs.append(gbgs)
greytrack_labels.append(glabels)
features, flabels = self.draw_track(track) # Features and graphs
feature_elements.append(features)
feature_labels.append(flabels)
if track.scale:
axes, slabels = self.draw_scale(track) # Scale axes
scale_axes.append(axes)
scale_labels.append(slabels)
feature_cross_links = []
for cross_link_obj in self.cross_track_links:
cross_link_elements = self.draw_cross_link(cross_link_obj)
if cross_link_elements:
feature_cross_links.append(cross_link_elements)
# Groups listed in order of addition to page (from back to front)
# Draw track backgrounds
# Draw feature cross track links
# Draw features and graphs
# Draw scale axes
# Draw scale labels
# Draw feature labels
# Draw track labels
element_groups = [
greytrack_bgs,
feature_cross_links,
feature_elements,
scale_axes,
scale_labels,
feature_labels,
greytrack_labels,
]
for element_group in element_groups:
for element_list in element_group:
[self.drawing.add(element) for element in element_list]
if self.tracklines:
# Draw test tracks over top of diagram
self.draw_test_tracks()
def draw_track(self, track):
"""Return list of track elements and list of track labels."""
track_elements = [] # Holds elements for features and graphs
track_labels = [] # Holds labels for features and graphs
# Distribution dictionary for dealing with different set types
set_methods = {FeatureSet: self.draw_feature_set, GraphSet: self.draw_graph_set}
for set in track.get_sets(): # Draw the feature or graph sets
elements, labels = set_methods[set.__class__](set)
track_elements += elements
track_labels += labels
return track_elements, track_labels
def draw_feature_set(self, set):
"""Return list of feature elements and list of labels for them."""
# print('draw feature set')
feature_elements = [] # Holds diagram elements belonging to the features
label_elements = [] # Holds diagram elements belonging to feature labels
# Collect all the elements for the feature set
for feature in set.get_features():
if self.is_in_bounds(feature.start) or self.is_in_bounds(feature.end):
features, labels = self.draw_feature(feature)
feature_elements += features
label_elements += labels
return feature_elements, label_elements
def draw_feature(self, feature):
"""Return list of feature elements and list of labels for them."""
feature_elements = [] # Holds drawable elements for a single feature
label_elements = [] # Holds labels for a single feature
if feature.hide: # Don't show feature: return early
return feature_elements, label_elements
start, end = self._current_track_start_end()
# A single feature may be split into subfeatures, so loop over them
for locstart, locend in feature.locations:
if locend < start:
continue
locstart = max(locstart, start)
if end < locstart:
continue
locend = min(locend, end)
# Get sigil for the feature/ each subfeature
feature_sigil, label = self.get_feature_sigil(feature, locstart, locend)
feature_elements.append(feature_sigil)
if label is not None: # If there's a label
label_elements.append(label)
return feature_elements, label_elements
def get_feature_sigil(self, feature, locstart, locend, **kwargs):
"""Return graphics for feature, and any required label for it.
Arguments:
- feature Feature object
- locstart The start position of the feature
- locend The end position of the feature
"""
# Establish the co-ordinates for the sigil
btm, ctr, top = self.track_radii[self.current_track_level]
startangle, startcos, startsin = self.canvas_angle(locstart)
endangle, endcos, endsin = self.canvas_angle(locend)
midangle, midcos, midsin = self.canvas_angle(float(locend + locstart) / 2)
# Distribution dictionary for various ways of drawing the feature
# Each method takes the inner and outer radii, the start and end angle
# subtended at the diagram center, and the color as arguments
draw_methods = {
"BOX": self._draw_sigil_box,
"OCTO": self._draw_sigil_cut_corner_box,
"JAGGY": self._draw_sigil_jaggy,
"ARROW": self._draw_sigil_arrow,
"BIGARROW": self._draw_sigil_big_arrow,
}
# Get sigil for the feature, location dependent on the feature strand
method = draw_methods[feature.sigil]
kwargs["head_length_ratio"] = feature.arrowhead_length
kwargs["shaft_height_ratio"] = feature.arrowshaft_height
# Support for clickable links... needs ReportLab 2.4 or later
# which added support for links in SVG output.
if hasattr(feature, "url"):
kwargs["hrefURL"] = feature.url
kwargs["hrefTitle"] = feature.name
sigil = method(
btm,
ctr,
top,
startangle,
endangle,
feature.strand,
color=feature.color,
border=feature.border,
**kwargs
)
if feature.label: # Feature needs a label
# The spaces are a hack to force a little space between the label
# and the edge of the feature
label = String(
0,
0,
" %s " % feature.name.strip(),
fontName=feature.label_font,
fontSize=feature.label_size,
fillColor=feature.label_color,
)
labelgroup = Group(label)
if feature.label_strand:
strand = feature.label_strand
else:
strand = feature.strand
if feature.label_position in ("start", "5'", "left"):
# Position the label at the feature's start
if strand != -1:
label_angle = startangle + 0.5 * pi # Make text radial
sinval, cosval = startsin, startcos
else:
label_angle = endangle + 0.5 * pi # Make text radial
sinval, cosval = endsin, endcos
elif feature.label_position in ("middle", "center", "centre"):
# Position the label at the feature's midpoint
label_angle = midangle + 0.5 * pi # Make text radial
sinval, cosval = midsin, midcos
elif feature.label_position in ("end", "3'", "right"):
# Position the label at the feature's end
if strand != -1:
label_angle = endangle + 0.5 * pi # Make text radial
sinval, cosval = endsin, endcos
else:
label_angle = startangle + 0.5 * pi # Make text radial
sinval, cosval = startsin, startcos
elif startangle < pi:
# Default to placing the label the bottom of the feature
# as drawn on the page, meaning feature end on left half
label_angle = endangle + 0.5 * pi # Make text radial
sinval, cosval = endsin, endcos
else:
# Default to placing the label on the bottom of the feature,
# which means the feature end when on right hand half
label_angle = startangle + 0.5 * pi # Make text radial
sinval, cosval = startsin, startcos
if strand != -1:
# Feature label on top
radius = top
if startangle < pi: # Turn text round
label_angle -= pi
else:
labelgroup.contents[0].textAnchor = "end"
else:
# Feature label on bottom
radius = btm
if startangle < pi: # Turn text round and anchor end
label_angle -= pi
labelgroup.contents[0].textAnchor = "end"
x_pos = self.xcenter + radius * sinval
y_pos = self.ycenter + radius * cosval
coslabel = cos(label_angle)
sinlabel = sin(label_angle)
labelgroup.transform = (
coslabel,
-sinlabel,
sinlabel,
coslabel,
x_pos,
y_pos,
)
else:
# No label required
labelgroup = None
# if locstart > locend:
# print(locstart, locend, feature.strand, sigil, feature.name)
# print(locstart, locend, feature.name)
return sigil, labelgroup
def draw_cross_link(self, cross_link):
"""Draw a cross-link between features."""
startA = cross_link.startA
startB = cross_link.startB
endA = cross_link.endA
endB = cross_link.endB
if not self.is_in_bounds(startA) and not self.is_in_bounds(endA):
return None
if not self.is_in_bounds(startB) and not self.is_in_bounds(endB):
return None
if startA < self.start:
startA = self.start
if startB < self.start:
startB = self.start
if self.end < endA:
endA = self.end
if self.end < endB:
endB = self.end
trackobjA = cross_link._trackA(list(self._parent.tracks.values()))
trackobjB = cross_link._trackB(list(self._parent.tracks.values()))
assert trackobjA is not None
assert trackobjB is not None
if trackobjA == trackobjB:
raise NotImplementedError()
if trackobjA.start is not None:
if endA < trackobjA.start:
return
startA = max(startA, trackobjA.start)
if trackobjA.end is not None:
if trackobjA.end < startA:
return
endA = min(endA, trackobjA.end)
if trackobjB.start is not None:
if endB < trackobjB.start:
return
startB = max(startB, trackobjB.start)
if trackobjB.end is not None:
if trackobjB.end < startB:
return
endB = min(endB, trackobjB.end)
for track_level in self._parent.get_drawn_levels():
track = self._parent[track_level]
if track == trackobjA:
trackA = track_level
if track == trackobjB:
trackB = track_level
if trackA == trackB:
raise NotImplementedError()
startangleA, startcosA, startsinA = self.canvas_angle(startA)
startangleB, startcosB, startsinB = self.canvas_angle(startB)
endangleA, endcosA, endsinA = self.canvas_angle(endA)
endangleB, endcosB, endsinB = self.canvas_angle(endB)
btmA, ctrA, topA = self.track_radii[trackA]
btmB, ctrB, topB = self.track_radii[trackB]
if ctrA < ctrB:
return [
self._draw_arc_poly(
topA,
btmB,
startangleA,
endangleA,
startangleB,
endangleB,
cross_link.color,
cross_link.border,
cross_link.flip,
)
]
else:
return [
self._draw_arc_poly(
btmA,
topB,
startangleA,
endangleA,
startangleB,
endangleB,
cross_link.color,
cross_link.border,
cross_link.flip,
)
]
def draw_graph_set(self, set):
"""Return list of graph elements and list of their labels.
Arguments:
- set GraphSet object
"""
# print('draw graph set')
elements = [] # Holds graph elements
# Distribution dictionary for how to draw the graph
style_methods = {
"line": self.draw_line_graph,
"heat": self.draw_heat_graph,
"bar": self.draw_bar_graph,
}
for graph in set.get_graphs():
elements += style_methods[graph.style](graph)
return elements, []
def draw_line_graph(self, graph):
"""Return line graph as list of drawable elements.
Arguments:
- graph GraphData object
"""
line_elements = [] # holds drawable elements
# Get graph data
data_quartiles = graph.quartiles()
minval, maxval = data_quartiles[0], data_quartiles[4]
btm, ctr, top = self.track_radii[self.current_track_level]
trackheight = 0.5 * (top - btm)
datarange = maxval - minval
if datarange == 0:
datarange = trackheight
start, end = self._current_track_start_end()
data = graph[start:end]
if not data:
return []
# midval is the value at which the x-axis is plotted, and is the
# central ring in the track
if graph.center is None:
midval = (maxval + minval) / 2.0
else:
midval = graph.center
# Whichever is the greatest difference: max-midval or min-midval, is
# taken to specify the number of pixel units resolved along the
# y-axis
resolution = max((midval - minval), (maxval - midval))
# Start from first data point
pos, val = data[0]
lastangle, lastcos, lastsin = self.canvas_angle(pos)
# We calculate the track height
posheight = trackheight * (val - midval) / resolution + ctr
lastx = self.xcenter + posheight * lastsin # start xy coords
lasty = self.ycenter + posheight * lastcos
for pos, val in data:
posangle, poscos, possin = self.canvas_angle(pos)
posheight = trackheight * (val - midval) / resolution + ctr
x = self.xcenter + posheight * possin # next xy coords
y = self.ycenter + posheight * poscos
line_elements.append(
Line(
lastx,
lasty,
x,
y,
strokeColor=graph.poscolor,
strokeWidth=graph.linewidth,
)
)
lastx, lasty = x, y
return line_elements
def draw_bar_graph(self, graph):
"""Return list of drawable elements for a bar graph.
Arguments:
- graph Graph object
"""
# At each point contained in the graph data, we draw a vertical bar
# from the track center to the height of the datapoint value (positive
# values go up in one color, negative go down in the alternative
# color).
bar_elements = []
# Set the number of pixels per unit for the data
data_quartiles = graph.quartiles()
minval, maxval = data_quartiles[0], data_quartiles[4]
btm, ctr, top = self.track_radii[self.current_track_level]
trackheight = 0.5 * (top - btm)
datarange = maxval - minval
if datarange == 0:
datarange = trackheight
data = graph[self.start : self.end]
# midval is the value at which the x-axis is plotted, and is the
# central ring in the track
if graph.center is None:
midval = (maxval + minval) / 2.0
else:
midval = graph.center
# Convert data into 'binned' blocks, covering half the distance to the
# next data point on either side, accounting for the ends of fragments
# and tracks
start, end = self._current_track_start_end()
data = intermediate_points(start, end, graph[start:end])
if not data:
return []
# Whichever is the greatest difference: max-midval or min-midval, is
# taken to specify the number of pixel units resolved along the
# y-axis
resolution = max((midval - minval), (maxval - midval))
if resolution == 0:
resolution = trackheight
# Create elements for the bar graph based on newdata
for pos0, pos1, val in data:
pos0angle, pos0cos, pos0sin = self.canvas_angle(pos0)
pos1angle, pos1cos, pos1sin = self.canvas_angle(pos1)
barval = trackheight * (val - midval) / resolution
if barval >= 0:
barcolor = graph.poscolor
else:
barcolor = graph.negcolor
# Draw bar
bar_elements.append(
self._draw_arc(ctr, ctr + barval, pos0angle, pos1angle, barcolor)
)
return bar_elements
def draw_heat_graph(self, graph):
"""Return list of drawable elements for the heat graph.
Arguments:
- graph Graph object
"""
# At each point contained in the graph data, we draw a box that is the
# full height of the track, extending from the midpoint between the
# previous and current data points to the midpoint between the current
# and next data points
heat_elements = [] # holds drawable elements
# Get graph data
data_quartiles = graph.quartiles()
minval, maxval = data_quartiles[0], data_quartiles[4]
midval = (maxval + minval) / 2.0 # mid is the value at the X-axis
btm, ctr, top = self.track_radii[self.current_track_level]
trackheight = top - btm
start, end = self._current_track_start_end()
data = intermediate_points(start, end, graph[start:end])
# Create elements on the graph, indicating a large positive value by
# the graph's poscolor, and a large negative value by the graph's
# negcolor attributes
for pos0, pos1, val in data:
pos0angle, pos0cos, pos0sin = self.canvas_angle(pos0)
pos1angle, pos1cos, pos1sin = self.canvas_angle(pos1)
# Calculate the heat color, based on the differential between
# the value and the median value
heat = colors.linearlyInterpolatedColor(
graph.poscolor, graph.negcolor, maxval, minval, val
)
# Draw heat box
heat_elements.append(
self._draw_arc(btm, top, pos0angle, pos1angle, heat, border=heat)
)
return heat_elements
def draw_scale(self, track):
"""Return list of elements in the scale and list of their labels.
Arguments:
- track Track object
"""
scale_elements = [] # holds axes and ticks
scale_labels = [] # holds labels
if not track.scale:
# no scale required, exit early
return [], []
# Get track locations
btm, ctr, top = self.track_radii[self.current_track_level]
trackheight = top - ctr
# X-axis
start, end = self._current_track_start_end()
if track.start is not None or track.end is not None:
# Draw an arc, leaving out the wedge
p = ArcPath(strokeColor=track.scale_color, fillColor=None)
startangle, startcos, startsin = self.canvas_angle(start)
endangle, endcos, endsin = self.canvas_angle(end)
p.addArc(
self.xcenter,
self.ycenter,
ctr,
90 - (endangle * 180 / pi),
90 - (startangle * 180 / pi),
)
scale_elements.append(p)
del p
# Y-axis start marker
x0, y0 = self.xcenter + btm * startsin, self.ycenter + btm * startcos
x1, y1 = self.xcenter + top * startsin, self.ycenter + top * startcos
scale_elements.append(Line(x0, y0, x1, y1, strokeColor=track.scale_color))
# Y-axis end marker
x0, y0 = self.xcenter + btm * endsin, self.ycenter + btm * endcos
x1, y1 = self.xcenter + top * endsin, self.ycenter + top * endcos
scale_elements.append(Line(x0, y0, x1, y1, strokeColor=track.scale_color))
elif self.sweep < 1:
# Draw an arc, leaving out the wedge
p = ArcPath(strokeColor=track.scale_color, fillColor=None)
# Note reportlab counts angles anti-clockwise from the horizontal
# (as in mathematics, e.g. complex numbers and polar coordinates)
# in degrees.
p.addArc(
self.xcenter,
self.ycenter,
ctr,
startangledegrees=90 - 360 * self.sweep,
endangledegrees=90,
)
scale_elements.append(p)
del p
# Y-axis start marker
x0, y0 = self.xcenter, self.ycenter + btm
x1, y1 = self.xcenter, self.ycenter + top
scale_elements.append(Line(x0, y0, x1, y1, strokeColor=track.scale_color))
# Y-axis end marker
alpha = 2 * pi * self.sweep
x0, y0 = self.xcenter + btm * sin(alpha), self.ycenter + btm * cos(alpha)
x1, y1 = self.xcenter + top * sin(alpha), self.ycenter + top * cos(alpha)
scale_elements.append(Line(x0, y0, x1, y1, strokeColor=track.scale_color))
else:
# Draw a full circle
scale_elements.append(
Circle(
self.xcenter,
self.ycenter,
ctr,
strokeColor=track.scale_color,
fillColor=None,
)
)
start, end = self._current_track_start_end()
if track.scale_ticks: # Ticks are required on the scale
# Draw large ticks
# I want the ticks to be consistently positioned relative to
# the start of the sequence (position 0), not relative to the
# current viewpoint (self.start and self.end)
ticklen = track.scale_largeticks * trackheight
tickiterval = int(track.scale_largetick_interval)
# Note that we could just start the list of ticks using
# range(0,self.end,tickinterval) and the filter out the
# ones before self.start - but this seems wasteful.
# Using tickiterval * (self.start/tickiterval) is a shortcut.
for tickpos in range(
tickiterval * (self.start // tickiterval), int(self.end), tickiterval
):
if tickpos <= start or end <= tickpos:
continue
tick, label = self.draw_tick(
tickpos, ctr, ticklen, track, track.scale_largetick_labels
)
scale_elements.append(tick)
if label is not None: # If there's a label, add it
scale_labels.append(label)
# Draw small ticks
ticklen = track.scale_smallticks * trackheight
tickiterval = int(track.scale_smalltick_interval)
for tickpos in range(
tickiterval * (self.start // tickiterval), int(self.end), tickiterval
):
if tickpos <= start or end <= tickpos:
continue
tick, label = self.draw_tick(
tickpos, ctr, ticklen, track, track.scale_smalltick_labels
)
scale_elements.append(tick)
if label is not None: # If there's a label, add it
scale_labels.append(label)
# Check to see if the track contains a graph - if it does, get the
# minimum and maximum values, and put them on the scale Y-axis
# at 60 degree intervals, ordering the labels by graph_id
startangle, startcos, startsin = self.canvas_angle(start)
endangle, endcos, endsin = self.canvas_angle(end)
if track.axis_labels:
for set in track.get_sets():
if set.__class__ is GraphSet:
# Y-axis
for n in range(7):
angle = n * 1.0471975511965976
if angle < startangle or endangle < angle:
continue
ticksin, tickcos = sin(angle), cos(angle)
x0, y0 = (
self.xcenter + btm * ticksin,
self.ycenter + btm * tickcos,
)
x1, y1 = (
self.xcenter + top * ticksin,
self.ycenter + top * tickcos,
)
scale_elements.append(
Line(x0, y0, x1, y1, strokeColor=track.scale_color)
)
graph_label_min = []
graph_label_max = []
graph_label_mid = []
for graph in set.get_graphs():
quartiles = graph.quartiles()
minval, maxval = quartiles[0], quartiles[4]
if graph.center is None:
midval = (maxval + minval) / 2.0
graph_label_min.append("%.3f" % minval)
graph_label_max.append("%.3f" % maxval)
graph_label_mid.append("%.3f" % midval)
else:
diff = max(
(graph.center - minval), (maxval - graph.center)
)
minval = graph.center - diff
maxval = graph.center + diff
midval = graph.center
graph_label_mid.append("%.3f" % midval)
graph_label_min.append("%.3f" % minval)
graph_label_max.append("%.3f" % maxval)
xmid, ymid = (x0 + x1) / 2.0, (y0 + y1) / 2.0
for limit, x, y in [
(graph_label_min, x0, y0),
(graph_label_max, x1, y1),
(graph_label_mid, xmid, ymid),
]:
label = String(
0,
0,
";".join(limit),
fontName=track.scale_font,
fontSize=track.scale_fontsize,
fillColor=track.scale_color,
)
label.textAnchor = "middle"
labelgroup = Group(label)
labelgroup.transform = (
tickcos,
-ticksin,
ticksin,
tickcos,
x,
y,
)
scale_labels.append(labelgroup)
return scale_elements, scale_labels
def draw_tick(self, tickpos, ctr, ticklen, track, draw_label):
"""Return drawing element for a tick on the scale.
Arguments:
- tickpos Int, position of the tick on the sequence
- ctr Float, Y co-ord of the center of the track
- ticklen How long to draw the tick
- track Track, the track the tick is drawn on
- draw_label Boolean, write the tick label?
"""
# Calculate tick co-ordinates
tickangle, tickcos, ticksin = self.canvas_angle(tickpos)
x0, y0 = self.xcenter + ctr * ticksin, self.ycenter + ctr * tickcos
x1, y1 = (
self.xcenter + (ctr + ticklen) * ticksin,
self.ycenter + (ctr + ticklen) * tickcos,
)
# Calculate height of text label so it can be offset on lower half
# of diagram
# LP: not used, as not all fonts have ascent_descent data in reportlab.pdfbase._fontdata
# label_offset = _fontdata.ascent_descent[track.scale_font][0]*\
# track.scale_fontsize/1000.
tick = Line(x0, y0, x1, y1, strokeColor=track.scale_color)
if draw_label:
# Put tick position on as label
if track.scale_format == "SInt":
if tickpos >= 1000000:
tickstring = str(tickpos // 1000000) + " Mbp"
elif tickpos >= 1000:
tickstring = str(tickpos // 1000) + " Kbp"
else:
tickstring = str(tickpos)
else:
tickstring = str(tickpos)
label = String(
0,
0,
tickstring, # Make label string
fontName=track.scale_font,
fontSize=track.scale_fontsize,
fillColor=track.scale_color,
)
if tickangle > pi:
label.textAnchor = "end"
# LP: This label_offset depends on ascent_descent data, which is not available for all
# fonts, so has been deprecated.
# if 0.5*pi < tickangle < 1.5*pi:
# y1 -= label_offset
labelgroup = Group(label)
labelgroup.transform = (1, 0, 0, 1, x1, y1)
else:
labelgroup = None
return tick, labelgroup
def draw_test_tracks(self):
"""Draw blue test tracks with grene line down their center."""
# Add lines only for drawn tracks
for track in self.drawn_tracks:
btm, ctr, top = self.track_radii[track]
self.drawing.add(
Circle(
self.xcenter,
self.ycenter,
top,
strokeColor=colors.blue,
fillColor=None,
)
) # top line
self.drawing.add(
Circle(
self.xcenter,
self.ycenter,
ctr,
strokeColor=colors.green,
fillColor=None,
)
) # middle line
self.drawing.add(
Circle(
self.xcenter,
self.ycenter,
btm,
strokeColor=colors.blue,
fillColor=None,
)
) # bottom line
def draw_greytrack(self, track):
"""Drawing element for grey background to passed Track object."""
greytrack_bgs = [] # Holds track backgrounds
greytrack_labels = [] # Holds track foreground labels
if not track.greytrack: # No greytrack required, return early
return [], []
# Get track location
btm, ctr, top = self.track_radii[self.current_track_level]
start, end = self._current_track_start_end()
startangle, startcos, startsin = self.canvas_angle(start)
endangle, endcos, endsin = self.canvas_angle(end)
# Make background
if track.start is not None or track.end is not None: