def render(self, style=0): self.what = quod.What(self.get_sequence(), style=style) self.entities['what'] = self.what entlist = [] entlist = [self.what.entities[0]] return entlist
def render(self, style=0): what = quod.What(self.get_sequence(), style=style) self.entities['what'] = what entlist = [] for k in self.entities: entlist.append(self.entities[k]) return entlist
def colored_quod(seq1, seq2, linecolor1='red', linecolor2='blue', tmscolor1='orange', tmscolor2='cyan', outfile='test.png'): '''This example creates a standard hydropathy plot for two raw sequences, making sure to specify colors manually seq1: sequence 1 seq2: sequence 2 linecolor1: line color for sequence 1 linecolor2: line color for sequence 2 tmscolor1: tms color for sequence 1 tmscolor2: tms color for sequence 2 outfile: what to name the resulting figure''' plot = quod.Plot() plot.add(quod.What(seq1, tmscolor=tmscolor1, linecolor=linecolor1)) plot.add(quod.What(seq2, tmscolor=tmscolor2, linecolor=linecolor2)) plot.render() plot.save(outfile)
def render(self, style=0): for msa in self.alignments: self.what = quod.What('', style=style, nohmmtop=True) self.hydro = self.what.entities[0] self.hydro.Y = avehas3.get_average_hydropathies(msa, window=19) self.hydro.X = np.arange(0., len(self.hydro.Y)) self.entities['what'] = self.what entlist = [] entlist = [self.what.entities[0]] if self.amphipathicity: amphi = quod.Hydropathy('', style='g') amphi.Y = avehas3.get_average_amphipathicities(msa, window=19) amphi.X = np.arange(0, len(amphi.Y)) entlist.append(amphi) entlist.append( avehas3.TMcenter(avehas3.get_tmcenters(msa), ymin=-3, ymax=-2.4)) simil = avehas3.get_similarities(msa) window = 10 ymin = -3 ymax = -1.5 scores = np.array([ np.nanmean(simil[i:i + window]) for i in range(0, len(simil) - window) ]) normscores = (scores - min(scores)) / (max(scores) - min(scores)) scaledscores = normscores * (ymax - ymin) shiftedscores = scaledscores + ymin similcurve = quod.Hydropathy('', style='gray') similcurve.Y = shiftedscores similcurve.X = np.arange(0, len(shiftedscores)) + window // 2 entlist.append(similcurve) if self.occupancy: occcurve = quod.Hydropathy('', style='y') occcurve.Y = avehas3.get_occupancies(msa) occcurve.X = np.arange(len(occcurve.Y)) entlist.append(occcurve) #what's the worst that can happen??? return entlist
def entropy_quod(*sequences, **kwargs): '''This example plots the entropies of multiple sequences sequences: raw sequences **kwargs: outfile: where to put the resulting figure''' outfile = kwargs['outfile'] if 'outfile' in kwargs else kwargs['outfile'] plot = quod.Plot() for i, seq in enumerate(sequences): plot.add(quod.What(seq, style=i, mode='entropy')) plot.render() plot.save(outfile)
def simple_quod(*sequences, **kwargs): '''This example creates a standard hydropathy plot from several raw sequences and saves it with a specific filename if given *sequences: raw sequences **kwargs: window: window size for hydropathy averaging (default: 19) outfile: what to name the resulting figure''' outfile = 'test.png' if ('outfile' not in kwargs) else kwargs['outfile'] window = 19 if ('window' not in kwargs) else kwargs['window'] plot = quod.Plot() for i, seq in enumerate(sequences): plot.add(quod.What(seq, style=i, window=window)) plot.render() plot.save(outfile)
def walls_quod(*sequences, **kwargs): '''This example plots sequences with walls+wedges defining certain intervals *sequences: raw sequences **kwargs: intervals: a list of Interval objects to generate walls+wedges from (default: []) outfile: what to name the resulting figure (default: test.png)''' plot = quod.Plot() intervals = [] if 'intervals' not in kwargs else kwargs['intervals'] outfile = 'test.png' if 'outfile' not in kwargs else kwargs['outfile'] mode = 'wall' if 'mode' not in kwargs else kwargs['mode'] for i in intervals: plot.add(i.get_auto()) for n, seq in enumerate(sequences): plot.add(quod.What(seq, style=n)) plot.render() plot.save(outfile)
def run_quod(cfg): entities = {} maxlens = {} for name in cfg['subplots']: entities[name] = [] maxlens[name] = 0 for seq in cfg['sequences'][name]: entities[name].append(quod.What(seq)) maxlens[name] = max(maxlens[name], len(entities[name][-1])) #walls if name in cfg['walls']: for walldef in cfg['walls'][name]: entities[name].append(quod.Wall(spans=[[walldef['start'], walldef['end']]], y=walldef['y'], ylim=walldef['lim'], thickness=walldef['thickness'], wedge=walldef['thickness'])) #domains if name in cfg['domains']: for domaindef in cfg['domains'][name]: entities[name].append(quod.Region( spans=domaindef['xlim'], yspan=domaindef['ylim'], label=domaindef['label'], style=domaindef['color'], pos=domaindef['pos'], size=domaindef['fontsize'], center=domaindef['halign'] )) cfg['weights'][name] *= maxlens[name] if 'tms' in cfg: do_tms_stuff(entities, cfg) fig = Figure() canvas = FigureCanvas(fig) fig.set_tight_layout(True) gs = gridspec.GridSpec(len(cfg['rowscheme']), cfg['hres']) hgap = cfg['hgap']/cfg['width']/2 margin = 0.03 if 'margin' not in cfg else cfg['margin'] gs.update( left=margin + hgap, right=cfg['width'] - margin, top=cfg['height'] - margin-hgap, bottom=margin, wspace=0) def get_limit(wt1, wtlist, offset=0): x = int((offset + wt1/sum(wtlist)) * cfg['hres']) return max(0, min(x, cfg['hres'])) if cfg['mode'] == 'hvordan': lims = [] cfg['lims'] = {} for namelist in cfg['rowscheme']: row = [cfg['weights'][name] for name in namelist] last = -hgap if len(namelist) == 1: cfg['lims'][namelist[0]] = [0, cfg['hres']] else: bounds = [0] s = 0 rawweights = [cfg['weights'][name] for name in namelist] weights = [w/sum(rawweights) for w in rawweights] for i in range(len(namelist) - 1): bounds.append((weights[i] - hgap) * cfg['hres']) bounds.append((weights[i] + hgap) * cfg['hres']) #for i in namelist bounds.append(cfg['hres']) bounds = [int(x) for x in bounds] for i in range(0, len(namelist)): name = namelist[i] cfg['lims'][name] = [bounds[2*i], bounds[2*i + 1]] axdict = {} for r, row in enumerate(cfg['rowscheme']): for name in row: #axdict[name] = fig.add_subplot(gs[r, cfg['lims'][name][0]:cfg['lims'][name][1]]) axdict[name] = fig.add_subplot(gs[r,cfg['lims'][name][0]:cfg['lims'][name][1]]) n = 0 name2row = {} stretchlabel = {} firstcol = set() for r, row in enumerate(cfg['rowscheme']): for c, name in enumerate(row): if not c: firstcol.add(name) name2row[name] = r if 'ylabel' in cfg and name in cfg['ylabel']: ylabel = cfg['ylabel'][name] else: ylabel = '' if c else None yticks = [] if c else None plot(cfg, name, fig, canvas, axdict[name], entities[name], ylabel=ylabel, yticks=yticks) try: title = cfg['title'][name] except KeyError: title = chr(65 + n) axdict[name].set_title(title, loc='left') n += 1 if len(row) > 1: ax = fig.add_subplot(gs[r,:]) ax.set_xticks([0]) ax.axes.get_yaxis().set_visible(False) ax.set_frame_on(False) #TODO: expose customizing xlabels per-plot/per-row ax.set_xlabel('Position') ax.tick_params(labelcolor=(0,0,0,0), color=(0,0,0,0)) stretchlabel[r] = ax elif len(row) == 1: #ax = fig.add_subplot(gs[r,:]) ax = axdict[row[0]] ax.set_xlabel('Position') stretchlabel[r] = ax if 'xlabel' in cfg: for name in cfg['xlabel']: stretchlabel[name2row[name]].set_xlabel(cfg['xlabel'][name]) if 'ylabel' in cfg: for name in cfg['ylabel']: stretchlabel[name2row[name]].set_ylabel(cfg['ylabel'][name]) if 'font' in cfg: for name in cfg['font']: for target in cfg['font'][name]: if target.endswith('ticks'): axdict[name].tick_params(labelsize=cfg['font'][name][target]) if name in firstcol: stretchlabel[name2row[name]].tick_params(labelsize=cfg['font'][name][target]) elif target.endswith('xaxis'): axdict[name].set_xlabel(axdict[name].get_xlabel(), fontsize=cfg['font'][name][target]) stretchlabel[name2row[name]].set_xlabel(stretchlabel[name2row[name]].get_xlabel(), fontsize=cfg['font'][name][target]) elif target.endswith('yaxis'): axdict[name].set_ylabel(axdict[name].get_ylabel(), fontsize=cfg['font'][name][target]) elif target == 'title': axdict[name].set_title(axdict[name].get_title(), fontsize=cfg['font'][name][target]) #gs.tight_layout(fig, pad=cfg['margin'], w_pad=cfg['hgap'], h_pad=0.0) gs.tight_layout(fig, pad=0, w_pad=cfg['hgap'], h_pad=cfg['vgap']) fig.savefig(cfg['outfile'], dpi=cfg['dpi']) else: raise NotImplementedError('Unimplemented mode: {}'.format(cfg['mode']))
def quod_set(seqids, sequences, indir, outdir, dpi=300, force=False, bars=[], prefix='', suffix='', silent=False, pars=[], kernel=None): ''' generates QUOD plots for batches of sequences ''' if not os.path.isdir(outdir): os.mkdir(outdir) #wedges = [[[x, 2 * (0.5 - (i % 2))] for i, x in enumerate(span)] for span in bars] ove = lambda x: int(2 * (0.5 - (x % 2))) wedges = [] for i, span in enumerate(bars): wedges.append([]) if 1 <= i <= 2: y = -2 else: y = -2 wedges[-1].append(quod.Wall(spans=[span], y=y, ylim=[0, 0.5])) medges = [] for i, span in enumerate(pars): medges.append([]) y = 2 medges[-1].append(quod.Wall(spans=[span], y=y, ylim=[0.5, 1])) domains = [] styledict = {} for i, seqid in enumerate(seqids): #if i < 2: color = 'red' #else: color = 'blue' #domains.append(parse_pfam('{}/../pfam/{}.pfam'.format(indir, seqid), color=color)) entities, styledict = parse_pfam('{}/../pfam/{}.pfam'.format( indir, seqid), styledict=styledict) domains.append(entities) #Draw A: barred by B #quod.what([sequences[seqids[0]]], force_seq=True, title=seqids[0], imgfmt='png', outdir=outdir, outfile=(seqids[0] + '_' + seqids[1] + '.png'), dpi=dpi, hide=1, entities=wedges[0]+domains[0], silent=True, width=15, height=3) halfwidth = 7.5 halfheight = 2 fig_a = quod.plt.figure() ax_a = fig_a.add_subplot(111) plot_a = quod.Plot(fig=fig_a, ax=ax_a) plot_a.add(quod.What(sequences[seqids[0]], style=0, kernel=kernel)) for e in wedges[0] + domains[0]: plot_a.add(e) plot_a.width = halfwidth plot_a.height = halfheight plot_a.render() plot_a.ax.set_title(seqids[0]) plot_a.fig.savefig('{}/{}_{}.png'.format(outdir, seqids[0], seqids[1]), dpi=dpi) #Draw B: barred by C #quod.what([sequences[seqids[1]]], force_seq=True, title=seqids[1], imgfmt='png', outdir=outdir, outfile=(seqids[1] + '_' + seqids[2] + '.png'), dpi=dpi, hide=1, entities=wedges[1]+medges[0]+domains[1], silent=True, width=15, height=3) fig_b = quod.plt.figure() ax_b = fig_b.add_subplot(111) plot_b = quod.Plot(fig=fig_b, ax=ax_b) plot_b.add(quod.What(sequences[seqids[1]], style=0, kernel=kernel)) for e in wedges[1] + medges[0] + domains[1]: plot_b.add(e) plot_b.width = halfwidth plot_b.height = halfheight plot_b.render() plot_b.ax.set_title(seqids[1]) plot_b.fig.savefig('{}/{}_{}.png'.format(outdir, seqids[1], seqids[2]), dpi=dpi) #Draw C: barred by B #quod.what([sequences[seqids[2]]], force_seq=True, title=seqids[2], imgfmt='png', outdir=outdir, outfile=(seqids[2] + '_' + seqids[1] + '.png'), dpi=dpi, hide=1, color=1, entities=wedges[2]+medges[1]+domains[2], silent=True, width=15, height=3) fig_c = quod.plt.figure() ax_c = fig_c.add_subplot(111) plot_c = quod.Plot(fig=fig_c, ax=ax_c) plot_c.add(quod.What(sequences[seqids[2]], style=1, kernel=kernel)) for e in wedges[2] + medges[1] + domains[2]: plot_c.add(e) plot_c.width = halfwidth plot_c.height = halfheight plot_c.render() plot_c.ax.set_title(seqids[2]) plot_c.fig.savefig('{}/{}_{}.png'.format(outdir, seqids[2], seqids[1]), dpi=dpi) #Draw D: barred by C #quod.what([sequences[seqids[3]]], force_seq=True, title=seqids[3], imgfmt='png', outdir=outdir, outfile=(seqids[3] + '_' + seqids[2] + '.png'), dpi=dpi, hide=1, color=1, entities=wedges[3]+domains[3], silent=True, width=15, height=3) fig_d = quod.plt.figure() ax_d = fig_d.add_subplot(111) plot_d = quod.Plot(fig=fig_d, ax=ax_d) plot_d.add(quod.What(sequences[seqids[3]], style=1, kernel=kernel)) for e in wedges[3] + domains[3]: plot_d.add(e) plot_d.width = halfwidth plot_d.height = halfheight plot_d.render() plot_d.ax.set_title(seqids[3]) plot_d.fig.savefig('{}/{}_{}.png'.format(outdir, seqids[3], seqids[2]), dpi=dpi)
def run_quod(cfg): entities = {} maxlens = {} for name in cfg['subplots']: entities[name] = [] maxlens[name] = 0 mode = cfg['mode'][name] if mode in ('hvordan', 'quod'): if cfg['frag'][name]: for i in range(0, len(cfg['sequences'][name]), 2): entities[name].append( quod.FragmentWhat(cfg['sequences'][name][i], cfg['sequences'][name][i + 1])) maxlens[name] = max(maxlens[name], len(entities[name][-1])) else: for seq in cfg['sequences'][name]: entities[name].append(quod.What(seq)) maxlens[name] = max(maxlens[name], len(entities[name][-1])) elif mode in ('avehas', ): if avehas3 is None: raise ImportError('Could not find avehas3.py') for seq in cfg['sequences'][name]: entities[name].append( avehas3.Avehas(io.BytesIO(seq.encode('utf-8')), amphi=cfg['amphi'][name])) #print(name, seq, maxlens[name]) #for msa in avehas3.AlignIO.parse( #print(len(entities[name][-1])) maxlens[name] = max(maxlens[name], len(entities[name][-1])) elif mode in ('empty', ): spacer = Spacer(length=cfg['baselength'][name]) maxlens[name] = cfg['baselength'][name] entities[name].append(spacer) for seq in cfg['sequences'][name]: #walls if name in cfg['walls']: for walldef in cfg['walls'][name]: entities[name].append( quod.Wall(spans=[[walldef['start'], walldef['end']]], y=walldef['y'], ylim=walldef['lim'], thickness=walldef['thickness'], wedge=walldef['thickness'])) #domains if name in cfg['domains']: for domaindef in cfg['domains'][name]: entities[name].append( quod.Region(spans=domaindef['xlim'], yspan=domaindef['ylim'], label=domaindef['label'], style=domaindef['color'], pos=domaindef['pos'], size=domaindef['fontsize'], center=domaindef['halign'])) if name in cfg['text']: label = cfg['text'][name] entities[name].append( quod.Text(label['pos'], label['text'], label.get('halign', 'l'), label.get('font', None))) if cfg['baselength'][name] is None: cfg['baselength'][name] = maxlens[name] #cfg['length'][name] = maxlens[name] #cfg['weight'][name] = maxlens[name] cfg['length'][name] = cfg['baselength'][name] * cfg['weight'][name] if 'tms' in cfg: do_tms_stuff(entities, cfg) fig = quod.Figure() fig.set_tight_layout(True) gs = gridspec.GridSpec(len(cfg['rowscheme']), cfg['hres']) hgap = cfg['hgap'] / cfg['width'] / 2 margin = 0.03 if 'margin' not in cfg else cfg['margin'] gs.update(left=margin + hgap, right=cfg['width'] - margin, top=cfg['height'] - margin - hgap, bottom=margin, wspace=0) def get_limit(wt1, wtlist, offset=0): x = int((offset + wt1 / sum(wtlist)) * cfg['hres']) return max(0, min(x, cfg['hres'])) if True: lims = [] cfg['lims'] = {} for namelist in cfg['rowscheme']: row = [cfg['length'][name] for name in namelist] last = -hgap if len(namelist) == 1: cfg['lims'][namelist[0]] = [0, cfg['hres']] else: bounds = [0] s = 0 rawweight = [cfg['length'][name] for name in namelist] weight = [w / sum(rawweight) for w in rawweight] for i in range(len(namelist) - 1): bounds.append((weight[i] - hgap) * cfg['hres']) bounds.append((weight[i] + hgap) * cfg['hres']) #for i in namelist bounds.append(cfg['hres']) bounds = [int(x) for x in bounds] for i in range(0, len(namelist)): name = namelist[i] cfg['lims'][name] = [bounds[2 * i], bounds[2 * i + 1]] axdict = {} for r, row in enumerate(cfg['rowscheme']): for name in row: #axdict[name] = fig.add_subplot(gs[r, cfg['lims'][name][0]:cfg['lims'][name][1]]) axdict[name] = fig.add_subplot( gs[r, cfg['lims'][name][0]:cfg['lims'][name][1]]) n = 0 name2row = {} stretchlabel = {} firstcol = set() for r, row in enumerate(cfg['rowscheme']): for c, name in enumerate(row): if not c: firstcol.add(name) name2row[name] = r if 'ylabel' in cfg and name in cfg['ylabel']: ylabel = cfg['ylabel'][name] else: ylabel = '' if c else None yticks = None #[] if c else None plot(cfg, name, fig, axdict[name], entities[name], ylabel=ylabel, yticks=yticks) if c: axdict[name].set_yticklabels( [] * len(axdict[name].get_yticklabels())) try: title = cfg['title'][name] except KeyError: title = chr(65 + n) titlefont = get_titlefont(cfg, name) #TODO: implement rowtitle separately #axdict[name].set_title(cfg['title'].get(name, ''), loc='left', fontsize=titlefont) titlepad = quod.matplotlib.rcParams['axes.titlepad'] transOffset = matplotlib.transforms.ScaledTranslation( 0., titlepad / 72., fig.dpi_scale_trans) if name in cfg['ctitle']: subtitlefont = get_titlefont(cfg, name, subname='ctitle', default=titlefont) t = axdict[name].text(0.5, 1.0, cfg['ctitle'].get(name, ''), ha='center', va='baseline', fontsize=subtitlefont, transform=axdict[name].transAxes) t.set_transform(axdict[name].transAxes + transOffset) if name in cfg['ltitle']: subtitlefont = get_titlefont(cfg, name, subname='ltitle', default=titlefont) t = axdict[name].text(0.0, 1.0, cfg['ltitle'].get(name, ''), ha='left', va='baseline', fontsize=subtitlefont, transform=axdict[name].transAxes) t.set_transform(axdict[name].transAxes + transOffset) if name in cfg['rtitle']: subtitlefont = get_titlefont(cfg, name, subname='rtitle', default=titlefont) t = axdict[name].text(1.0, 1.0, cfg['rtitle'].get(name, ''), ha='right', va='baseline', fontsize=subtitlefont, transform=axdict[name].transAxes) t.set_transform(axdict[name].transAxes + transOffset) if name in cfg['title']: axdict[name].set_title(cfg['title'].get(name, ''), loc='left', fontsize=titlefont) n += 1 if len(row) > 1: ax = fig.add_subplot(gs[r, :]) ax.set_xticks([0]) ax.axes.get_yaxis().set_visible(False) #ax.axes.get_xaxis().set_visible(False) ax.set_frame_on(False) #TODO: expose customizing xlabels per-plot/per-row ax.set_xlabel('Position') ax.tick_params(labelcolor=(1, 1, 1, 0), color=(1, 1, 1, 0)) for side in ['left', 'right', 'bottom', 'top']: ax.spines[side].set_color((1, 1, 1, 0)) ax.spines[side].set_linewidth(0) stretchlabel[r] = ax elif len(row) == 1: #ax = fig.add_subplot(gs[r,:]) ax = axdict[row[0]] ax.set_xlabel('Position') stretchlabel[r] = ax if 'xlabel' in cfg: for name in cfg['xlabel']: if name.startswith('row:'): stretchlabel[name2row[name[4:]]].set_xlabel( cfg['xlabel'][name]) else: axdict[name].set_xlabel(cfg['xlabel'][name]) stretchlabel[name2row[name]].set_xlabel(' ') if 'ylabel' in cfg: for name in cfg['ylabel']: stretchlabel[name2row[name]].set_ylabel(cfg['ylabel'][name]) if 'font' in cfg: for name in cfg['font']: for target in cfg['font'][name]: if target.endswith('ticks'): axdict[name].tick_params( labelsize=cfg['font'][name][target]) if name in firstcol: stretchlabel[name2row[name]].tick_params( labelsize=cfg['font'][name][target]) elif target.endswith('xaxis'): axdict[name].set_xlabel( axdict[name].get_xlabel(), fontsize=cfg['font'][name][target]) stretchlabel[name2row[name]].set_xlabel( stretchlabel[name2row[name]].get_xlabel(), fontsize=cfg['font'][name][target]) elif target.endswith('yaxis'): axdict[name].set_ylabel( axdict[name].get_ylabel(), fontsize=cfg['font'][name][target]) #gs.tight_layout(fig, pad=cfg['margin'], w_pad=cfg['hgap'], h_pad=0.0) #gs.tight_layout(fig, pad=0, w_pad=cfg['hgap'], h_pad=cfg['vgap']) gs.tight_layout(fig, pad=cfg['margin'], w_pad=cfg['hgap'], h_pad=cfg['vgap']) fig.savefig(cfg['outfile'], dpi=cfg['dpi']) else: raise NotImplementedError('Unimplemented mode: {}'.format(cfg['mode']))