<s> import os . path as op <EOL> import sys <EOL> import logging <EOL> from functools import partial <EOL> from random import sample <EOL> import numpy as np <EOL> import matplotlib as mpl <EOL> mpl . use ( '<STR_LIT>' ) <EOL> import matplotlib . pyplot as plt <EOL> import matplotlib . ticker as ticker <EOL> from matplotlib import cm , rc <EOL> from matplotlib . patches import Rectangle , Polygon , CirclePolygon , PathPatch , FancyArrow , FancyArrowPatch <EOL> from matplotlib . path import Path <EOL> from jcvi . utils . brewer2mpl import get_map <EOL> from jcvi . formats . base import LineFile <EOL> from jcvi . apps . console import dark , green <EOL> from jcvi . apps . base import glob , listify , datadir <EOL> class ImageOptions ( object ) : <EOL> def __init__ ( self , opts ) : <EOL> self . w , self . h = [ int ( x ) for x in opts . figsize . split ( '<STR_LIT:x>' ) ] <EOL> self . dpi = opts . dpi <EOL> self . format = opts . format <EOL> self . cmap = cm . get_cmap ( opts . cmap ) <EOL> self . opts = opts <EOL> def __str__ ( self ) : <EOL> return "<STR_LIT>" . format ( self . dpi * self . w , self . dpi * self . h ) <EOL> @ property <EOL> def diverge ( self ) : <EOL> colors = get_map ( self . opts . diverge , '<STR_LIT>' , <NUM_LIT:5> ) . mpl_colors <EOL> return colors [ <NUM_LIT:0> ] , colors [ - <NUM_LIT:1> ] <EOL> class TextHandler ( object ) : <EOL> def __init__ ( self , fig ) : <EOL> self . heights = [ ] <EOL> try : <EOL> self . build_height_array ( fig ) <EOL> except ValueError : <EOL> logging . debug ( "<STR_LIT>" ) <EOL> @ classmethod <EOL> def get_text_width_height ( cls , fig , txt = "<STR_LIT>" , size = <NUM_LIT:12> , usetex = True ) : <EOL> tp = mpl . textpath . TextPath ( ( <NUM_LIT:0> , <NUM_LIT:0> ) , txt , size = size , usetex = usetex ) <EOL> bb = tp . get_extents ( ) <EOL> xmin , ymin = fig . transFigure . inverted ( ) . transform ( ( bb . xmin , bb . ymin ) ) <EOL> xmax , ymax = fig . transFigure . inverted ( ) . transform ( ( bb . xmax , bb . ymax ) ) <EOL> return xmax - xmin , ymax - ymin <EOL> def build_height_array ( self , fig , start = <NUM_LIT:1> , stop = <NUM_LIT> ) : <EOL> for i in xrange ( start , stop + <NUM_LIT:1> ) : <EOL> w , h = TextHandler . get_text_width_height ( fig , size = i ) <EOL> self . heights . append ( ( h , i ) ) <EOL> def select_fontsize ( self , height , minsize = <NUM_LIT:1> , maxsize = <NUM_LIT:12> ) : <EOL> if not self . heights : <EOL> return maxsize if height > <NUM_LIT> else minsize <EOL> from bisect import bisect_left <EOL> i = bisect_left ( self . heights , ( height , ) ) <EOL> size = self . heights [ i - <NUM_LIT:1> ] [ <NUM_LIT:1> ] if i else minsize <EOL> size = min ( size , maxsize ) <EOL> return size <EOL> class AbstractLayout ( LineFile ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , filename , delimiter = '<STR_LIT:U+002C>' ) : <EOL> super ( AbstractLayout , self ) . __init__ ( filename ) <EOL> def assign_array ( self , attrib , array ) : <EOL> assert len ( array ) == len ( self ) <EOL> for x , c in zip ( self , array ) : <EOL> if not getattr ( x , attrib ) : <EOL> setattr ( x , attrib , c ) <EOL> def assign_colors ( self ) : <EOL> colorset = get_map ( '<STR_LIT>' , '<STR_LIT>' , <NUM_LIT:8> ) . mpl_colors <EOL> colorset = sample ( colorset , len ( self ) ) <EOL> self . assign_array ( "<STR_LIT>" , colorset ) <EOL> def assign_markers ( self ) : <EOL> markerset = sample ( mpl . lines . Line2D . filled_markers , len ( self ) ) <EOL> self . assign_array ( "<STR_LIT>" , markerset ) <EOL> def __str__ ( self ) : <EOL> return "<STR_LIT:\n>" . join ( str ( x ) for x in self ) <EOL> CHARS = { <EOL> '<STR_LIT:&>' : r'<STR_LIT>' , <EOL> '<STR_LIT:%>' : r'<STR_LIT>' , <EOL> '<STR_LIT:$>' : r'<STR_LIT>' , <EOL> '<STR_LIT:#>' : r'<STR_LIT>' , <EOL> '<STR_LIT:_>' : r'<STR_LIT>' , <EOL> '<STR_LIT:{>' : r'<STR_LIT>' , <EOL> '<STR_LIT:}>' : r'<STR_LIT>' , <EOL> } <EOL> def latex ( s ) : <EOL> return "<STR_LIT>" . join ( [ CHARS . get ( char , char ) for char in s ] ) <EOL> def shorten ( s , maxchar = <NUM_LIT:20> ) : <EOL> if len ( s ) <= maxchar : <EOL> return s <EOL> pad = ( maxchar - <NUM_LIT:3> ) / <NUM_LIT:2> <EOL> return s [ : pad ] + "<STR_LIT>" + s [ - pad : ] <EOL> def prettyplot ( ) : <EOL> set2 = get_map ( '<STR_LIT>' , '<STR_LIT>' , <NUM_LIT:8> ) . mpl_colors <EOL> set1 = get_map ( '<STR_LIT>' , '<STR_LIT>' , <NUM_LIT:9> ) . mpl_colors <EOL> reds = mpl . cm . Reds <EOL> reds . set_bad ( '<STR_LIT>' ) <EOL> reds . set_under ( '<STR_LIT>' ) <EOL> blues_r = mpl . cm . Blues_r <EOL> blues_r . set_bad ( '<STR_LIT>' ) <EOL> blues_r . set_under ( '<STR_LIT>' ) <EOL> blue_red = get_map ( '<STR_LIT>' , '<STR_LIT>' , <NUM_LIT:11> , <EOL> reverse = True ) . mpl_colormap <EOL> green_purple = get_map ( '<STR_LIT>' , '<STR_LIT>' , <NUM_LIT:11> ) . mpl_colormap <EOL> red_purple = get_map ( '<STR_LIT>' , '<STR_LIT>' , <NUM_LIT:9> ) . mpl_colormap <EOL> return blues_r , reds , blue_red , set1 , set2 , green_purple , red_purple <EOL> blues_r , reds , blue_red , set1 , set2 , green_purple , red_purple = prettyplot ( ) <EOL> def normalize_axes ( axes ) : <EOL> axes = listify ( axes ) <EOL> for ax in axes : <EOL> ax . set_xlim ( <NUM_LIT:0> , <NUM_LIT:1> ) <EOL> ax . set_ylim ( <NUM_LIT:0> , <NUM_LIT:1> ) <EOL> ax . set_axis_off ( ) <EOL> def panel_labels ( ax , labels , size = <NUM_LIT:16> ) : <EOL> for xx , yy , panel_label in labels : <EOL> panel_label = r"<STR_LIT>" . format ( panel_label ) <EOL> ax . text ( xx , yy , panel_label , size = size , <EOL> ha = "<STR_LIT>" , va = "<STR_LIT>" ) <EOL> def savefig ( figname , dpi = <NUM_LIT> , iopts = None ) : <EOL> try : <EOL> format = figname . rsplit ( "<STR_LIT:.>" , <NUM_LIT:1> ) [ - <NUM_LIT:1> ] . lower ( ) <EOL> except : <EOL> format = "<STR_LIT>" <EOL> try : <EOL> plt . savefig ( figname , dpi = dpi , format = format ) <EOL> except Exception as e : <EOL> message = "<STR_LIT>" <EOL> message += "<STR_LIT>" . format ( str ( e ) ) <EOL> logging . error ( message ) <EOL> rc ( '<STR_LIT:text>' , ** { '<STR_LIT>' : False } ) <EOL> plt . savefig ( figname , dpi = dpi ) <EOL> msg = "<STR_LIT>" . format ( figname ) <EOL> if iopts : <EOL> msg += "<STR_LIT>" . format ( iopts ) <EOL> logging . debug ( msg ) <EOL> plt . rcdefaults ( ) <EOL> def human_readable ( x , pos , base = False ) : <EOL> x = str ( int ( x ) ) <EOL> if x . endswith ( "<STR_LIT>" ) : <EOL> x = x [ : - <NUM_LIT:9> ] + "<STR_LIT>" <EOL> elif x . endswith ( "<STR_LIT>" ) : <EOL> x = x [ : - <NUM_LIT:6> ] + "<STR_LIT:M>" <EOL> elif x . endswith ( "<STR_LIT>" ) : <EOL> x = x [ : - <NUM_LIT:3> ] + "<STR_LIT>" <EOL> if base and x [ - <NUM_LIT:1> ] in "<STR_LIT>" : <EOL> x += "<STR_LIT:b>" <EOL> return x <EOL> human_readable_base = partial ( human_readable , base = True ) <EOL> human_formatter = ticker . FuncFormatter ( human_readable ) <EOL> human_base_formatter = ticker . FuncFormatter ( human_readable_base ) <EOL> mb_formatter = ticker . FuncFormatter ( lambda x , pos : "<STR_LIT>" . format ( int ( x / <NUM_LIT> ) ) ) <EOL> mb_float_formatter = ticker . FuncFormatter ( lambda x , pos : "<STR_LIT>" . format ( x / <NUM_LIT> ) ) <EOL> kb_formatter = ticker . FuncFormatter ( lambda x , pos : "<STR_LIT>" . format ( int ( x / <NUM_LIT:1000> ) ) ) <EOL> def set_human_axis ( ax , formatter = human_formatter ) : <EOL> ax . xaxis . set_major_formatter ( formatter ) <EOL> ax . yaxis . set_major_formatter ( formatter ) <EOL> set_human_base_axis = partial ( set_human_axis , formatter = human_base_formatter ) <EOL> available_fonts = [ op . basename ( x ) for x in glob ( datadir + "<STR_LIT>" ) ] <EOL> def fontprop ( ax , name , size = <NUM_LIT:12> ) : <EOL> assert name in available_fonts , "<STR_LIT>" . format ( available_fonts ) <EOL> import matplotlib . font_manager as fm <EOL> fname = op . join ( datadir , name ) <EOL> prop = fm . FontProperties ( fname = fname , size = size ) <EOL> logging . debug ( "<STR_LIT>" . format ( name , prop . get_file ( ) ) ) <EOL> for text in ax . texts : <EOL> text . set_fontproperties ( prop ) <EOL> return prop <EOL> def markup ( s ) : <EOL> import re <EOL> s = latex ( s ) <EOL> s = re . sub ( "<STR_LIT>" , r"<STR_LIT>" , s ) <EOL> return s <EOL> def setup_theme ( context = '<STR_LIT>' , style = "<STR_LIT>" , palette = '<STR_LIT>' , font = '<STR_LIT>' ) : <EOL> try : <EOL> import seaborn as sns <EOL> extra_rc = { "<STR_LIT>" : <NUM_LIT:1> , <EOL> "<STR_LIT>" : <NUM_LIT:1> , <EOL> "<STR_LIT>" : '<STR_LIT:k>' , <EOL> } <EOL> sns . set ( context = context , style = style , palette = palette , rc = extra_rc ) <EOL> except ( ImportError , SyntaxError ) : <EOL> pass <EOL> rc ( '<STR_LIT:text>' , usetex = True ) <EOL> if font == "<STR_LIT>" : <EOL> rc ( '<STR_LIT>' , ** { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT>' : [ '<STR_LIT>' ] } ) <EOL> elif font == "<STR_LIT>" : <EOL> rc ( '<STR_LIT>' , ** { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT>' : [ '<STR_LIT>' ] } ) <EOL> elif font == "<STR_LIT>" : <EOL> rc ( '<STR_LIT>' , ** { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT>' : [ '<STR_LIT>' ] } ) <EOL> setup_theme ( ) <EOL> def asciiaxis ( x , digit = <NUM_LIT:1> ) : <EOL> if isinstance ( x , int ) : <EOL> x = str ( x ) <EOL> elif isinstance ( x , float ) : <EOL> x = "<STR_LIT>" . format ( x , digit ) <EOL> elif isinstance ( x , np . ndarray ) : <EOL> assert len ( x ) == <NUM_LIT:2> <EOL> x = str ( x ) . replace ( "<STR_LIT:]>" , "<STR_LIT:)>" ) <EOL> return x <EOL> def asciiplot ( x , y , digit = <NUM_LIT:1> , width = <NUM_LIT:50> , title = None , char = "<STR_LIT:=>" ) : <EOL> """<STR_LIT>""" <EOL> ax = np . array ( x ) <EOL> ay = np . array ( y ) <EOL> if title : <EOL> print >> sys . stderr , dark ( title ) <EOL> az = ay * width / ay . max ( ) <EOL> tx = [ asciiaxis ( x , digit = digit ) for x in ax ] <EOL> rjust = max ( [ len ( x ) for x in tx ] ) + <NUM_LIT:1> <EOL> for x , y , z in zip ( tx , ay , az ) : <EOL> x = x . rjust ( rjust ) <EOL> y = y or "<STR_LIT>" <EOL> z = green ( char * z ) <EOL> print >> sys . stderr , "<STR_LIT>" . format ( x , z , y ) <EOL> def print_colors ( palette , outfile = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> fig = plt . figure ( ) <EOL> ax = fig . add_subplot ( <NUM_LIT> ) <EOL> xmax = <NUM_LIT:20> * ( len ( palette ) + <NUM_LIT:1> ) <EOL> x1s = np . arange ( <NUM_LIT:0> , xmax , <NUM_LIT:20> ) <EOL> xintervals = [ <NUM_LIT:10> ] * len ( palette ) <EOL> xx = zip ( x1s , xintervals ) <EOL> ax . broken_barh ( xx , ( <NUM_LIT:5> , <NUM_LIT:10> ) , facecolors = palette ) <EOL> ax . set_ylim ( <NUM_LIT:0> , <NUM_LIT:20> ) <EOL> ax . set_xlim ( <NUM_LIT:0> , xmax ) <EOL> ax . set_axis_off ( ) <EOL> savefig ( outfile ) <EOL> def discrete_rainbow ( N = <NUM_LIT:7> , cmap = cm . Set1 , usepreset = True , shuffle = False , plot = False ) : <EOL> """<STR_LIT>""" <EOL> import random <EOL> from scipy import interpolate <EOL> if usepreset : <EOL> if <NUM_LIT:0> < N <= <NUM_LIT:5> : <EOL> cmap = cm . gist_rainbow <EOL> elif N <= <NUM_LIT:20> : <EOL> cmap = cm . Set1 <EOL> else : <EOL> sys . exit ( discrete_rainbow . __doc__ ) <EOL> cdict = cmap . _segmentdata . copy ( ) <EOL> colors_i = np . linspace ( <NUM_LIT:0> , <NUM_LIT:1.> , N ) <EOL> indices = np . linspace ( <NUM_LIT:0> , <NUM_LIT:1.> , N + <NUM_LIT:1> ) <EOL> rgbs = [ ] <EOL> for key in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> D = np . array ( cdict [ key ] ) <EOL> I = interpolate . interp1d ( D [ : , <NUM_LIT:0> ] , D [ : , <NUM_LIT:1> ] ) <EOL> colors = I ( colors_i ) <EOL> rgbs . append ( colors ) <EOL> A = np . zeros ( ( N + <NUM_LIT:1> , <NUM_LIT:3> ) , float ) <EOL> A [ : , <NUM_LIT:0> ] = indices <EOL> A [ <NUM_LIT:1> : , <NUM_LIT:1> ] = colors <EOL> A [ : - <NUM_LIT:1> , <NUM_LIT:2> ] = colors <EOL> L = [ ] <EOL> for l in A : <EOL> L . append ( tuple ( l ) ) <EOL> cdict [ key ] = tuple ( L ) <EOL> palette = zip ( * rgbs ) <EOL> if shuffle : <EOL> random . shuffle ( palette ) <EOL> if plot : <EOL> print_colors ( palette ) <EOL> return mpl . colors . LinearSegmentedColormap ( '<STR_LIT>' , cdict , <NUM_LIT> ) , palette <EOL> def get_intensity ( octal ) : <EOL> from math import sqrt <EOL> r , g , b = octal [ <NUM_LIT:1> : <NUM_LIT:3> ] , octal [ <NUM_LIT:3> : <NUM_LIT:5> ] , octal [ <NUM_LIT:5> : ] <EOL> r , g , b = int ( r , <NUM_LIT:16> ) , int ( g , <NUM_LIT:16> ) , int ( b , <NUM_LIT:16> ) <EOL> intensity = sqrt ( ( r * r + g * g + b * b ) / <NUM_LIT:3> ) <EOL> return intensity <EOL> def adjust_spines ( ax , spines ) : <EOL> for loc , spine in ax . spines . items ( ) : <EOL> if loc in spines : <EOL> pass <EOL> else : <EOL> spine . set_color ( '<STR_LIT:none>' ) <EOL> if '<STR_LIT:left>' in spines : <EOL> ax . yaxis . set_ticks_position ( '<STR_LIT:left>' ) <EOL> else : <EOL> ax . yaxis . set_ticks_position ( '<STR_LIT:right>' ) <EOL> if '<STR_LIT>' in spines : <EOL> ax . xaxis . set_ticks_position ( '<STR_LIT>' ) <EOL> else : <EOL> ax . xaxis . set_ticks_position ( '<STR_LIT>' ) <EOL> def set_ticklabels_helvetica ( ax , xcast = int , ycast = int ) : <EOL> xticklabels = [ xcast ( x ) for x in ax . get_xticks ( ) ] <EOL> yticklabels = [ ycast ( x ) for x in ax . get_yticks ( ) ] <EOL> ax . set_xticklabels ( xticklabels , family = '<STR_LIT>' ) <EOL> ax . set_yticklabels ( yticklabels , family = '<STR_LIT>' ) <EOL> def draw_cmap ( ax , cmap_text , vmin , vmax , cmap = None , reverse = False ) : <EOL> Y = np . outer ( np . ones ( <NUM_LIT:10> ) , np . arange ( <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT> ) ) <EOL> if reverse : <EOL> Y = Y [ : : - <NUM_LIT:1> ] <EOL> xmin , xmax = <NUM_LIT> , <NUM_LIT> <EOL> ymin , ymax = <NUM_LIT> , <NUM_LIT> <EOL> ax . imshow ( Y , extent = ( xmin , xmax , ymin , ymax ) , cmap = cmap ) <EOL> ax . text ( xmin - <NUM_LIT> , ( ymin + ymax ) * <NUM_LIT> , markup ( cmap_text ) , <EOL> ha = "<STR_LIT:right>" , va = "<STR_LIT>" , size = <NUM_LIT:10> ) <EOL> vmiddle = ( vmin + vmax ) * <NUM_LIT> <EOL> xmiddle = ( xmin + xmax ) * <NUM_LIT> <EOL> for x , v in zip ( ( xmin , xmiddle , xmax ) , ( vmin , vmiddle , vmax ) ) : <EOL> ax . text ( x , ymin - <NUM_LIT> , "<STR_LIT>" % v , ha = "<STR_LIT>" , va = "<STR_LIT>" , size = <NUM_LIT:10> ) <EOL> def write_messages ( ax , messages ) : <EOL> """<STR_LIT>""" <EOL> tc = "<STR_LIT>" <EOL> axt = ax . transAxes <EOL> yy = <NUM_LIT> <EOL> for msg in messages : <EOL> ax . text ( <NUM_LIT> , yy , msg , color = tc , transform = axt , ha = "<STR_LIT:right>" ) <EOL> yy -= <NUM_LIT> <EOL> def quickplot ( data , xmin , xmax , xlabel , title , ylabel = "<STR_LIT>" , <EOL> figname = "<STR_LIT>" , counts = True , print_stats = True ) : <EOL> """<STR_LIT>""" <EOL> plt . figure ( <NUM_LIT:1> , ( <NUM_LIT:6> , <NUM_LIT:6> ) ) <EOL> left , height = zip ( * sorted ( data . items ( ) ) ) <EOL> pad = max ( height ) * <NUM_LIT> <EOL> if counts : <EOL> for l , h in zip ( left , height ) : <EOL> if xmax and l > xmax : <EOL> break <EOL> plt . text ( l , h + pad , str ( h ) , color = "<STR_LIT>" , size = <NUM_LIT:8> , <EOL> ha = "<STR_LIT>" , va = "<STR_LIT>" , rotation = <NUM_LIT> ) <EOL> if xmax is None : <EOL> xmax = max ( left ) <EOL> plt . bar ( left , height , align = "<STR_LIT>" ) <EOL> plt . xlabel ( markup ( xlabel ) ) <EOL> plt . ylabel ( markup ( ylabel ) ) <EOL> plt . title ( markup ( title ) ) <EOL> plt . xlim ( ( xmin - <NUM_LIT> , xmax + <NUM_LIT> ) ) <EOL> messages = [ ] <EOL> counts_over_xmax = sum ( [ v for k , v in data . items ( ) if k > xmax ] ) <EOL> if counts_over_xmax : <EOL> messages += [ "<STR_LIT>" . format ( xmax , counts_over_xmax ) ] <EOL> kk = [ ] <EOL> for k , v in data . items ( ) : <EOL> kk += [ k ] * v <EOL> messages += [ "<STR_LIT>" . format ( np . sum ( height ) ) ] <EOL> messages += [ "<STR_LIT>" . format ( np . max ( kk ) ) ] <EOL> messages += [ "<STR_LIT>" . format ( np . min ( kk ) ) ] <EOL> messages += [ "<STR_LIT>" . format ( np . mean ( kk ) ) ] <EOL> messages += [ "<STR_LIT>" . format ( np . median ( kk ) ) ] <EOL> ax = plt . gca ( ) <EOL> if print_stats : <EOL> write_messages ( ax , messages ) <EOL> set_human_axis ( ax ) <EOL> set_ticklabels_helvetica ( ax ) <EOL> savefig ( figname ) </s>
