Skip to content

Commit

Permalink
Merge pull request #223 from deeptools/fix_plotHiC_matrix_on_small_ch…
Browse files Browse the repository at this point in the history
…romosomes

Improved colorbar scale when log1p options is used.
  • Loading branch information
joachimwolff committed May 8, 2018
2 parents 1d9200c + 1278a00 commit 97d4c8c
Show file tree
Hide file tree
Showing 25 changed files with 5,186 additions and 5,316 deletions.
2 changes: 1 addition & 1 deletion hicexplorer/HiCMatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,7 @@ def convert_to_obs_exp_matrix(self, maxdepth=None, zscore=False, perchr=False):
depth = max_depth_in_bins
else:
depth = m_size
estimated_size_dense_matrix = m_size**2 * 8
estimated_size_dense_matrix = m_size ** 2 * 8
if estimated_size_dense_matrix > 100e6:
log.info("To compute z-scores a dense matrix is required. This will use \n"
"{} Mb of memory.\n To reduce memory use the maxdeph option."
Expand Down
5 changes: 2 additions & 3 deletions hicexplorer/hicCorrectMatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ def parse_arguments(args=None):
"""
)

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

subparsers = parser.add_subparsers(
title="Options",
Expand Down Expand Up @@ -572,7 +571,7 @@ def main(args=None):

log.info("matrix contains {} data points. Sparsity {:.3f}.".format(
len(ma.matrix.data),
float(len(ma.matrix.data)) / (ma.matrix.shape[0]**2)))
float(len(ma.matrix.data)) / (ma.matrix.shape[0] ** 2)))

if args.skipDiagonal:
ma.diagflat(value=0)
Expand Down
2 changes: 1 addition & 1 deletion hicexplorer/hicFindTADs.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ def get_incremental_step_size(min_win_size, max_win_size, start_step_len):
step = -1
while 1:
step += 1
inc_step = min_win_size + int(start_step_len * (step**1.5))
inc_step = min_win_size + int(start_step_len * (step ** 1.5))
if step > 1 and inc_step == incremental_step[-1]:
continue
if inc_step > max_win_size:
Expand Down
47 changes: 21 additions & 26 deletions hicexplorer/hicPlotMatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
from hicexplorer._version import __version__
import numpy as np
import pyBigWig
from builtins import range
from past.builtins import zip

import argparse
Expand Down Expand Up @@ -138,9 +137,12 @@ def parse_arguments(args=None):
parserOpt.add_argument('--version', action='version',
version='%(prog)s {}'.format(__version__))

return parser
# Used for automatic testing
parserOpt.add_argument('--disable_tight_layout',
help=argparse.SUPPRESS,
action='store_true')

# relabel xticks
return parser


def relabel_ticks(pXTicks):
Expand Down Expand Up @@ -227,16 +229,8 @@ def plotHeatmap(ma, chrBinBoundaries, fig, position, args, cmap, xlabel=None,
cax = divider.append_axes("right", size="2.5%", pad=0.09)
else:
cax = pBigwig['axis_colorbar']
if args.log1p:
from matplotlib.ticker import LogFormatter
formatter = LogFormatter(10, labelOnlyBase=False)
# get a useful log scale
# that looks like [1, 2, 5, 10, 20, 50, 100, ... etc]
aa = np.array([1, 2, 5])
tick_values = np.concatenate([aa * 10 ** x for x in range(10)])
cbar = fig.colorbar(img3, ticks=tick_values, format=formatter, cax=cax)
else:
cbar = fig.colorbar(img3, cax=cax)

cbar = fig.colorbar(img3, cax=cax)

cbar.solids.set_edgecolor("face") # to avoid white lines in the color bar in pdf plots
if args.scoreName:
Expand Down Expand Up @@ -322,7 +316,7 @@ def plotPerChr(hic_matrix, cmap, args, pBigwig):
col = idx % chrom_per_row
if pBigwig:
inner_grid = gridspec.GridSpecFromSubplotSpec(2, 2, height_ratios=[0.85, 0.15], width_ratios=[0.93, 0.07],
subplot_spec=grids[row, col], wspace=0.0, hspace=0.1)
subplot_spec=grids[row, col], wspace=0.1, hspace=0.1)
axis = plt.subplot(inner_grid[0, 0])
axis_eigenvector = plt.subplot(inner_grid[1, 0])
axis_scale = plt.subplot(inner_grid[0, 1])
Expand All @@ -347,8 +341,6 @@ def plotPerChr(hic_matrix, cmap, args, pBigwig):
matrix[mask_nan] = np.nanmin(matrix[mask_nan == False])
matrix[mask_inf] = np.nanmin(matrix[mask_inf == False])

if args.log:
matrix = np.log(matrix)
except Exception:
log.debug("Clearing of matrix failed.")
log.debug("any nanafter remove of nan: {}".format(np.isnan(matrix).any()))
Expand All @@ -357,6 +349,9 @@ def plotPerChr(hic_matrix, cmap, args, pBigwig):
matrix += 1
norm = LogNorm()

elif args.log:
norm = LogNorm()

bigwig_info = None
if pBigwig:
bigwig_info = {'args': args, 'axis': None, 'axis_colorbar': None, 'nan_bins': hic_matrix.nan_bins}
Expand Down Expand Up @@ -560,14 +555,13 @@ def main(args=None):
matrix[mask_nan] = np.nanmin(matrix[mask_nan == False])
matrix[mask_inf] = np.nanmin(matrix[mask_inf == False])

if args.log:
matrix = np.log(matrix)

log.debug("any nan after remove of nan: {}".format(np.isnan(matrix).any()))
log.debug("any inf after remove of inf: {}".format(np.isinf(matrix).any()))
if args.log1p:
matrix += 1
norm = LogNorm()
elif args.log:
norm = LogNorm()

if args.bigwig:
# increase figure height to accommodate bigwig track
Expand Down Expand Up @@ -602,13 +596,14 @@ def main(args=None):
args, cmap, xlabel=chrom, ylabel=chrom2,
start_pos=start_pos1, start_pos2=start_pos2, pNorm=norm, pAxis=ax1, pBigwig=bigwig_info)

if args.perChromosome or args.bigwig:
try:
plt.tight_layout()
except UserWarning:
log.info("Failed to tight layout. Using regular plot.")
except ValueError:
log.info("Failed to tight layout. Using regular plot.")
if not args.disable_tight_layout:
if args.perChromosome or args.bigwig:
try:
plt.tight_layout()
except UserWarning:
log.info("Failed to tight layout. Using regular plot.")
except ValueError:
log.info("Failed to tight layout. Using regular plot.")

plt.savefig(args.outFileName, dpi=args.dpi)
plt.close(fig)
Expand Down

0 comments on commit 97d4c8c

Please sign in to comment.