Plots the resions corresponding to open reading frames
 Param
 +orfs+: +Hash+ containing the open reading frame
 +output+: location where the plot will be saved in jped file format
 +prediction+: Sequence objects
174027
def plot_orfs(orfs, translated_length)
      raise QueryError unless orfs.is_a? Hash

      data = []

      # Create hashes for the Background
      (-3..3).each do |frame|
        next if frame == 0
        data << { 'y' => frame, 'start' => 1, 'stop' => translated_length,
                  'color' => 'gray' }
      end

      # Create the hashes for the ORFs...
      orfs.each do |_key, h|
        data << { 'y' => h[:frame], 'start' => h[:orf_start],
                  'stop' => h[:orf_end], 'color' => 'red' }
      end

      Plot.new(data,
               :lines,
               'Open Reading Frames in all 6 Frames',
               'Open Reading Frame (Minimimum Length: 30 amino acids),red',
               'Offset in the Prediction',
               'Reading Frame',
               14)
    end
302290
def _layout(self):
        
        # Ensure the axes are created if not hist, then return.
        if not self.hist:
            self.ax
            return

        # Ensure matplotlib version compatibility
        if make_axes_locatable is None:
            raise YellowbrickValueError((
                "joint plot histograms requires matplotlib 2.0.2 or greater "
                "please upgrade matplotlib or set hist=False on the visualizer"
            ))

        # Create the new axes for the histograms
        divider = make_axes_locatable(self.ax)
        self._xhax = divider.append_axes("top", size=1, pad=0.1, sharex=self.ax)
        self._yhax = divider.append_axes("right", size=1, pad=0.1, sharey=self.ax)

        # Modify the display of the axes
        self._xhax.xaxis.tick_top()
        self._yhax.yaxis.tick_right()
        self._xhax.grid(False, axis='y')
        self._yhax.grid(False, axis='x')
1054900
def plot_diagrams(results, configs, compiler, out_dir):
    """"""
    compiler_fn = make_filename(compiler)
    total = psutil.virtual_memory().total  # pylint:disable=I0011,E1101
    memory = int(math.ceil(byte_to_gb(total)))

    images_dir = os.path.join(out_dir, 'images')

    for config in configs:
        out_prefix = '{0}_{1}'.format(config['name'], compiler_fn)

        plot_diagram(
            config,
            results,
            images_dir,
            os.path.join(images_dir, '{0}.png'.format(out_prefix))
        )

        with open(
            os.path.join(out_dir, '{0}.qbk'.format(out_prefix)),
            'wb'
        ) as out_f:
            qbk_content = """{0}
Measured on a {2} host with {3} GB memory. Compiler used: {4}.

[$images/metaparse/{1}.png [width 100%]]
""".format(config['desc'], out_prefix, platform.platform(), memory, compiler)
            out_f.write(qbk_content)
504630
def plot_memory(calc_id=-1):
    
    dstore = util.read(calc_id)
    plots = []
    for task_name in dstore['task_info']:
        mem = dstore['task_info/' + task_name]['mem_gb']
        plots.append((task_name, mem))
    plt = make_figure(plots)
    plt.show()
172114
def plots_from_files(imspaths, figsize=(10,5), rows=1, titles=None, maintitle=None):
    
    f = plt.figure(figsize=figsize)
    if maintitle is not None: plt.suptitle(maintitle, fontsize=16)
    for i in range(len(imspaths)):
        sp = f.add_subplot(rows, ceildiv(len(imspaths), rows), i+1)
        sp.axis('Off')
        if titles is not None: sp.set_title(titles[i], fontsize=16)
        img = plt.imread(imspaths[i])
        plt.imshow(img)
493403
def display(self):
        '''
        
        '''
        w, h = (0, 0)
        for line in self.shell('dumpsys', 'display').splitlines():
            m = _DISPLAY_RE.search(line, 0)
            if not m:
                continue
            w = int(m.group('width'))
            h = int(m.group('height'))
            o = int(m.group('orientation'))
            w, h = min(w, h), max(w, h)
            return self.Display(w, h, o)

        output = self.shell('LD_LIBRARY_PATH=/data/local/tmp', self.__minicap, '-i')
        try:
            data = json.loads(output)
            (w, h, o) = (data['width'], data['height'], data['rotation']/90)
            return self.Display(w, h, o)            
        except ValueError:
            pass
766337
def displayplot(data, plinds, plottype, scaling, fileroot, url_path='http://www.aoc.nrao.edu/~claw/plots'):
    

    plotdict = {'dmt': plotdmt, 'norm': plotnorm,
               'loc': plotloc, 'stat': plotstat,
               'all': plotall}
    sizedict = {'dmt': [900,500], 'norm': [700, 700], 'loc': [700,700],
                'stat': [700,700]}

    sortinds = sorted(set(plinds['cir'] + plinds['cro'] + plinds['edg']))
    sizesrc, plaw = scaling.split('_')
    data['sizes'] = calcsize(data[sizesrc], inds=sortinds, plaw=int(plaw))

    if plottype != 'all':
        wid, hei = sizedict[plottype]
        pl = plotdict[plottype](data, circleinds=plinds['cir'], crossinds=plinds['cro'],
                                edgeinds=plinds['edg'], url_path=url_path,
                                fileroot=fileroot, plot_width=wid, plot_height=hei)
    else:
        pl = plotall(data, circleinds=plinds['cir'], crossinds=plinds['cro'],
                                 edgeinds=plinds['edg'], url_path=url_path,
                                 fileroot=fileroot)
    hdl = show(pl)
470646
def read(self, filename):
        """"""
        QUIET = self.settings.get('RMD_READER_KNITR_QUIET', True)
        ENCODING = self.settings.get('RMD_READER_KNITR_ENCODING', 'UTF-8')
        CLEANUP = self.settings.get('RMD_READER_CLEANUP', True)
        RENAME_PLOT = self.settings.get('RMD_READER_RENAME_PLOT', 'chunklabel')
        if type(RENAME_PLOT) is bool:
            logger.error("RMD_READER_RENAME_PLOT takes a string value (either chunklabel or directory), please see the readme.")
            if RENAME_PLOT:
                RENAME_PLOT = 'chunklabel'
                logger.error("Defaulting to chunklabel")
            else:
                RENAME_PLOT = 'disabled'
                logger.error("Disabling plot renaming")
        logger.debug("RMD_READER_KNITR_QUIET = %s", QUIET)
        logger.debug("RMD_READER_KNITR_ENCODING = %s", ENCODING)
        logger.debug("RMD_READER_CLEANUP = %s", CLEANUP)
        logger.debug("RMD_READER_RENAME_PLOT = %s", RENAME_PLOT)
        # replace single backslashes with double backslashes
        filename = filename.replace('\\', '\\\\')
        # parse Rmd file - generate md file
        md_filename = filename.replace('.Rmd', '.aux').replace('.rmd', '.aux')
        if RENAME_PLOT == 'chunklabel' or RENAME_PLOT == 'directory':
            if RENAME_PLOT == 'chunklabel':
                chunk_label = os.path.splitext(os.path.basename(filename))[0]
                logger.debug('Chunk label: %s', chunk_label)
            elif RENAME_PLOT == 'directory':
                chunk_label = 'unnamed-chunk'
                PATH = self.settings.get('PATH','%s/content' % settings.DEFAULT_CONFIG.get('PATH'))
                src_name = os.path.splitext(os.path.relpath(filename, PATH))[0]
                idx = KNITR.opts_chunk.names.index('set')
                knitroptschunk = { 'fig.path': '%s-' % os.path.join(FIG_PATH, src_name) }
                KNITR.opts_chunk[idx](**{str(k): v for k,v in knitroptschunk.items()})
                logger.debug('Figures path: %s, chunk label: %s', knitroptschunk['fig.path'], chunk_label)
            R_OBJECTS.r('''
opts_knit$set(unnamed.chunk.label="{unnamed_chunk_label}")
render_markdown()
hook_plot <- knit_hooks$get('plot')
knit_hooks$set(plot=function(x, options) hook_plot(paste0("{{static}}/", x), options))
            '''.format(unnamed_chunk_label=chunk_label))
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            KNITR.knit(filename, md_filename, quiet=QUIET, encoding=ENCODING)
        # read md file - create a MarkdownReader
        md_reader = readers.MarkdownReader(self.settings)
        content, metadata = md_reader.read(md_filename)
        # remove md file
        if CLEANUP:
            os.remove(md_filename)
        return content, metadata
1140752
def get_orfs(_orf_length = 100, prediction = @prediction)
      '-' if prediction.type != 'nucleotide'

      seq = Bio::Sequence::NA.new(prediction.raw_sequence)

      result = {}
      key = 0
      (1..6).each do |f|
        s = seq.translate(f)
        f = -1 if f == 4
        f = -2 if f == 5
        f = -3 if f == 6
        s.scan(/(\w{30,})/) do |_orf|
          orf_start = $LAST_MATCH_INFO.offset(0)[0] + 1
          orf_end   = $LAST_MATCH_INFO.offset(0)[1] + 1
          coverage = (((orf_end - orf_start) / s.length.to_f) * 100).ceil
          # reduce the orf_end and the translated length by 2% to increase the
          #   width between ORFs on the plot
          chopping = s.length * 0.02
          orf_end = (orf_end.to_f - chopping).floor
          translated_length = (s.length - chopping).ceil
          key += 1
          result[key] = { frame: f, orf_start: orf_start, orf_end: orf_end,
                          coverage: coverage,
                          translated_length: translated_length }
        end
      end
      result
    end
1308434
def output_barplot(df, figformat, path, title=None, palette=None):
    """"""
    logging.info("Nanoplotter: Creating barplots for number of reads and total throughput.")
    read_count = Plot(path=path + "NanoComp_number_of_reads." + figformat,
                      title="Comparing number of reads")
    ax = sns.countplot(x="dataset",
                       data=df,
                       palette=palette)
    ax.set(ylabel='Number of reads',
           title=title or read_count.title)
    plt.xticks(rotation=30, ha='center')
    read_count.fig = ax.get_figure()
    read_count.save(format=figformat)
    plt.close("all")

    throughput_bases = Plot(path=path + "NanoComp_total_throughput." + figformat,
                            title="Comparing throughput in gigabases")
    if "aligned_lengths" in df:
        throughput = df.groupby('dataset')['aligned_lengths'].sum()
        ylabel = 'Total gigabase aligned'
    else:
        throughput = df.groupby('dataset')['lengths'].sum()
        ylabel = 'Total gigabase sequenced'
    ax = sns.barplot(x=list(throughput.index),
                     y=throughput / 1e9,
                     palette=palette,
                     order=df["dataset"].unique())
    ax.set(ylabel=ylabel,
           title=title or throughput_bases.title)
    plt.xticks(rotation=30, ha='center')
    throughput_bases.fig = ax.get_figure()
    throughput_bases.save(format=figformat)
    plt.close("all")
    return read_count, throughput_bases
712464
def _save_plot(self, *args, extension='pdf', **kwargs):
        
        import matplotlib.pyplot as plt

        tmp_path = make_temp_dir()
        filename = '{}.{}'.format(str(uuid.uuid4()), extension.strip('.'))
        filepath = posixpath.join(tmp_path, filename)

        plt.savefig(filepath, *args, **kwargs)
        return filepath
469759
def plot(self, file_type):
        

        samples = self.mod_data[file_type]
        plot_title = file_types[file_type]['title']
        plot_func = file_types[file_type]['plot_func']
        plot_params = file_types[file_type]['plot_params']
        return plot_func(samples,
                    file_type,
                    plot_title=plot_title,
                    plot_params=plot_params)
616569
def _process_phenotypicseries(self, limit):
        
        if self.test_mode:
            graph = self.testgraph
        else:
            graph = self.graph
        LOG.info("getting phenotypic series titles")
        model = Model(graph)
        line_counter = 0
        src_key = 'phenotypicSeries'
        col = self.files[src_key]['columns']
        raw = '/'.join((self.rawdir, self.files[src_key]['file']))
        with open(raw) as reader:
            line = reader.readline()  # title
            line = reader.readline()  # date downloaded
            line = reader.readline()  # copyright
            line = reader.readline()  # <blank>

            line = reader.readline().strip()  # column headers
            line_counter = 5
            row = line.split('\t')
            if row != col:  # assert
                LOG.error('Expected  %s to have columns: %s', raw, col)
                LOG.error('But Found %s to have columns: %s', raw, row)
                raise AssertionError('Incomming data headers have changed.')

            for line in reader:
                line_counter += 1
                row = line.strip().split('\t')
                if row and len(row) != len(col):
                    LOG.warning(
                        'Unexpected input on line: %i  got: %s', line_counter, row)
                    continue
                ps_label = row[col.index('Phenotypic Series Title')].strip()
                ps_num = row[col.index('Phenotypic Series number')].strip()
                omimps_curie = 'OMIMPS:' + ps_num
                model.addClassToGraph(omimps_curie, ps_label)

                if not self.test_mode and limit is not None and line_counter > limit:
                    break
488779
def plot_and_save(self,
                      data,
                      w=800,
                      h=420,
                      filename='chart',
                      overwrite=True):
        """"""
        self.save(data, filename, overwrite)
        return IFrame(filename + '.html', w, h)
85838
@Override
    public void displayFile(FileSystem fs, Path path, OutputStream outStream,
        int startLine, int endLine) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("displaying orc file:" + path.toUri().getPath());
        }
        StringBuilder ret = new StringBuilder();
        Reader orcreader = null;
        RecordReader reader = null;
        Object row = null;
        try {
            int lineNum = 1;

            orcreader = OrcFile.createReader(fs, path);
            reader = orcreader.rows(null);
            long endTime = System.currentTimeMillis() + STOP_TIME;
            while (reader.hasNext() && lineNum <= endLine
                && System.currentTimeMillis() <= endTime) {
                row = reader.next(row);
                if (lineNum >= startLine) {
                    ret.append(String.format("Record %d:\n", lineNum));
                    String jsonString =
                        SerDeUtilsWrapper.getJSON(row,
                            orcreader.getObjectInspector());
                    try {
                        JSONObject jsonobj = new JSONObject(jsonString);
                        ret.append(jsonobj.toString(JSON_INDENT));
                    } catch (JSONException e) {
                        logger.error("Failed to parse json as JSONObject", e);
                        // default to unformatted json string
                        ret.append(jsonString);
                    }
                    ret.append("\n\n");
                }
                lineNum++;
            }
            outStream.write(ret.toString().getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            outStream.write(("Error in display orc file: " + e
                .getLocalizedMessage()).getBytes("UTF-8"));
            throw e;
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
474132
def _previewFile(self):
        
        dataFrame = self._loadCSVDataFrame()
        dataFrameModel = DataFrameModel(dataFrame, filePath=self._filename)
        dataFrameModel.enableEditing(True)
        self._previewTableView.setModel(dataFrameModel)
        columnModel = dataFrameModel.columnDtypeModel()
        columnModel.changeFailed.connect(self.updateStatusBar)
        self._datatypeTableView.setModel(columnModel)
437500
def _plot_properties(self, key, element):
        
        init = 'plot' not in self.handles
        size_multiplier = self.renderer.size/100.
        options = self._traverse_options(element, 'plot', ['width', 'height'], defaults=False)

        logger = self.param if init else None
        aspect_props, dimension_props = compute_layout_properties(
            self.width, self.height, self.frame_width, self.frame_height,
            options['width'], options['height'], self.aspect, self.data_aspect,
            self.responsive, size_multiplier, logger=logger)

        if not init:
            if aspect_props['aspect_ratio'] is None:
                aspect_props['aspect_ratio'] = self.state.aspect_ratio

        if self.dynamic and aspect_props['match_aspect']:
            # Sync the plot size on dynamic plots to support accurate
            # scaling of dimension ranges
            stream = PlotSize(subscribers=[self._update_size])
            self.callbacks.append(PlotSizeCallback(self, [stream], None))

        plot_props = {
            'margin':        self.margin,
            'max_width':     self.max_width,
            'max_height':    self.max_height,
            'min_width':     self.min_width,
            'min_height':    self.min_height
        }
        plot_props.update(aspect_props)
        if not self.drawn:
            plot_props.update(dimension_props)

        if self.bgcolor:
            plot_props['background_fill_color'] = self.bgcolor
        if self.border is not None:
            for p in ['left', 'right', 'top', 'bottom']:
                plot_props['min_border_'+p] = self.border
        lod = dict(self.param.defaults().get('lod', {}), **self.lod)
        for lod_prop, v in lod.items():
            plot_props['lod_'+lod_prop] = v
        return plot_props