-
Notifications
You must be signed in to change notification settings - Fork 25
/
visualization.py
289 lines (227 loc) · 9.35 KB
/
visualization.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
""" Chromosome plotting functions.
Notes
-----
Adapted from Ryan Dale's GitHub Gist for plotting chromosome features. [#Dale]_
References
----------
.. [#Dale] Ryan Dale, GitHub Gist,
https://gist.github.com/daler/c98fc410282d7570efc3#file-ideograms-py
"""
"""
The MIT License (MIT)
Copyright (c) 2016 Ryan Dale
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
"""
MIT License
Copyright (c) 2017 Andrew Riha
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import logging
import os
from atomicwrites import atomic_write
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
from matplotlib.collections import BrokenBarHCollection
from matplotlib import patches
logger = logging.getLogger(__name__)
def plot_chromosomes(one_chrom_match, two_chrom_match, cytobands, path, title, build):
"""Plots chromosomes with designated markers.
Parameters
----------
one_chrom_match : pandas.DataFrame
segments to highlight on the chromosomes representing one shared chromosome
two_chrom_match : pandas.DataFrame
segments to highlight on the chromosomes representing two shared chromosomes
cytobands : pandas.DataFrame
cytobands table loaded with Resources
path : str
path to destination `.png` file
title : str
title for plot
build : {37}
human genome build
"""
# Height of each chromosome
chrom_height = 1.25
# Spacing between consecutive chromosomes
chrom_spacing = 1
# Decide which chromosomes to use
chromosome_list = ["chr%s" % i for i in range(1, 23)]
chromosome_list.append("chrY")
chromosome_list.append("chrX")
# Keep track of the y positions for chromosomes, and the center of each chromosome
# (which is where we'll put the ytick labels)
ybase = 0
chrom_ybase = {}
chrom_centers = {}
# Iterate in reverse so that items in the beginning of `chromosome_list` will
# appear at the top of the plot
for chrom in chromosome_list[::-1]:
chrom_ybase[chrom] = ybase
chrom_centers[chrom] = ybase + chrom_height / 2.0
ybase += chrom_height + chrom_spacing
# Colors for different chromosome stains
color_lookup = {
"gneg": (202 / 255, 202 / 255, 202 / 255), # background
"one_chrom": (0 / 255, 176 / 255, 240 / 255),
"two_chrom": (66 / 255, 69 / 255, 121 / 255),
"centromere": (1, 1, 1, 0.6),
}
df = _patch_chromosomal_features(cytobands, one_chrom_match, two_chrom_match)
# Add a new column for colors
df["colors"] = df["gie_stain"].apply(lambda x: color_lookup[x])
# Width, height (in inches)
figsize = (6.5, 9)
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
# Now all we have to do is call our function for the chromosome data...
for collection in _chromosome_collections(df, chrom_ybase, chrom_height):
ax.add_collection(collection)
# Axes tweaking
ax.set_yticks([chrom_centers[i] for i in chromosome_list])
ax.set_yticklabels(chromosome_list)
ax.margins(0.01)
ax.axis("tight")
handles = []
# setup legend
if len(one_chrom_match) > 0:
one_chrom_patch = patches.Patch(
color=color_lookup["one_chrom"], label="One chromosome shared"
)
handles.append(one_chrom_patch)
if len(two_chrom_match) > 0:
two_chrom_patch = patches.Patch(
color=color_lookup["two_chrom"], label="Two chromosomes shared"
)
handles.append(two_chrom_patch)
no_match_patch = patches.Patch(color=color_lookup["gneg"], label="No shared DNA")
handles.append(no_match_patch)
centromere_patch = patches.Patch(
color=(234 / 255, 234 / 255, 234 / 255), label="Centromere"
)
handles.append(centromere_patch)
plt.legend(handles=handles, loc="lower right", bbox_to_anchor=(0.95, 0.05))
ax.set_title(title, fontsize=14, fontweight="bold")
plt.xlabel("Build " + str(build) + " Chromosome Position", fontsize=10)
logger.info("Saving {}".format(os.path.relpath(path)))
plt.tight_layout()
with atomic_write(path, mode="wb", overwrite=True) as f:
plt.savefig(f)
def _chromosome_collections(df, y_positions, height, **kwargs):
"""
Yields BrokenBarHCollection of features that can be added to an Axes
object.
Parameters
----------
df : pandas.DataFrame
Must at least have columns ['chrom', 'start', 'end', 'color']. If no
column 'width', it will be calculated from start/end.
y_positions : dict
Keys are chromosomes, values are y-value at which to anchor the
BrokenBarHCollection
height : float
Height of each BrokenBarHCollection
Additional kwargs are passed to BrokenBarHCollection
"""
del_width = False
if "width" not in df.columns:
del_width = True
df["width"] = df["end"] - df["start"]
for chrom, group in df.groupby("chrom"):
yrange = (y_positions["chr" + chrom], height)
xranges = group[["start", "width"]].values
yield BrokenBarHCollection(
xranges, yrange, facecolors=group["colors"], **kwargs
)
if del_width:
del df["width"]
def _patch_chromosomal_features(cytobands, one_chrom_match, two_chrom_match):
"""Highlight positions for each chromosome segment / feature.
Parameters
----------
cytobands : pandas.DataFrame
cytoband table from UCSC
one_chrom_match : pandas.DataFrame
segments to highlight on the chromosomes representing one shared chromosome
two_chrom_match : pandas.DataFrame
segments to highlight on the chromosomes representing two shared chromosomes
Returns
-------
df : pandas.DataFrame
the start and stop positions of particular features on each
chromosome
"""
def concat(df, chrom, start, end, gie_stain):
return pd.concat(
[
df,
pd.DataFrame(
{
"chrom": [chrom],
"start": [start],
"end": [end],
"gie_stain": [gie_stain],
}
),
],
ignore_index=True,
)
chromosomes = cytobands["chrom"].unique()
df = pd.DataFrame()
for chromosome in chromosomes:
chromosome_length = np.max(
cytobands[cytobands["chrom"] == chromosome]["end"].values
)
# get all markers for this chromosome
one_chrom_match_markers = one_chrom_match.loc[
one_chrom_match["chrom"] == chromosome
]
two_chrom_match_markers = two_chrom_match.loc[
two_chrom_match["chrom"] == chromosome
]
# background of chromosome
df = concat(df, chromosome, 0, chromosome_length, "gneg")
# add markers for shared DNA on one chromosome
for marker in one_chrom_match_markers.itertuples():
df = concat(df, chromosome, marker.start, marker.end, "one_chrom")
# add markers for shared DNA on both chromosomes
for marker in two_chrom_match_markers.itertuples():
df = concat(df, chromosome, marker.start, marker.end, "two_chrom")
# add centromeres
for item in cytobands.loc[
(cytobands["chrom"] == chromosome) & (cytobands["gie_stain"] == "acen")
].itertuples():
df = concat(df, chromosome, item.start, item.end, "centromere")
return df