Skip to content

Commit

Permalink
Send logger to stderr (#611)
Browse files Browse the repository at this point in the history
* Set logging level from INFO to DEBUG to match old behavior

* Use logger in graphics.chromosome

* Send to stderr instead
  • Loading branch information
tanghaibao authored Nov 24, 2023
1 parent 0c8bebf commit 2215984
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 30 deletions.
6 changes: 3 additions & 3 deletions jcvi/apps/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@ def debug(level=logging.DEBUG):
debug()


def get_logger(name: str):
def get_logger(name: str, level: int = logging.DEBUG):
"""Return a logger with a default ColoredFormatter."""
logger = logging.getLogger(name)
if logger.hasHandlers():
logger.handlers.clear()
logger.addHandler(RichHandler())
logger.addHandler(RichHandler(console=Console(stderr=True)))
logger.propagate = False
logger.setLevel(logging.INFO)
logger.setLevel(level)
return logger


Expand Down
6 changes: 2 additions & 4 deletions jcvi/graphics/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
FancyArrowPatch,
FancyBboxPatch,
)
from matplotlib.path import Path
from typing import Optional

from ..apps.base import datadir, glob, listify, logger, sample_N, which
Expand Down Expand Up @@ -313,7 +312,6 @@ def savefig(figname, dpi=150, iopts=None, cleanup=True):
format = "pdf"
try:
logger.debug("Matplotlib backend is: %s", mpl.get_backend())
logger.debug("Attempting save as: %s", figname)
plt.savefig(figname, dpi=dpi, format=format)
except Exception as e:
logger.error("savefig failed with message:\n%s", e)
Expand All @@ -324,9 +322,9 @@ def savefig(figname, dpi=150, iopts=None, cleanup=True):
remove(figname)
sys.exit(1)

msg = "Figure saved to `{0}`".format(figname)
msg = f"Figure saved to `{figname}`"
if iopts:
msg += " {0}".format(iopts)
msg += f" {iopts}"
logger.debug(msg)

if cleanup:
Expand Down
40 changes: 18 additions & 22 deletions jcvi/graphics/chromosome.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@
Legacy script to plot distribution of certain classes onto chromosomes. Adapted
from the script used in the Tang et al. PNAS 2010 paper, sigma figure.
"""
import logging
import sys
from itertools import groupby
from math import ceil
from natsort import natsorted
from typing import Tuple

import numpy as np

from jcvi.apps.base import OptionGroup, OptionParser, datafile, sample_N
from jcvi.formats.base import DictFile, get_number
from jcvi.formats.bed import Bed
from jcvi.formats.sizes import Sizes
from jcvi.graphics.base import (
from natsort import natsorted

from ..apps.base import OptionGroup, OptionParser, datafile, logger, sample_N
from ..formats.base import DictFile, get_number
from ..formats.bed import Bed
from ..formats.sizes import Sizes
from ..graphics.base import (
CirclePolygon,
Polygon,
Rectangle,
Expand All @@ -29,7 +29,7 @@
set1_n,
set3_n,
)
from jcvi.graphics.glyph import BaseGlyph, plot_cap
from ..graphics.glyph import BaseGlyph, plot_cap


class Chromosome(BaseGlyph):
Expand Down Expand Up @@ -236,7 +236,7 @@ def __init__(
# tip = length of the ticks
y1, y2 = sorted((y1, y2))
ax.plot([x, x], [y1, y2], "-", color=fc, lw=2)
max_marker_name, max_chr_len = max(markers, key=lambda x: x[-1])
_, max_chr_len = max(markers, key=lambda x: x[-1])
r = y2 - y1
ratio = r / max_chr_len
marker_pos = {}
Expand Down Expand Up @@ -314,7 +314,7 @@ def write_ImageMapLine(tlx, tly, brx, bry, w, h, dpi, chr, segment_start, segmen
"""
tlx, brx = [canvas2px(x, w, dpi) for x in (tlx, brx)]
tly, bry = [canvas2px(y, h, dpi) for y in (tly, bry)]
chr, bac_list = chr.split(":")
chr, _ = chr.split(":")
return (
'<area shape="rect" coords="'
+ ",".join(str(x) for x in (tlx, tly, brx, bry))
Expand Down Expand Up @@ -358,7 +358,7 @@ def draw_cytoband(
bands = pd.read_csv(filename, sep="\t")
chrombands = bands[bands["#chrom"] == chrom]
data = []
for i, (chr, start, end, name, gie) in chrombands.iterrows():
for _, (chr, start, end, name, gie) in chrombands.iterrows():
data.append((chr, start, end, name, gie))
chromsize = max(x[2] for x in data)
scale = width * 1.0 / chromsize
Expand Down Expand Up @@ -541,9 +541,7 @@ def draw_chromosomes(
mappings = dict((x, x) for x in classes)
preset_colors = {}

logging.debug(
"A total of {} classes found: {}".format(len(classes), ",".join(classes))
)
logger.debug("A total of %d classes found: %s", len(classes), ",".join(classes))

# Assign colors to classes
ncolors = max(3, min(len(classes), 12))
Expand All @@ -552,14 +550,14 @@ def draw_chromosomes(
colorset = sample_N(colorset, len(classes), seed=iopts.seed)
class_colors = dict(zip(classes, colorset))
class_colors.update(preset_colors)
logging.debug("Assigned colors: {}".format(class_colors))
logger.debug("Assigned colors: %s", class_colors)

chr_lens = {}
centromeres = {}
if sizes:
chr_lens = Sizes(sizes).sizes_mapping
else:
for b, blines in groupby(bed, key=(lambda x: x.seqid)):
for b, blines in groupby(bed, key=lambda x: x.seqid):
blines = list(blines)
maxlen = max(x.end for x in blines)
chr_lens[b] = maxlen
Expand Down Expand Up @@ -630,11 +628,9 @@ def draw_chromosomes(
prev_end, prev_klass = b.end, klass

if imagemap:
"""
`segment` : size of current BAC being investigated + `excess`
`excess` : left-over bases from the previous BAC, as a result of
iterating over `winsize` regions of `segment`
"""
# `segment` : size of current BAC being investigated + `excess`
# `excess` : left-over bases from the previous BAC, as a result of
# iterating over `winsize` regions of `segment`
if excess == 0:
segment_start = start
segment = (end - start + 1) + excess
Expand Down Expand Up @@ -700,7 +696,7 @@ def draw_chromosomes(
if imagemap:
print("</map>", file=mapfh)
mapfh.close()
logging.debug("Image map written to `{0}`".format(mapfh.name))
logger.debug("Image map written to `%s`", mapfh.name)

if gauge:
xstart, ystart = 0.9, 0.85
Expand Down
2 changes: 1 addition & 1 deletion jcvi/graphics/synteny.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import numpy as np
import matplotlib.transforms as transforms
from matplotlib.path import Path

from ..apps.base import OptionParser, logger
from ..compara.synteny import BlockFile
Expand All @@ -31,7 +32,6 @@
markup,
plt,
savefig,
Path,
PathPatch,
AbstractLayout,
)
Expand Down

0 comments on commit 2215984

Please sign in to comment.