File: plotCorrelation.py

package info (click to toggle)
python-deeptools 3.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 34,624 kB
  • sloc: python: 14,765; xml: 4,090; sh: 38; makefile: 11
file content (260 lines) | stat: -rw-r--r-- 10,831 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
import argparse
import numpy as np
import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['svg.fonttype'] = 'none'
from deeptools import cm  # noqa: F401
import matplotlib.pyplot as plt

from deeptools.correlation import Correlation
from deeptools.parserCommon import writableFile
from deeptools._version import __version__

old_settings = np.seterr(all='ignore')


def parse_arguments(args=None):
    basic_args = plot_correlation_args()
    heatmap_parser = heatmap_options()
    scatter_parser = scatterplot_options()
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="""
Tool for the analysis and visualization of sample correlations based on the output of multiBamSummary or
multiBigwigSummary. Pearson or Spearman methods are available to compute correlation
coefficients. Results can be saved as multiple
scatter plots depicting the pairwise correlations or as a clustered heatmap,
where the colors represent the correlation coefficients and the clusters are constructed using complete linkage.
Optionally, the values can be saved as tables, too.


detailed help:

  plotCorrelation -h

""",
        epilog='example usages:\n'
               'plotCorrelation -in results_file --whatToPlot heatmap --corMethod pearson -o heatmap.png\n\n'
               ' \n\n',
        parents=[basic_args, heatmap_parser, scatter_parser])

    return parser


def plot_correlation_args():
    parser = argparse.ArgumentParser(add_help=False)
    required = parser.add_argument_group('Required arguments')

    # define the arguments
    required.add_argument('--corData', '-in',
                          metavar='FILE',
                          help='Compressed matrix of values generated by multiBigwigSummary or multiBamSummary',
                          required=True)

    required.add_argument('--corMethod', '-c',
                          help="Correlation method.",
                          choices=['spearman', 'pearson'],
                          required=True)

    required.add_argument('--whatToPlot', '-p',
                          help="Choose between a heatmap or pairwise scatter plots",
                          choices=['heatmap', 'scatterplot'],
                          required=True)

    optional = parser.add_argument_group('Optional arguments')
    optional.add_argument('--plotFile', '-o',
                          help='File to save the heatmap to. The file extension determines the format, '
                          'so heatmap.pdf will save the heatmap in PDF format. '
                          'The available formats are: .png, '
                          '.eps, .pdf and .svg.',
                          type=writableFile,
                          metavar='FILE')

    optional.add_argument('--skipZeros',
                          help='By setting this option, genomic regions '
                          'that have zero or missing (nan) values in all samples '
                          'are excluded.',
                          action='store_true',
                          required=False)

    optional.add_argument('--labels', '-l',
                          metavar='sample1 sample2',
                          help='User defined labels instead of default labels from '
                          'file names. '
                          'Multiple labels have to be separated by spaces, e.g. '
                          '--labels sample1 sample2 sample3',
                          nargs='+')

    optional.add_argument('--plotTitle', '-T',
                          help='Title of the plot, to be printed on top of '
                          'the generated image. Leave blank for no title. (Default: %(default)s)',
                          default='')

    optional.add_argument('--plotFileFormat',
                          metavar='FILETYPE',
                          help='Image format type. If given, this option '
                          'overrides the image format based on the plotFile '
                          'ending. The available options are: png, '
                          'eps, pdf and svg.',
                          choices=['png', 'pdf', 'svg', 'eps', 'plotly'])

    optional.add_argument(
        '--removeOutliers',
        help='If set, bins with very large counts are removed. '
             'Bins with abnormally high reads counts artificially increase '
             'pearson correlation; that\'s why, multiBamSummary tries '
             'to remove outliers using the median absolute deviation (MAD) '
             'method applying a threshold of 200 to only consider extremely '
             'large deviations from the median. The ENCODE blacklist page '
             '(https://sites.google.com/site/anshulkundaje/projects/blacklists) '
             'contains useful information about regions with unusually high counts'
             'that may be worth removing.',
        action='store_true')

    optional.add_argument('--version', action='version',
                          version='%(prog)s {}'.format(__version__))

    group = parser.add_argument_group('Output optional options')

    group.add_argument('--outFileCorMatrix',
                       help='Save matrix with pairwise correlation values to a tab-separated file.',
                       metavar='FILE',
                       type=writableFile)

    return parser


def scatterplot_options():
    """
    Options specific for creating the scatter plot
    """
    parser = argparse.ArgumentParser(add_help=False)
    scatter_opts = parser.add_argument_group('Scatter plot options')

    scatter_opts.add_argument('--xRange',
                              help='The X axis range. The default scales these such that the full range of dots is displayed.',
                              type=int,
                              nargs=2,
                              default=None)

    scatter_opts.add_argument('--yRange',
                              help='The Y axis range. The default scales these such that the full range of dots is displayed.',
                              type=int,
                              nargs=2,
                              default=None)

    scatter_opts.add_argument('--log1p',
                              help='Plot the natural log of the scatter plot after adding 1. Note that this is ONLY for plotting, the correlation is unaffected.',
                              action='store_true')

    return parser


def heatmap_options():
    """
    Options for generating the correlation heatmap
    """
    parser = argparse.ArgumentParser(add_help=False)
    heatmap = parser.add_argument_group('Heatmap options')

    heatmap.add_argument('--plotHeight',
                         help='Plot height in cm. (Default: %(default)s)',
                         type=float,
                         default=9.5)

    heatmap.add_argument('--plotWidth',
                         help='Plot width in cm. The minimum value is 1 cm. (Default: %(default)s)',
                         type=float,
                         default=11)

    heatmap.add_argument('--zMin', '-min',
                         default=None,
                         help='Minimum value for the heatmap intensities. '
                              'If not specified, the value is set automatically',
                         type=float)

    heatmap.add_argument('--zMax', '-max',
                         default=None,
                         help='Maximum value for the heatmap intensities.'
                              'If not specified, the value is set automatically',
                         type=float)

    heatmap.add_argument(
        '--colorMap', default='jet',
        metavar='',
        help='Color map to use for the heatmap. Available values can be '
             'seen here: '
             'http://matplotlib.org/examples/color/colormaps_reference.html')

    heatmap.add_argument('--plotNumbers',
                         help='If set, then the correlation number is plotted '
                         'on top of the heatmap. This option is only valid when plotting a heatmap.',
                         action='store_true',
                         required=False)

    return parser


def main(args=None):

    args = parse_arguments().parse_args(args)

    if args.plotFile is None and args.outFileCorMatrix is None:
        sys.exit("At least one of --plotFile and --outFileCorMatrix must be specified!\n")

    corr = Correlation(args.corData,
                       args.corMethod,
                       labels=args.labels,
                       remove_outliers=args.removeOutliers,
                       skip_zeros=args.skipZeros)

    if args.corMethod == 'pearson':
        # test if there are outliers and write a message recommending the removal
        if len(corr.get_outlier_indices(np.asarray(corr.matrix).flatten())) > 0:
            if args.removeOutliers:
                sys.stderr.write("\nOutliers were detected in the data. They "
                                 "will be removed to avoid bias "
                                 "in the pearson correlation.\n")

            else:
                sys.stderr.write("\nOutliers were detected in the data. Consider "
                                 "using the --removeOutliers parameter to avoid a bias "
                                 "in the pearson correlation.\n")

    if args.colorMap:
        try:
            plt.get_cmap(args.colorMap)
        except ValueError as error:
            sys.stderr.write(
                "A problem was found. Message: {}\n".format(error))
            exit()

    if args.plotFile is not None:
        if args.whatToPlot == 'scatterplot':
            corr.plot_scatter(args.plotFile,
                              plot_title=args.plotTitle,
                              image_format=args.plotFileFormat,
                              xRange=args.xRange,
                              yRange=args.yRange,
                              log1p=args.log1p)
        else:
            corr.plot_correlation(args.plotFile,
                                  vmax=args.zMax,
                                  vmin=args.zMin,
                                  colormap=args.colorMap,
                                  plot_title=args.plotTitle,
                                  image_format=args.plotFileFormat,
                                  plot_numbers=args.plotNumbers,
                                  plotWidth=args.plotWidth,
                                  plotHeight=args.plotHeight)

    if args.outFileCorMatrix:
        o = open(args.outFileCorMatrix, "w")
        o.write("#plotCorrelation --outFileCorMatrix\n")
        corr.save_corr_matrix(o)
        o.close()