コード例 #1
0
 def save_plot(self, fig, axes, **kwargs):
     # Parameters #
     self.params = {}
     for key in self.default_params:
         if key in kwargs:                          self.params[key] = kwargs[key]
         elif hasattr(self, key):                   self.params[key] = getattr(self, key)
         elif self.default_params[key] is not None: self.params[key] = self.default_params[key]
     # Backwards compatibility #
     if kwargs.get('x_log', False): self.params['x_scale'] = 'symlog'
     if kwargs.get('y_log', False): self.params['y_scale'] = 'symlog'
     # Log #
     if 'x_scale' in self.params: axes.set_xscale(self.params['x_scale'])
     if 'y_scale' in self.params: axes.set_yscale(self.params['y_scale'])
     # Axis limits #
     if 'x_min' in self.params: axes.set_xlim(self.params['x_min'], axes.get_xlim()[1])
     if 'x_max' in self.params: axes.set_xlim(axes.get_xlim()[0], self.params['x_max'])
     if 'y_min' in self.params: axes.set_xlim(self.params['y_min'], axes.get_ylim()[1])
     if 'y_max' in self.params: axes.set_xlim(axes.get_ylim()[0], self.params['y_max'])
     # Title #
     title = self.params.get('title', False)
     if title: axes.set_title(title)
     # Axes labels  #
     if self.params.get('x_label'): axes.set_xlabel(self.params['x_label'])
     if self.params.get('y_label'): axes.set_ylabel(self.params['y_label'])
     # Adjust #
     fig.set_figwidth(self.params['width'])
     fig.set_figheight(self.params['height'])
     fig.subplots_adjust(hspace=0.0, bottom = self.params['bottom'], top   = self.params['top'],
                                     left   = self.params['left'],   right = self.params['right'])
     # Grid #
     axes.xaxis.grid(self.params['x_grid'])
     axes.yaxis.grid(self.params['y_grid'])
     # Data and source extra text #
     if hasattr(self, 'dev_mode') and self.dev_mode is True:
         fig.text(0.99, 0.98, time.asctime(), horizontalalignment='right')
         job_name = os.environ.get('SLURM_JOB_NAME', 'Unnamed')
         user_msg = 'user: %s, job: %s' % (getpass.getuser(), job_name)
         fig.text(0.01, 0.98, user_msg, horizontalalignment='left')
     # Nice digit grouping #
     if 'x' in self.params['sep']:
         separate = lambda x,pos: split_thousands(x)
         axes.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(separate))
     if 'y' in self.params['sep']:
         separate = lambda y,pos: split_thousands(y)
         axes.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(separate))
     # Add custom labels #
     if 'x_labels' in self.params: axes.set_xticklabels(self.params['x_labels'])
     if 'x_labels_rot' in self.params: pyplot.setp(axes.xaxis.get_majorticklabels(), rotation=self.params['x_labels_rot'])
     # Possibility to overwrite path #
     if 'path' in self.params:   path = FilePath(self.params['path'])
     elif hasattr(self, 'path'): path = FilePath(self.path)
     else:                       path = FilePath(self.short_name + '.pdf')
     # Save it as different formats #
     for ext in self.params['formats']: fig.savefig(path.replace_extension(ext))
コード例 #2
0
ファイル: graphs.py プロジェクト: DC23/plumbing
 def __init__(self, parent=None, base_dir=None, short_name=None):
     # Save parent #
     self.parent = parent
     # Base dir #
     if base_dir is None: self.base_dir = self.parent.p.graphs_dir
     else: self.base_dir = base_dir
     # Short name #
     if short_name: self.short_name = short_name
     if not hasattr(self, 'short_name'): self.short_name = 'graph'
     # Paths #
     self.path = FilePath(self.base_dir + self.short_name + '.pdf')
コード例 #3
0
ファイル: __init__.py プロジェクト: tarah28/seqenv
def download_from_url(source, destination, progress=False, uncompress=True):
    """Download a file from an URL and place it somewhere. Like wget.
    Uses requests and tqdm to display progress if you want.
    By default it will uncompress files."""
    # Modules #
    from tqdm import tqdm
    import requests
    from autopaths import FilePath
    # Check destination exists #
    destination = FilePath(destination)
    destination.directory.create_if_not_exists()
    # Over HTTP #
    response = requests.get(source, stream=True)
    total_size = int(response.headers.get('content-length'))
    block_size = total_size / 1024
    # Do it #
    with open(destination, "wb") as handle:
        if progress:
            for data in tqdm(response.iter_content(chunk_size=block_size),
                             total=1024):
                handle.write(data)
        else:
            for data in response.iter_content(chunk_size=block_size):
                handle.write(data)
    # Uncompress #
    if uncompress:
        with open(destination) as f:
            header = f.read(4)
        if header == "PK\x03\x04": unzip(destination, inplace=True)
        # Add other compression formats here
    # Return #
    return destination
コード例 #4
0
ファイル: tmpstuff.py プロジェクト: DC23/plumbing
 def __new__(cls, path=None, content=None, **kwargs):
     handle = open(path, 'w') if path else tempfile.NamedTemporaryFile(delete=False, **kwargs)
     if content: handle.write(content)
     handle.close()
     return FilePath.__new__(cls, handle.name)
コード例 #5
0
ファイル: tmpstuff.py プロジェクト: tarah28/seqenv
 def __new__(cls, path=None, content=None, **kwargs):
     handle = open(path, 'w') if path else tempfile.NamedTemporaryFile(delete=False, **kwargs)
     if content: handle.write(content)
     handle.close()
     return FilePath.__new__(cls, handle.name)
コード例 #6
0
ファイル: graphs.py プロジェクト: DC23/plumbing
class Graph(object):
    width  = 12.0
    height = 7.0
    bottom = 0.14
    top    = 0.93
    left   = 0.06
    right  = 0.98
    formats = ('pdf',)

    def __nonzero__(self): return self.path.__nonzero__()

    def __init__(self, parent=None, base_dir=None, short_name=None):
        # Save parent #
        self.parent = parent
        # Base dir #
        if base_dir is None: self.base_dir = self.parent.p.graphs_dir
        else: self.base_dir = base_dir
        # Short name #
        if short_name: self.short_name = short_name
        if not hasattr(self, 'short_name'): self.short_name = 'graph'
        # Paths #
        self.path = FilePath(self.base_dir + self.short_name + '.pdf')

    def __call__(self, *args, **kwatgs):
        """Plot the graph if it doesn't exist. Then return the path to it."""
        if not self: self.plot(*args, **kwatgs)
        return self.path

    def save_plot(self, fig, axes, width=None, height=None, bottom=None, top=None, left=None, right=None, sep=()):
        # Attributes or parameters #
        w = width  if width  != None else self.width
        h = height if height != None else self.height
        b = bottom if bottom != None else self.bottom
        t = top    if top    != None else self.top
        l = left   if left   != None else self.left
        r = right  if right  != None else self.right
        # Adjust #
        fig.set_figwidth(w)
        fig.set_figheight(h)
        fig.subplots_adjust(hspace=0.0, bottom=b, top=t, left=l, right=r)
        # Data and source #
        if hasattr(self, 'dev_mode'):
            fig.text(0.99, 0.98, time.asctime(), horizontalalignment='right')
            job_name = os.environ.get('SLURM_JOB_NAME', 'Unnamed')
            user_msg = 'user: %s, job: %s' % (getpass.getuser(), job_name)
            fig.text(0.01, 0.98, user_msg, horizontalalignment='left')
        # Nice digit grouping #
        if 'x' in sep:
            seperate = lambda x,pos: split_thousands(x)
            axes.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(seperate))
        if 'y' in sep:
            seperate = lambda y,pos: split_thousands(y)
            axes.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(seperate))
        # Save it as different formats #
        for ext in self.formats: fig.savefig(self.path.replace_extension(ext))

    def plot(self):
        """An example plot function. You have to subclass this method."""
        fig = pyplot.figure()
        axes = fig.add_subplot(111)
        axes.plot([0,1,10,1000], [0,1,2,3], 'ro')
        axes.set_title("Rarefaction curve of the diversity estimate")
        axes.set_xlabel("Sequences rarefied down to this many sequences")
        axes.set_ylabel("The diversity estimate")
        axes.yaxis.grid(True)
        axes.set_xscale('symlog')
        axes.set_xlim(0, axes.get_xlim()[1])
        self.save_plot(fig, axes, sep=('x',))
        pyplot.close(fig)

    def save_anim(self, fig, animate, init, bitrate=10000, fps=30):
        """Not functional -- TODO"""
        from matplotlib import animation
        anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20)
        FFMpegWriter = animation.writers['ffmpeg']
        writer = FFMpegWriter(bitrate= bitrate, fps=fps)
        # Save #
        self.avi_path = self.base_dir + self.short_name + '.avi'
        anim.save(self.avi_path, writer=writer, codec='x264')