Пример #1
0
def _draw_1d(axis,
             residues0,
             residues,
             codes,
             helices,
             contacts,
             ylabel,
             setylim,
             plottext=True):
    """
  Draw a residue contact probability plot

  Parameters
  ----------
  axis : Axis object
    the axis to draw on
  residues0 : numpy array
    the tick positions of the residues
  residues : numpy array
    the x-ray number of the residues
  codes : numpy array
    the 1 amino acid residue names
  helices : list
    the first and last residue index for each helix
  contacts : numpy array
    the contact probabilities
  ylabel : string
    the label of the y-axis
  setylim : boolean, optional
    if to set ylim to  [0, 100]
  plottext : boolean, optional
    if to put out text on the 95% residues
  """

    # Plot the average residue occupancy
    axis.plot(residues0, contacts, '--k')
    for i, h in enumerate(helices):
        c = colors.color(i) if i > 0 else colors.color(11)
        axis.plot(residues0[h[0] - 1:h[1]], contacts[h[0] - 1:h[1]], color=c)

    # Fix extent of axis and xticks
    axis.set_xlim([0, residues0[-1]])
    axis.set_ylim([0, setylim])
    sel = residues > 0
    axis.set_xticks(residues0[sel][::20])
    axis.set_xticklabels(residues[sel][::20])

    # Plot labels for the 95% percentile
    sel = contacts >= np.percentile(contacts, 98)
    text = ["%s%d" % (c, r) for c, r in zip(codes[sel], residues[sel])]
    if plottext: _plot_text(axis, text, residues0[sel], contacts[sel])
    print "\n" + ylabel
    print "\tAverage of 95 percentile %.3f" % (contacts[sel].mean())
    print "\t95 percentile: %s" % (", ".join(
        "%s:%.3f" % (t, c) for t, c in zip(text, contacts[sel])))

    axis.set_ylabel(ylabel)
    axis.set_xlabel("Residue")
Пример #2
0
def _draw_aa(axis, names, contacts_list, labels):
    """
  Draw an amino-acid averaged probability plot

  Parameters
  ----------
  axis : Axis object
    the axis to draw on
  names : list of string
    the residue names
  contact_list : list of numpy array
    the residue-residue joint probability for at least one group
  labels : list of strings
    the labels of the groups
  """
    def _aa_contacts(names, contacts):
        aas = pdb.codes.keys()
        aacount = {aa: 0 for aa in aas}
        aapp = {aa: 0 for aa in aas}
        # Accumulate probability and amino acid counts
        for name, pp in zip(names, contacts):
            aapp[name.lower()] += pp
            aacount[name.lower()] += 1
        # Compute average probability
        for aa in aas:
            if aacount[aa] == 0: continue
            aapp[aa] = aapp[aa] / float(aacount[aa])
        # Group histidine residues
        aapp["his"] = (aapp["his"] + aapp["hie"] + aapp["hid"] +
                       aapp["hip"]) / 4.0
        del aapp["hie"]
        del aapp["hid"]
        del aapp["hip"]

        aas = sorted(aapp.keys())
        return aas, np.array([aapp[aa] for aa in aas])

    n = len(contacts_list)
    aas = []
    for i, (contacts, label) in enumerate(zip(contacts_list, labels)):
        aas, height = _aa_contacts(names, contacts.diagonal())
        left = np.arange(1, len(aas) + 1) - 0.3 + 0.3 * i
        c = colors.color(i) if i > 0 else colors.color(11)
        axis.bar(left, height, width=0.6 / float(n), color=c, label=label)

    if len(labels) > 1:
        axis.legend(loc='best', fancybox=True, labelspacing=0.20)
    axis.set_xticks(left + 0.3)
    axis.set_xticklabels([aa.capitalize() for aa in aas], rotation='vertical')
    axis.set_xlim([0, left[-1] + 1.3])
    axis.set_ylabel("Average contact probability")
Пример #3
0
def _plot_single(data, errors, headers, barlabels, ylabel, fig):

    a = fig.add_axes((0.15,0.15,0.75,0.75))

    ngroups = data.shape[0]
    nitems = len(headers)

    gleft = 0.8*(np.arange(nitems)+1.0)
    width = gleft[-1] - gleft[0]
    left =  np.asarray([gleft+(width + 1.6)*i for i in range(ngroups)]).reshape(ngroups*nitems)
    gcolor = [colors.color(i) for i in range(nitems)]
    color = []
    labels = []
    for i in range(ngroups):
        color.extend(gcolor)
        labels.extend(barlabels)
    a.bar(left, data.T.reshape(ngroups*nitems), yerr=errors.T.reshape(ngroups*nitems),
            width=0.8, color=color, error_kw=dict(ecolor='k'))
    a.set_xticks(left+0.4)
    a.set_xticklabels(labels, rotation=45)

    for tick in a.xaxis.get_major_ticks() :
        tick.label.set_fontsize(8)
    for tick in a.yaxis.get_major_ticks() :
        tick.label.set_fontsize(8)
    a.set_ylim([data.min()-3.0,data.max()+3.0])
    for i,h  in enumerate(headers):
        a.text(left[nitems*i]+0.4,data.max()+4.0,h, size=10)
    a.set_ylabel(ylabel, fontsize=8)
Пример #4
0
def _plot_order(order_list, labels, figure):
    """
    Plot the distribution of a series in subplots
    """
    nchains = len(order_list[0])
    ncols = 2.0
    nrows = np.ceil(nchains / ncols)

    axes = []
    miny, maxy = 1.0, 0.0
    for ichain in range(nchains):
        a = figure.add_subplot(nrows, ncols, ichain + 1)
        axes.append(a)
        for i, (simorder, label) in enumerate(zip(order_list, labels)):
            order = simorder[ichain]
            miny = min(miny, order.min())
            maxy = max(maxy, order.max())
            a.plot(np.arange(1,
                             len(order) + 1, 1),
                   order,
                   '-*',
                   label=label,
                   color=colors.color(i))
        a.set_xticks(np.arange(0, len(order) + 2, 1))
        # Add legend and ticks
        if ichain == 0:
            a.legend(loc=1, fontsize=8)

    for a in axes:
        a.set_ylim([miny - 0.05, maxy + 0.05])
Пример #5
0
def _plot_data(figure, datalist, labels, ylabels, xlabels, ncols=3):
    if isinstance(ylabels,str):
        ylabels = [ylabels]*len(datalist)
        xlabels = [xlabels]*len(datalist)
        ilabels = False
    else:
        ilabels = True

    nrows = int(np.ceil(len(datalist)/float(ncols)))
    minv = np.floor(min([d.min() for d in datalist]))
    maxv = np.ceil(max([d.max() for d in datalist]))
    vrange = maxv - minv
    delta = np.ceil(vrange/8.0)
    ticks = np.arange(minv,maxv+1.0,delta)

    for i,(data,label,ylabel,xlabel) in enumerate(zip(datalist,labels,ylabels,xlabels),1):
        a = figure.add_subplot(nrows,ncols,i)
        a.plot(data[:,1],data[:,0],".",color=colors.color(i-1))
        tau,tpval = stats.kendalltau(data[:,1],data[:,0])
        r,rpval = stats.pearsonr(data[:,1],data[:,0])
        print "%s\t%.5f\t%.5f\t%.5f\t%5f"%(label,r,rpval,tau,tpval)
        a.plot([minv,maxv],[minv,maxv],"--k")
        a.set_xlim(minv,maxv)
        a.set_ylim(minv,maxv)
        a.set_xticks(ticks)
        a.set_yticks(ticks)
        if ilabels or a.is_first_col():
            a.set_ylabel(ylabel)
        if ilabels or a.is_last_row():
            a.set_xlabel(xlabel)
        a.text(0.05,0.92,label,transform=a.transAxes)
        a.set_aspect('equal')

    figure.tight_layout()
    print ""
Пример #6
0
def _plot_single(data, errors, headers, barlabels, ylabel, fig):

    a = fig.add_axes((0.2,0.15,0.75,0.75))

    ngroups = data.shape[0]
    nitems = len(headers)
    print ngroups, nitems

    gleft = 0.8*(np.arange(nitems)+1.0)
    width = gleft[-1] - gleft[0]
    left =  np.asarray([gleft+(width + 1.6)*i for i in range(ngroups)]).reshape(ngroups*nitems)
    gcolor = [colors.color(i) for i in range(nitems)]
    color = []
    labels = []
    for i in range(ngroups):
        color.extend(gcolor)
        labels.extend("")
    a.bar(left, data.reshape(ngroups*nitems), yerr=errors.reshape(ngroups*nitems),
            width=0.8, color=color, error_kw=dict(ecolor='k'), label=headers)
    a.set_xticks(left[::2]+width)
    a.set_xticklabels(barlabels)
    #a.legend()
    h, l = a.get_legend_handles_labels()
    a.legend(h[0], headers, loc='best', fancybox=True, framealpha=0.5,fontsize=8,labelspacing=0.20)

    for tick in a.xaxis.get_major_ticks() :
        tick.label.set_fontsize(8)
    for tick in a.yaxis.get_major_ticks() :
        tick.label.set_fontsize(8)
    a.set_ylim([data.min()-3.0,data.max()+3.0])
    #for i,h  in enumerate(barlabels):
    #    a.text(left[nitems*i]+0.4,data.min()-6.0,h, size=8)
    a.set_ylabel(ylabel, fontsize=8)
    a.set_xlabel("Docking pose", fontsize=8)
Пример #7
0
 def _plot_trace(self, trace, axis, idx):
     """
     Plot the trace, but make breaks if the
     atoms pass over the periodic box so that very long lines aren't drawn
     """
     xy = [trace[0].value]
     for prevrecord, record in zip(trace[:-1], trace[1:]):
         if np.abs(prevrecord.value[0]-record.value[0]) > self.halfbox[0] or \
             np.abs(prevrecord.value[1]-record.value[1]) > self.halfbox[1] :
             xy = np.asarray(xy)
             axis.plot(xy[:,0], xy[:,1], "-", color=colors.color(idx))
             xy = [record.value]
         else:
             xy.append(record.value)
     xy = np.asarray(xy)
     axis.plot(xy[:,0], xy[:,1], "-", color=colors.color(idx))
     axis.set_xlim(0, self.box[0])
     axis.set_ylim(0, self.box[1])
     axis.set_aspect('equal')
Пример #8
0
 def _plot_trace(self, trace, axis, idx):
     """
     Plot the trace, but make breaks if the
     atoms pass over the periodic box so that very long lines aren't drawn
     """
     xy = [trace[0].value]
     for prevrecord, record in zip(trace[:-1], trace[1:]):
         if np.abs(prevrecord.value[0]-record.value[0]) > self.halfbox[0] or \
             np.abs(prevrecord.value[1]-record.value[1]) > self.halfbox[1] :
             xy = np.asarray(xy)
             axis.plot(xy[:, 0], xy[:, 1], "-", color=colors.color(idx))
             xy = [record.value]
         else:
             xy.append(record.value)
     xy = np.asarray(xy)
     axis.plot(xy[:, 0], xy[:, 1], "-", color=colors.color(idx))
     axis.set_xlim(0, self.box[0])
     axis.set_ylim(0, self.box[1])
     axis.set_aspect('equal')
Пример #9
0
def _anal_contacts(filenames, labels, plot=[], time=None, window=None):
    """
  Main analysis routine
  
  Parameters
  ----------
  filenames : list of strings
    the files to read and analyse
  labels : list of strings
    the labels for the files
  plot : list of integers, optional
    the series to plot
  time : float, optional
    the total simulation time
  window : float, optional
    the window time for averaging
    
  Returns
  -------
  list of numpy array
    the produce result
  """

    # Read in state file from disc or combine them using expression evaluation
    states = []
    for filename, label in zip(filenames, labels):
        if os.path.isfile(filename):
            states.append(gpcr_lib.read_statefile(filename))
        else:
            states.append(
                gpcr_lib.logical_expr(filename.replace(" ", ""), *states))

    # Count the number of on states and write out statistics
    print "%18s\t%8s\t%8s" % ("", "Mean", "Std")
    results = []
    for i, (state, label) in enumerate(zip(states, labels), 1):
        counton = state.sum(axis=1)
        print "%-18s\t%8.3f\t%8.3f" % (label, counton.mean(), counton.std())
        results.append(np.array([counton.mean(), counton.std()]))

        if len(plot) > 0 and time is not None and i in plot:
            ns_per_snapshot = time / float(counton.shape[0])
            snapshot_per_window = window / ns_per_snapshot
            series = moving(counton, snapshot_per_window)
            f = plt.figure(i)
            x = np.arange(series.shape[0]) * ns_per_snapshot
            f.gca().plot(x, series, color=colors.color(plot.index(i)))
            f.gca().set_xlabel("Time (ns)")
            f.gca().set_ylabel(label)
            f.savefig("series%d.png" % (i), format="png", dpi=300)

    return results
Пример #10
0
def _anal_contacts(filenames,labels,plot=[],time=None,window=None) :
  """
  Main analysis routine
  
  Parameters
  ----------
  filenames : list of strings
    the files to read and analyse
  labels : list of strings
    the labels for the files
  plot : list of integers, optional
    the series to plot
  time : float, optional
    the total simulation time
  window : float, optional
    the window time for averaging
    
  Returns
  -------
  list of numpy array
    the produce result
  """
  
  # Read in state file from disc or combine them using expression evaluation
  states = []
  for filename,label in zip(filenames,labels) :
    if os.path.isfile(filename) :
      states.append(gpcr_lib.read_statefile(filename))
    else :
      states.append(gpcr_lib.logical_expr(filename.replace(" ",""),*states))
     
  # Count the number of on states and write out statistics      
  print "%18s\t%8s\t%8s"%("","Mean","Std")
  results = []
  for i,(state,label) in enumerate(zip(states,labels),1) : 
    counton = state.sum(axis=1)
    print "%-18s\t%8.3f\t%8.3f"%(label,counton.mean(),counton.std())  
    results.append(np.array([counton.mean(),counton.std()]))
    
    if len(plot) > 0 and time is not None and i in plot :
      ns_per_snapshot = time / float(counton.shape[0])
      snapshot_per_window = window / ns_per_snapshot
      series = moving(counton,snapshot_per_window)
      f = plt.figure(i)
      x = np.arange(series.shape[0])*ns_per_snapshot
      f.gca().plot(x,series,color=colors.color(plot.index(i)))
      f.gca().set_xlabel("Time (ns)")
      f.gca().set_ylabel(label)
      f.savefig("series%d.png"%(i),format="png",dpi=300)
    
  return results
Пример #11
0
def _plot_multi(data, errors, headers, barlabels, nrow, ncol, fig):

    for i, (idata, ierrors, header) in enumerate(zip(data.T, errors.T, headers), 1):
        a = fig.add_subplot(nrow, ncol, i)
        left = (np.arange(data.shape[0])+1)*2-0.4
        barcolors = [colors.color(i) for i in range(data.shape[0])]
        a.bar(left, idata, yerr=ierrors, color=barcolors, error_kw=dict(ecolor='k'))
        a.set_xticks(left+0.4)
        a.set_xticklabels(barlabels, rotation=45)
        a.set_ylabel(header, fontsize=8)
        for tick in a.xaxis.get_major_ticks() :
            tick.label.set_fontsize(8)
        for tick in a.yaxis.get_major_ticks() :
            tick.label.set_fontsize(8)
Пример #12
0
def _plot_multi(data, errors, headers, barlabels, nrow, ncol, fig):

    for i, (idata, ierrors, header) in enumerate(zip(data.T, errors.T, headers), 1):
        a = fig.add_subplot(nrow, ncol, i)
        left = (np.arange(data.shape[0])+1)*2-0.4
        barcolors = [colors.color(i) for i in range(data.shape[0])]
        a.bar(left, idata, yerr=ierrors, color=barcolors, error_kw=dict(ecolor='k'))
        a.set_xticks(left+0.4)
        a.set_xticklabels(barlabels, rotation=45)
        a.set_ylabel(header, fontsize=8)
        for tick in a.xaxis.get_major_ticks() :
            tick.label.set_fontsize(8)
        for tick in a.yaxis.get_major_ticks() :
            tick.label.set_fontsize(8)
Пример #13
0
def _draw_aa(axis,names,contacts_list,labels) :
  """
  Draw an amino-acid averaged probability plot
  
  Parameters
  ----------
  axis : Axis object
    the axis to draw on
  names : list of string
    the residue names
  contact_list : list of numpy array
    the residue-residue joint probability for at least one group
  labels : list of strings
    the labels of the groups
  """
  
  def _aa_contacts(names,contacts) :
    aas = pdb.codes.keys()
    aacount = {aa : 0 for aa in aas}
    aapp = {aa : 0 for aa in aas}
    # Accumulate probability and amino acid counts
    for name,pp in zip(names,contacts) :
      aapp[name.lower()] += pp
      aacount[name.lower()] += 1
    # Compute average probability
    for aa in aas :
      if aacount[aa] == 0 : continue
      aapp[aa] = aapp[aa] / float(aacount[aa])
    # Group histidine residues
    aapp["his"] = (aapp["his"]+aapp["hie"]+aapp["hid"]+aapp["hip"])/4.0
    del aapp["hie"]
    del aapp["hid"]
    del aapp["hip"]
    
    aas = sorted(aapp.keys())
    return aas,np.array([aapp[aa] for aa in aas])
    
  n = len(contacts_list)
  aas = []
  for i,(contacts,label) in enumerate(zip(contacts_list,labels)) :
    aas,height = _aa_contacts(names,contacts.diagonal())
    left = np.arange(1,len(aas)+1)-0.3+0.3*i
    axis.bar(left,height,width=0.6/float(n),color=colors.color(i),label=label)
  
  if len(labels) > 1 : axis.legend(loc='best', fancybox=True,labelspacing=0.20)  
  axis.set_xticks(left+0.3)
  axis.set_xticklabels([aa.capitalize() for aa in aas],rotation='vertical')
  axis.set_xlim([0,left[-1]+1.3])
  axis.set_ylabel("Average contact probability")
Пример #14
0
def _draw_1d(axis,residues0,residues,codes,helices,contacts,ylabel,setylim,plottext=True) :
  """
  Draw a residue contact probability plot
  
  Parameters
  ----------
  axis : Axis object
    the axis to draw on
  residues0 : numpy array
    the tick positions of the residues
  residues : numpy array
    the x-ray number of the residues
  codes : numpy array
    the 1 amino acid residue names
  helices : list
    the first and last residue index for each helix
  contacts : numpy array
    the contact probabilities
  ylabel : string
    the label of the y-axis
  setylim : boolean, optional
    if to set ylim to  [0, 100]
  plottext : boolean, optional
    if to put out text on the 95% residues
  """
  
  # Plot the average residue occupancy
  axis.plot(residues0,contacts,'--k')
  for i,h in enumerate(helices) :
    axis.plot(residues0[h[0]-1:h[1]],contacts[h[0]-1:h[1]],color=colors.color(i))
    
  # Fix extent of axis and xticks
  axis.set_xlim([0,residues0[-1]])
  axis.set_ylim([0,setylim])
  sel = residues > 0
  axis.set_xticks(residues0[sel][::20])
  axis.set_xticklabels(residues[sel][::20])
  
  # Plot labels for the 95% percentile
  sel = contacts >= np.percentile(contacts,98)
  text = ["%s%d"%(c,r) for c,r in zip(codes[sel],residues[sel])]
  if plottext : _plot_text(axis,text,residues0[sel],contacts[sel])
  print "\n"+ylabel
  print "\tAverage of 95 percentile %.3f"%(contacts[sel].mean())
  print "\t95 percentile: %s"%(", ".join("%s:%.3f"%(t,c) for t,c in zip(text,contacts[sel])))
  
  axis.set_ylabel(ylabel)
  axis.set_xlabel("Residue")
Пример #15
0
def _plot_single(data, errors, headers, barlabels, ylabel, fig):

    a = fig.add_axes((0.2, 0.15, 0.75, 0.75))

    ngroups = data.shape[0]
    nitems = len(headers)
    print ngroups, nitems

    gleft = 0.8 * (np.arange(nitems) + 1.0)
    width = gleft[-1] - gleft[0]
    left = np.asarray([gleft + (width + 1.6) * i
                       for i in range(ngroups)]).reshape(ngroups * nitems)
    gcolor = [colors.color(i) for i in range(nitems)]
    color = []
    labels = []
    for i in range(ngroups):
        color.extend(gcolor)
        labels.extend("")
    a.bar(left,
          data.reshape(ngroups * nitems),
          yerr=errors.reshape(ngroups * nitems),
          width=0.8,
          color=color,
          error_kw=dict(ecolor='k'),
          label=headers)
    a.set_xticks(left[::2] + width)
    a.set_xticklabels(barlabels)
    #a.legend()
    h, l = a.get_legend_handles_labels()
    a.legend(h[0],
             headers,
             loc='best',
             fancybox=True,
             framealpha=0.5,
             fontsize=8,
             labelspacing=0.20)

    for tick in a.xaxis.get_major_ticks():
        tick.label.set_fontsize(8)
    for tick in a.yaxis.get_major_ticks():
        tick.label.set_fontsize(8)
    a.set_ylim([data.min() - 3.0, data.max() + 3.0])
    #for i,h  in enumerate(barlabels):
    #    a.text(left[nitems*i]+0.4,data.min()-6.0,h, size=8)
    a.set_ylabel(ylabel, fontsize=8)
    a.set_xlabel("Docking pose", fontsize=8)
Пример #16
0
def _plot_data(figure, datalist, labels, ylabels, xlabels, ncols=4, minv=None, maxv=None):
    if isinstance(ylabels,str):
        ylabels = [ylabels]*len(datalist)
        xlabels = [xlabels]*len(datalist)
        ilabels = False
    else:
        ilabels = True

    nrows = int(np.ceil(len(datalist)/float(ncols)))
    if minv is None :
        minv = np.floor(min([d.min() for d in datalist]))
    if maxv is None :
        maxv = np.ceil(max([d.max() for d in datalist]))
    print "Limits = %.2f %.2f"%(minv, maxv)
    vrange = maxv - minv
    delta = np.ceil(vrange/4.0)
    ticks = np.arange(minv,maxv+1.0,delta)

    for i,(data,label,ylabel,xlabel) in enumerate(zip(datalist,labels,ylabels,xlabels),1):
        a = figure.add_subplot(nrows,ncols,i)
        fit = np.polyfit(data[:,0],data[:,1],1)
        a.plot([fit[0]*minv+fit[1],fit[0]*maxv+fit[1]],[minv,maxv],"-k")
        a.plot([minv,maxv],[minv,maxv],"--k")    
        a.plot(data[:,1],data[:,0],".",color=colors.color(i-1))
        tau,tpval = stats.kendalltau(data[:,1],data[:,0])
        r,rpval = stats.pearsonr(data[:,1],data[:,0])
        print "%s\t%.5f\t%.5f\t%.5f\t%5f"%(label,r,rpval,tau,tpval)

        a.set_xlim(minv,maxv)
        a.set_ylim(minv,maxv)
        a.set_xticks(ticks)
        a.set_yticks(ticks)
        if ilabels or a.is_first_col():
            a.set_ylabel(ylabel)
        if ilabels or a.is_last_row():
            a.set_xlabel(xlabel)
        a.text(0.05,0.90,label,transform=a.transAxes, fontsize='9')
        a.set_aspect('equal')

    figure.tight_layout()
    print ""
Пример #17
0
    for fi, filename in enumerate(args.file) :
        xvals, densities, ylabel = _parse_xvgfile(filename)
        midi = int(np.ceil(xvals.shape[0]/2.0))
        if args.shiftdens is not None:
            maxi = np.argmax(densities[args.shiftdens][:midi])
            xvals = xvals - xvals[:midi][maxi]
        if args.half :
            xvals = xvals[:midi]
        for di, density in enumerate(args.densities):
            idx = di if len(args.file) == 1 else fi
            y = densities[density]
            if args.half :
                y = y[:midi]
            if args.scale is not None:
                y = y / args.scale[idx]
            a.plot(xvals , y, "-", color=colors.color(idx),label=args.label[idx])

    if len(args.file) > 1 or len(args.densities) > 1 :
        a.legend(loc='best', fancybox=True, framealpha=0.5,fontsize=8,labelspacing=0.20)

    for tick in a.xaxis.get_major_ticks() :
        tick.label.set_fontsize(8)
    for tick in a.yaxis.get_major_ticks() :
        tick.label.set_fontsize(8)
    if args.xlabel is None :
        if args.shiftdens is not None:
            a.set_xlabel("Distance from %s [nm]"%args.shiftdens,fontsize=8)
        else:
            a.set_xlabel("z [nm]",fontsize=8)
    else :
        a.set_xlabel(args.xlabel,fontsize=8)
Пример #18
0
def _plot_dists(serieslist, labels, fflist, figure):
    """
    Plot the distribution of a series in subplots
    """
    nseries = len(fflist)
    ncols = 3.0
    nrows = np.ceil(nseries / ncols)
    RT = 303.0 * 8.314 / 4.184 / 1000.0

    for iseries in range(nseries):
        a = figure.add_subplot(nrows, ncols, iseries + 1)
        minval = 1000
        maxval = -1000
        stdval = 0
        # Plot the density for each simulated system
        lines = []
        for i, (series, label) in enumerate(zip(serieslist, labels)):
            s = series[iseries]
            x = s.points
            if isinstance(fflist[iseries].contype, elbalib.BondType):
                x = x * 0.1
            #l, = a.plot((x[1:]+x[:-1])/2.0, s.histo(), color=colors.color(i), label=label)
            l, = a.plot(x, s.density(), color=colors.color(i), label=label)
            lines.append(l)
            stdval = max(stdval, np.round(2.0 * s.std, 0), 0.5)
            minval = min(minval, np.floor(s.points.min()))
            maxval = max(maxval, np.ceil(s.points.max()))
        # Calculate the range of the x axis
        mean, std = fflist[iseries].contype.statmoments(RT)
        minval = min(minval, np.floor(mean - 2.0 * std))
        maxval = max(maxval, np.ceil(mean + 2.0 * std))
        # Plot the force field ideal distribution
        x = np.arange(minval, maxval, 0.1)
        y = fflist[iseries].contype.distribution(x, RT,trans=False)
        if isinstance(fflist[iseries].contype, elbalib.BondType):
            x = x * 0.1
        l, = a.plot(x, y, color=colors.color(len(labels)), label="ff")
        lines.append(l)
        stdval = max(stdval, np.round(2.0 * std, 0), 0.5)
        if isinstance(fflist[iseries].contype, elbalib.AngleType):
            minval = max(-1.0,minval)
            maxval = min(1.0,maxval)
            if stdval == 0.0 : stdval = np.cos(np.pi/4.0)

        # Add legend and ticks
        #if iseries == 0:
    #        a.legend(loc=3, fontsize=8,bbox_to_anchor = (0,1.02,1,0.102),
    #        mode="expand",ncol=2)
        a.set_yticks([])
        x = np.arange(minval, maxval+stdval, stdval)
        if isinstance(fflist[iseries].contype, elbalib.BondType):
            x = x * 0.1
        a.set_xticks(x)
        if isinstance(fflist[iseries].contype, elbalib.AngleType):
            a.set_xticklabels(np.rad2deg(np.arccos(x)))
            a.invert_xaxis()
        a.text(0.05,0.85,fflist[iseries].atomstring(),fontsize=8,transform=a.transAxes)
    labels2 = list(labels)
    labels2.append("ff")
    figure.legend(lines,labels2,loc=(0.03,0.95),fontsize=8,ncol=6)
    if isinstance(fflist[iseries].contype, elbalib.AngleType):
        figure.suptitle("Valance angle [deg]",y=0.05)
    else:
        figure.suptitle("Bond length [nm]",y=0.05)
    #figure.subplots_adjust(top=0.90)
    figure.tight_layout(rect=(0,0.025,1,0.96))
Пример #19
0
                        default="bar.png")
    parser.add_argument('--xlabel', nargs="+", help="the x label")
    parser.add_argument('--ylabel', help="the y label")
    args = parser.parse_args()

    f = plt.figure()
    a = f.gca()
    for i, (filename, label) in enumerate(zip(args.file, args.label)):
        data = parsing.parse2ndarray(filename)
        left = np.arange(
            data.shape[0]) + 0.38 + i * 0.75 / float(len(args.file))
        a.bar(left,
              data[:, 0],
              yerr=data[:, 1],
              width=1.0 / float(len(args.file)) * 0.75,
              color=colors.color(i),
              label=label,
              error_kw=dict(ecolor='black'))

    if len(args.file) > 1:
        a.legend(bbox_to_anchor=(0., 1.02, 1., .102),
                 loc=3,
                 ncol=4,
                 mode="expand",
                 borderaxespad=0.0,
                 fontsize=11)
    for tick in a.xaxis.get_major_ticks():
        tick.label.set_fontsize(8)
    for tick in a.yaxis.get_major_ticks():
        tick.label.set_fontsize(8)
    if args.xlabel is not None: a.set_xlabel(args.xlabel, fontsize=8)
Пример #20
0
        if args.multicol is not None:
            args.ycol = args.multicol[i]
        if data.shape[1] == 1: args.ycol = 0
        y = data[n:, args.ycol] * args.yfactor
        if data.shape[1] > 1:
            x = data[n:, args.xcol] * args.xfactor
        else:
            x = np.arange(1, len(y) + 1) * args.xfactor
        if args.stride is not None:
            x = x[::args.stride]
            y = y[::args.stride]
        if args.histogram is not None:
            y, x = np.histogram(y, bins=args.histogram)
            x = 0.5 * (x[:-1] + x[1:])
        stl = defaultstyle if args.nostyle else colors.style(i)
        ln = axis.plot(x, y, stl, color=colors.color(i), label=label)

        ylim[0] = min(ylim[0], y.min())
        ylim[1] = max(ylim[1], y.max())
        xlim[0] = min(xlim[0], y.min())
        xlim[1] = max(xlim[1], y.max())

        lines.append(ln[0])
        if args.errorbars:
            yerr = data[n:, args.ycol + 1] * args.yfactor
            plt.fill_between(x,
                             y - yerr,
                             y + yerr,
                             facecolor='grey',
                             linewidth=0,
                             alpha=0.4,
Пример #21
0
    def plot(self,
             axis,
             leaflet,
             centroid=None,
             reverseY=True,
             sigmas=None,
             sidechain=False,
             colorscheme=None,
             drawchol=True,
             specialres=None,
             rotate2D=None):
        """
    Plot the structure on a 2D grid

    Parameters
    ----------
    axis : Axis object
      the matplotlib Axis object to draw on
    leaflet : string
      the leaflet to draw
    reverseY : boolean, optional
      if the y coordinate should be reversed
      used to distinguish between an look-up or look-down view
    sigmas : numpy array, optional
      sizes of atoms
    sidechain : boolean, optional
      if we should draw sidechains
    colorscheme : list, optional
      colors to use if not pre-defined
    drawchol : boolean, optional
      if to draw cholesterols if they exists
    specialres : list of int
      residues to plot in black
    """
        if sigmas is None and self.sigmas is not None:
            sigmas = self.sigmas

        if specialres is not None:
            if colorscheme is None:
                colorscheme = -np.ones([self.pdbfile.xyz.shape[0], 3])
            for res in specialres:
                resid = self.template.residues.index(res)
                for atom in self.pdbfile.residues[resid].atoms:
                    colorscheme[atom.idx, :] = [0.05, 0.05, 0.05]

        grid = GridTemplate(np.array([[0.0, 0.0, 0.0], self.box]),
                            resolution=0.5)
        centx = int(float(grid.size[0]) /
                    2.0)  #+(35.0-centroid[0])*grid.resolution
        centy = int(float(grid.size[1]) /
                    2.0)  #+(35.0-centroid[1])*grid.resolution
        #print centx*grid.resolution,centy*grid.resolution,centroid,-(35.0-centroid[1]),-(35.0-centroid[0])

        coords = np.array(self.protxyz, copy=True)
        if rotate2D is not None:
            m = self.protxyz.mean(axis=0)[:2]
            coords[:, :2] = rotate2D(coords[:, :2] - m) + m

        hpoints = np.zeros([len(self.helices), 2])
        for i, h in enumerate(self.helices):
            hlxxyz = coords[h[0]:h[1] + 1, :]
            aid = np.arange(h[0], h[1] + 1)
            if leaflet[0:3] == "upp":
                sel = hlxxyz[:, 2] >= self.box[2] / 2
            else:
                sel = hlxxyz[:, 2] <= self.box[2] / 2
            if sel.sum() > 0:
                idx = grid.indices(hlxxyz[sel, :])
                hpoints[i, 0] = (idx[0].mean() - centx) * grid.resolution
                hpoints[i, 1] = ((-idx[1]).mean() + centy) * grid.resolution

                hlxsig = sigmas[h[0]:h[1] + 1]
                hlxflag = self.protflag[h[0]:h[1] + 1]
                for ai, coord, sig, flag in zip(aid[sel], hlxxyz[sel, :],
                                                hlxsig[sel], hlxflag[sel]):
                    if flag == -1 and not sidechain: continue
                    fac = -1
                    if reverseY: fac = 1
                    thiscolor = colors.color(i)
                    if i == 0: thiscolor = colors.color(11)
                    thisalpha = 0.8
                    if colorscheme is not None:
                        if colorscheme[ai, 0] > -1:
                            thiscolor = colorscheme[ai, :]
                            thisalpha = 1.0
                    cir = plt.patches.Circle(
                        (fac * (-coord[1] + centy * grid.resolution),
                         coord[0] - centx * grid.resolution),
                        radius=sig,
                        fc=thiscolor,
                        ec=colors.darker(thiscolor),
                        alpha=thisalpha)
                    axis.add_patch(cir)

        # Add annotation for each helix
        for i, pnt in enumerate(hpoints):
            fac = -1
            if reverseY: fac = 1  #colors.color(i)
            axis.text(fac * pnt[1],
                      pnt[0],
                      "%d" % (i + 1),
                      bbox=dict(facecolor='white', alpha=0.9),
                      color='k',
                      fontsize=10)

        # Write out cholesterols
        if drawchol and leaflet[
                0:
                3] == self.cholleaf and self.cholxyz is not None and self.cholxyz.shape[
                    0] > 0:
            fac = -1
            if reverseY: fac = 1
            coords = np.array(self.cholxyz, copy=True)
            if rotate2D is not None:
                m = self.protxyz.mean(axis=0)[:2]
                coords[:, :2] = rotate2D(coords[:, :2] - m) + m
            axis.plot(fac * (-coords[::2, 1] + centy * grid.resolution),
                      coords[::2, 0] - centx * grid.resolution,
                      'xk',
                      markeredgewidth=1.0)
Пример #22
0
  def plot(self,axis, leaflet, centroid=None, reverseY=True,sigmas=None,sidechain=False,
            colorscheme=None, drawchol=True, specialres=None, rotate2D=None) :
    """
    Plot the structure on a 2D grid

    Parameters
    ----------
    axis : Axis object
      the matplotlib Axis object to draw on
    leaflet : string
      the leaflet to draw
    reverseY : boolean, optional
      if the y coordinate should be reversed
      used to distinguish between an look-up or look-down view
    sigmas : numpy array, optional
      sizes of atoms
    sidechain : boolean, optional
      if we should draw sidechains
    colorscheme : list, optional
      colors to use if not pre-defined
    drawchol : boolean, optional
      if to draw cholesterols if they exists
    specialres : list of int
      residues to plot in black
    """
    if sigmas is None and self.sigmas is not None :
      sigmas = self.sigmas

    if specialres is not None:
      if colorscheme is None:
        colorscheme = -np.ones([self.pdbfile.xyz.shape[0],3])
      for res in specialres :
        resid = self.template.residues.index(res)
        for atom in self.pdbfile.residues[resid].atoms:
          colorscheme[atom.idx,:] = [0.05,0.05,0.05]

    grid = GridTemplate(np.array([[0.0,0.0,0.0],self.box]),resolution=0.5)
    centx = int(float(grid.size[0])/2.0)#+(35.0-centroid[0])*grid.resolution
    centy = int(float(grid.size[1])/2.0)#+(35.0-centroid[1])*grid.resolution
    #print centx*grid.resolution,centy*grid.resolution,centroid,-(35.0-centroid[1]),-(35.0-centroid[0])

    coords = np.array(self.protxyz,copy=True)
    if rotate2D is not None :
      m = self.protxyz.mean(axis=0)[:2]
      coords[:,:2] = rotate2D(coords[:,:2]-m)+m

    hpoints = np.zeros([len(self.helices),2])
    for i,h in enumerate(self.helices) :
      hlxxyz = coords[h[0]:h[1]+1,:]
      aid = np.arange(h[0],h[1]+1)
      if leaflet[0:3] == "upp" :
        sel = hlxxyz[:,2] >= self.box[2]/2
      else :
        sel = hlxxyz[:,2] <= self.box[2]/2
      if sel.sum() > 0 :
        idx = grid.indices(hlxxyz[sel,:])
        hpoints[i,0] = (idx[0].mean()-centx)*grid.resolution
        hpoints[i,1] = ((-idx[1]).mean()+centy)*grid.resolution

        hlxsig = sigmas[h[0]:h[1]+1]
        hlxflag = self.protflag[h[0]:h[1]+1]
        for ai,coord,sig,flag in zip(aid[sel],hlxxyz[sel,:],hlxsig[sel],hlxflag[sel]) :
          if flag == -1 and not sidechain : continue
          fac = -1
          if reverseY : fac = 1
          thiscolor = colors.color(i)
          if i == 0 : thiscolor = colors.color(11)
          thisalpha = 0.8
          if colorscheme is not None :
            if colorscheme[ai,0] > -1  :
              thiscolor = colorscheme[ai,:]
              thisalpha = 1.0
          cir = plt.patches.Circle((fac*(-coord[1]+centy*grid.resolution),coord[0]-centx*grid.resolution),
                radius=sig,fc=thiscolor,ec=colors.darker(thiscolor),alpha=thisalpha)
          axis.add_patch(cir)

    # Add annotation for each helix
    for i,pnt in enumerate(hpoints) :
      fac = -1
      if reverseY : fac = 1 #colors.color(i)
      axis.text(fac*pnt[1],pnt[0],"%d"%(i+1),bbox=dict(facecolor='white',alpha=0.9),color='k',fontsize=10)

    # Write out cholesterols
    if drawchol and leaflet[0:3] == self.cholleaf and self.cholxyz is not None and self.cholxyz.shape[0] > 0 :
      fac = -1
      if reverseY : fac = 1
      coords = np.array(self.cholxyz,copy=True)
      if rotate2D is not None :
        m = self.protxyz.mean(axis=0)[:2]
        coords[:,:2] = rotate2D(coords[:,:2]-m)+m
      axis.plot(fac*(-coords[::2,1]+centy*grid.resolution),coords[::2,0]-centx*grid.resolution,'xk',markeredgewidth=1.0)
Пример #23
0
                           nargs="+",
                           help="setup postprocess jobs")
    args = argparser.parse_args()

    loglines = []
    with open(args.log, "r") as f:
        loglines = f.readlines()

    traj = _write_xyz(loglines, os.path.splitext(args.log)[0] + ".xyz")

    energies = _extract_energies(loglines, args.energy)
    scanvalues = _extract_coordinates(traj, args.coordinate)
    print "%8s%12s" % ("Scan value", "Energy")
    for s, e in zip(scanvalues, energies):
        print "%10.3f %12.3f" % (s, e)
    plt.plot(scanvalues, energies, "-*", color=colors.color(0))
    plt.xlabel("Scan value")
    plt.ylabel("Energy [kJ/mol]")
    plt.savefig(os.path.splitext(args.log)[0] + ".png", dpi=360)

    if args.structure is not None:
        from zmat import mol
        graph = mol.GraphStructure(verbosity=0)
        graph.initialize(args.structure)
        graph.traverse()
        atoms = [z.split()[0] for z in graph.zmat]
        idx = np.asarray([atoms.index(atom.name) for atom in graph.structure])
        for i, atoms in enumerate(traj, 1):
            filename = os.path.splitext(args.log)[0] + "_%d.pdb" % i
            graph.structure.coordinates = np.asarray([a[1:]
                                                      for a in atoms])[idx]
Пример #24
0
    argparser.add_argument('-c','--coordinate',type=int,nargs="+",help="the coordinate that was scanned")
    argparser.add_argument('-p','--postprocess',nargs="+",help="setup postprocess jobs")
    args = argparser.parse_args()

    loglines = []
    with open(args.log, "r") as f :
        loglines = f.readlines()

    traj = _write_xyz(loglines, os.path.splitext(args.log)[0]+".xyz")

    energies = _extract_energies(loglines, args.energy)
    scanvalues = _extract_coordinates(traj, args.coordinate)
    print "%8s%12s"%("Scan value","Energy")
    for s, e in zip(scanvalues, energies) :
        print "%10.3f %12.3f"%(s, e)
    plt.plot(scanvalues, energies, "-*",color=colors.color(0))
    plt.xlabel("Scan value")
    plt.ylabel("Energy [kJ/mol]")
    plt.savefig(os.path.splitext(args.log)[0]+".png", dpi=360)

    if args.structure is not None :
        from zmat import mol
        graph = mol.GraphStructure(verbosity=0)
        graph.initialize(args.structure)
        graph.traverse()
        atoms = [z.split()[0] for z in graph.zmat]
        idx = np.asarray([atoms.index(atom.name) for atom in graph.structure])
        for i, atoms in enumerate(traj, 1) :
            filename = os.path.splitext(args.log)[0]+"_%d.pdb"%i
            graph.structure.coordinates = np.asarray([a[1:] for a in atoms])[idx]
            graph.structure.save(filename, overwrite=True)
Пример #25
0
        if densities:
            if i < len(densities):
                part = pmfs[-1].partition(densities[i][:, :WDENS + 1])
            else:
                part = pmfs[-1].partition(densities[-1][:, :WDENS + 1])
            part_std = part[1] * const
            part = np.log10(part[0] * const)
            partstr = "| %.3f +- %.3f" % (part,
                                          np.abs(part_std /
                                                 (part * np.log(10))))

        print "%20s %8.3f +- %8.3f | %8.3f +- %8.3f | %8.3f +- %8.3f | %8.3f +- %8.3f | %8.3f at %8.3f %s" % (
            label, transfer_dg[0], transfer_dg[1], wat_barr[0], wat_barr[1],
            pen_barr[0], pen_barr[1], std_dg[0], std_dg[1], pmfs[-1].av.min(),
            pmfs[-1].z[pmfs[-1].av.argmin()], partstr)
        max_pmf = max(max_pmf, pmfs[-1].av.max())
        min_pmf = min(min_pmf, pmfs[-1].av.min())

    for i, (pmf, label) in enumerate(zip(pmfs, args.labels)):

        if args.centre == "phosphate" and densities:
            pmf.z = _calc_zorg(densities, i) - pmf.z
        kwargs = {}
        if i < len(args.stride): kwargs["stride"] = args.stride[i]
        pmf.plot(fig=f, label=label, color=colors.color(i), **kwargs)

    #_plot_areas(a, densities, args.centre, (min_pmf-5.0, max_pmf+5.0))

    f.savefig(args.out, format="png", dpi=300)
#finalize_plot(fig1,min_pmf,max_pmf,args.out,ncol=3)
Пример #26
0
        if args.shiftdens is not None:
            maxi = np.argmax(densities[args.shiftdens][:midi])
            xvals = xvals - xvals[:midi][maxi]
        if args.half:
            xvals = xvals[:midi]
        for di, density in enumerate(args.densities):
            idx = di if len(args.file) == 1 else fi
            y = densities[density]
            if args.half:
                y = y[:midi]
            if args.scale is not None:
                y = y / args.scale[idx]
            a.plot(xvals,
                   y,
                   "-",
                   color=colors.color(idx),
                   label=args.label[idx])

    if len(args.file) > 1 or len(args.densities) > 1:
        a.legend(loc='best',
                 fancybox=True,
                 framealpha=0.5,
                 fontsize=8,
                 labelspacing=0.20)

    for tick in a.xaxis.get_major_ticks():
        tick.label.set_fontsize(8)
    for tick in a.yaxis.get_major_ticks():
        tick.label.set_fontsize(8)
    if args.xlabel is None:
        if args.shiftdens is not None:
Пример #27
0
        if args.multicol is not None :
            args.ycol = args.multicol[i]
        if data.shape[1] == 1 : args.ycol = 0
        y = data[n:,args.ycol]*args.yfactor
        if data.shape[1] > 1 :
            x = data[n:,args.xcol]*args.xfactor
        else:
            x = np.arange(1,len(y)+1)*args.xfactor
        if args.stride is not None :
            x = x[::args.stride]
            y = y[::args.stride]
        if args.histogram is not None:
            y, x = np.histogram(y, bins=args.histogram)
            x = 0.5 * (x[:-1] + x[1:])
        stl = defaultstyle if args.nostyle else colors.style(i)
        ln = axis.plot(x,y, stl,color=colors.color(i),label=label)

        ylim[0] = min(ylim[0], y.min())
        ylim[1] = max(ylim[1], y.max())
        xlim[0] = min(xlim[0], y.min())
        xlim[1] = max(xlim[1], y.max())

        lines.append(ln[0])
        if args.errorbars:
            yerr = data[n:,args.ycol+1]*args.yfactor
            plt.fill_between(x,y-yerr,y+yerr, facecolor='grey',linewidth=0,alpha=0.4,interpolate=True)
        if args.equil :
            equili = series.find_equilibration(x,y)
            print "%s equilibrated at %.3f"%(label,x[equili])

    if len(args.file) == 2 and args.twin :
Пример #28
0
from sgenlib import colors
from sgenlib import parsing

if __name__ == '__main__' :

  parser = argparse.ArgumentParser(description="Plot bar plots")
  parser.add_argument('-f','--file',nargs="+",help="the bar plots")
  parser.add_argument('-l','--label',nargs="+",help="the labels")
  parser.add_argument('-o','--out',help="the output filename",default="bar.png")
  parser.add_argument('--xlabel',nargs="+",help="the x label")
  parser.add_argument('--ylabel',help="the y label")
  args = parser.parse_args()

  f = plt.figure()
  a = f.gca()
  for i,(filename,label) in enumerate(zip(args.file,args.label)) :
    data = parsing.parse2ndarray(filename)
    left = np.arange(data.shape[0]) + 0.38 + i*0.75/float(len(args.file))
    a.bar(left,data[:,0],yerr=data[:,1],width=1.0/float(len(args.file))*0.75,color=colors.color(i),label=label,error_kw=dict(ecolor='black'))

  if len(args.file) > 1 :
    a.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=4, mode="expand", borderaxespad=0.0,fontsize=11)
  for tick in a.xaxis.get_major_ticks() :
    tick.label.set_fontsize(8)
  for tick in a.yaxis.get_major_ticks() :
    tick.label.set_fontsize(8)
  if args.xlabel is not None : a.set_xlabel(args.xlabel,fontsize=8)
  if args.ylabel is not None : a.set_ylabel(args.ylabel,fontsize=8)
  f.savefig(args.out,format="png",dpi=300)