Draw ANIb/ANIm/TETRA results

    - filestems - filestems for output files
    - gformat - the format for output graphics
511660
def draw(filestems, gformat):
    
    # Draw heatmaps
    for filestem in filestems:
        fullstem = os.path.join(args.outdirname, filestem)
        outfilename = fullstem + ".%s" % gformat
        infilename = fullstem + ".tab"
        df = pd.read_csv(infilename, index_col=0, sep="\t")
        logger.info("Writing heatmap to %s", outfilename)
        params = pyani_graphics.Params(
            params_mpl(df)[filestem],
            pyani_tools.get_labels(args.labels),
            pyani_tools.get_labels(args.classes),
        )
        if args.gmethod == "mpl":
            pyani_graphics.heatmap_mpl(
                df, outfilename=outfilename, title=filestem, params=params
            )
        elif args.gmethod == "seaborn":
            pyani_graphics.heatmap_seaborn(
                df, outfilename=outfilename, title=filestem, params=params
            )
965714
def draw(self):
        
        # Create display grid
        cr_display = np.zeros((len(self.classes_), len(self._displayed_scores)))


        # For each class row, append columns for precision, recall, f1, and support
        for idx, cls in enumerate(self.classes_):
            for jdx, metric in enumerate(self._displayed_scores):
                cr_display[idx, jdx] = self.scores_[metric][cls]

        # Set up the dimensions of the pcolormesh
        # NOTE: pcolormesh accepts grids that are (N+1,M+1)
        X, Y = np.arange(len(self.classes_)+1), np.arange(len(self._displayed_scores)+1)
        self.ax.set_ylim(bottom=0, top=cr_display.shape[0])
        self.ax.set_xlim(left=0, right=cr_display.shape[1])

        # Set data labels in the grid, enumerating over class, metric pairs
        # NOTE: X and Y are one element longer than the classification report
        # so skip the last element to label the grid correctly.
        for x in X[:-1]:
            for y in Y[:-1]:

                # Extract the value and the text label
                value = cr_display[x, y]
                svalue = "{:0.3f}".format(value)

                # change the svalue for support (when y == 3) because we want
                # to label it as the actual support value, not the percentage
                if y == 3:
                    if self.support != PERCENT:
                        svalue = self.support_score_[x]

                # Determine the grid and text colors
                base_color = self.cmap(value)
                text_color = find_text_color(base_color)

                # Add the label to the middle of the grid
                cx, cy = x+0.5, y+0.5
                self.ax.text(
                    cy, cx, svalue, va='center', ha='center', color=text_color
                )


        # Draw the heatmap with colors bounded by the min and max of the grid
        # NOTE: I do not understand why this is Y, X instead of X, Y it works
        # in this order but raises an exception with the other order.
        g = self.ax.pcolormesh(
            Y, X, cr_display, vmin=0, vmax=1, cmap=self.cmap, edgecolor='w',
        )

        # Add the color bar
        plt.colorbar(g, ax=self.ax)

        # Return the axes being drawn on
        return self.ax
204892
def format_geometry_in
      output = ""
      if self.lattice_vectors
        output << self.lattice_vectors.collect{|v| "lattice_vector #{v[0]} #{v[1]} #{v[2]}"}.join("\n")
        output << "\n"
      end
      output << self.atoms.collect{|a| a.format_geometry_in}.join("\n")

      output
    end
767429
private static int writeFormatTiles(TileDao tileDao, File directory,
			String imageFormat, Integer width, Integer height,
			TileFormatType tileType, boolean rawImage) throws IOException {

		int tileCount = 0;

		// Get the projection of the tile matrix set
		SpatialReferenceSystem srs = tileDao.getTileMatrixSet().getSrs();
		Projection projection = srs.getProjection();

		// Get the transformation to web mercator
		Projection webMercator = ProjectionFactory
				.getProjection(ProjectionConstants.EPSG_WEB_MERCATOR);
		ProjectionTransform projectionToWebMercator = projection
				.getTransformation(webMercator);

		// Get the bounding box of actual tiles
		BoundingBox zoomBoundingBox = tileDao.getBoundingBox();
		if (projection.isUnit(Units.DEGREES)) {
			zoomBoundingBox = TileBoundingBoxUtils
					.boundDegreesBoundingBoxWithWebMercatorLimits(zoomBoundingBox);
		}
		BoundingBox zoomWebMercatorBoundingBox = zoomBoundingBox
				.transform(projectionToWebMercator);

		GeoPackageTileRetriever retriever = null;
		if (rawImage) {
			retriever = new GeoPackageTileRetriever(tileDao);
		} else {
			retriever = new GeoPackageTileRetriever(tileDao, width, height,
					imageFormat);
		}

		double maxLength = tileDao.getMaxLength();
		double minLength = tileDao.getMinLength();

		double upperMax = getLength(
				new BoundingBox(zoomBoundingBox.getMinLongitude(),
						zoomBoundingBox.getMaxLatitude() - maxLength,
						zoomBoundingBox.getMinLongitude() + maxLength,
						zoomBoundingBox.getMaxLatitude()),
				projectionToWebMercator);
		double upperMin = getLength(
				new BoundingBox(zoomBoundingBox.getMinLongitude(),
						zoomBoundingBox.getMaxLatitude() - minLength,
						zoomBoundingBox.getMinLongitude() + minLength,
						zoomBoundingBox.getMaxLatitude()),
				projectionToWebMercator);

		double lowerMax = getLength(
				new BoundingBox(zoomBoundingBox.getMinLongitude(),
						zoomBoundingBox.getMinLatitude(),
						zoomBoundingBox.getMinLongitude() + maxLength,
						zoomBoundingBox.getMinLatitude() + maxLength),
				projectionToWebMercator);
		double lowerMin = getLength(
				new BoundingBox(zoomBoundingBox.getMinLongitude(),
						zoomBoundingBox.getMinLatitude(),
						zoomBoundingBox.getMinLongitude() + minLength,
						zoomBoundingBox.getMinLatitude() + minLength),
				projectionToWebMercator);

		double maxWebMercatorLength = Math.max(upperMax, lowerMax);
		double minWebMercatorLength = Math.min(upperMin, lowerMin);

		double minZoom = TileBoundingBoxUtils
				.zoomLevelOfTileSize(maxWebMercatorLength);
		double maxZoom = TileBoundingBoxUtils
				.zoomLevelOfTileSize(minWebMercatorLength);

		int minZoomCeiling = (int) Math.ceil(minZoom);
		int maxZoomFloor = (int) Math.floor(maxZoom);

		LOGGER.log(Level.INFO, tileType + " Zoom Range: " + minZoomCeiling
				+ " - " + maxZoomFloor);

		for (int zoomLevel = minZoomCeiling; zoomLevel <= maxZoomFloor; zoomLevel++) {

			File zDirectory = new File(directory, String.valueOf(zoomLevel));
			TileGrid tileGrid = TileBoundingBoxUtils.getTileGrid(
					zoomWebMercatorBoundingBox, zoomLevel);

			int zoomCount = 0;

			LOGGER.log(
					Level.INFO,
					"Zoom Level: " + zoomLevel + ", Min X: "
							+ tileGrid.getMinX() + ", Max X: "
							+ tileGrid.getMaxX() + ", Min Y: "
							+ tileGrid.getMinY() + ", Max Y: "
							+ tileGrid.getMaxY() + ", Max Tiles: "
							+ tileGrid.count());

			for (long x = tileGrid.getMinX(); x <= tileGrid.getMaxX(); x++) {

				// Build the z/x directory
				File xDirectory = new File(zDirectory, String.valueOf(x));

				for (long y = tileGrid.getMinY(); y <= tileGrid.getMaxY(); y++) {

					GeoPackageTile geoPackageTile = retriever.getTile((int) x,
							(int) y, zoomLevel);

					if (geoPackageTile != null) {

						// Get the y file name for the specified format
						long yFileName = y;
						if (tileType == TileFormatType.TMS) {
							yFileName = TileBoundingBoxUtils
									.getYAsOppositeTileFormat(zoomLevel,
											(int) y);
						}

						File imageFile = new File(xDirectory,
								String.valueOf(yFileName) + "." + imageFormat);

						// Make any needed directories for the image
						xDirectory.mkdirs();

						if (geoPackageTile.getImage() != null) {
							// Write the image to the file
							ImageIO.write(geoPackageTile.getImage(),
									imageFormat, imageFile);
						} else {
							// Write the raw image bytes to the file
							FileOutputStream fos = new FileOutputStream(
									imageFile);
							fos.write(geoPackageTile.getData());
							fos.close();
						}

						zoomCount++;

						if (zoomCount % ZOOM_PROGRESS_FREQUENCY == 0) {
							LOGGER.log(Level.INFO, "Zoom " + zoomLevel
									+ " Tile Progress... " + zoomCount);
						}
					}

				}
			}

			LOGGER.log(Level.INFO, "Zoom " + zoomLevel + " Tiles: " + zoomCount);

			tileCount += zoomCount;
		}

		return tileCount;
	}
140408
def display_output(arguments):
    ''''''
    global _ASCII
    if arguments['--alt-chars']:
        _ASCII=_ASCII_2
    try:
        im = Image.open(arguments['FILE'])
    except:
        raise IOError('Unable to open the file.')
    im = im.convert("RGBA")
    aspect_ratio    = float(im.size[0])/im.size[1]
    scaled_height   = _WIDTH / aspect_ratio
    scaled_width    = _HEIGHT * aspect_ratio*2

    if scaled_width > _WIDTH:
        width = int(_WIDTH)
        height = int(scaled_height/2)

    elif scaled_height > _HEIGHT:
        width = int(scaled_width)
        height = int(_HEIGHT)

    if arguments['--width']:
        width = int(arguments['--width'])
        height = int(width / aspect_ratio / 2)

    elif arguments['--height']:
        height = int(arguments['--height'])
        width = int(height * aspect_ratio * 2)

    if arguments['--width'] and arguments['--height']:
        height = int(arguments['--height'])
        width = int(arguments['--width'])

    im = im.resize((width,height),resample=Image.ANTIALIAS)

    enhancer = ImageEnhance.Contrast(im)
    im = enhancer.enhance(float(arguments['--contrast']))
    img = im.getdata()
    im = im.convert('L') #Grayscale

    if not arguments['--invert']:
        _ASCII = _ASCII[::-1]

    bg=None;
    if arguments['--bg']=='BLACK':
        bg=rgb(0,0,0)
        fg=rgb(5,5,5)
    elif arguments['--bg']=='WHITE':
        bg=rgb(5,5,5)
        fg=rgb(0,0,0)

    row_len=0
    if arguments['--bold']:
        bold=True
    else:
        bold=False
    for count,i in enumerate(im.getdata()):
        ascii_char = _ASCII[int(((i/255.0))*(len((_ASCII))-1))]
        try:
            if not arguments['--colors']:
                raise Exception
            color = rgb(int((img[count][0]/255.0)*5),int((img[count][1]/255.0)*5),int((img[count][2]/255.0)*5))
            print_color(ascii_char, end='', fg=color, bg=bg, bold=bold)
        except:
            if bg and bold:
                print_color(ascii_char, end='', fg=fg, bg=bg, bold=bold)
            elif bold:
                print_color(ascii_char, end='', bold=bold)
            elif bg:
                print_color(ascii_char, end='', fg=fg, bg=bg)
            else:
                print(ascii_char, end='')
        row_len+=1
        if row_len==width:
            row_len=0
            print('')
696760
def print_graphic(self):
        
        aLhang, aRhang, bLhang, bRhang = self.get_hangs()

        achar = ">"
        bchar = "<" if self.orientation == '-' else ">"
        if self.qreverse:
            achar = "<"
            bchar = {">" : "<", "<" : ">"}[bchar]

        print(aLhang, aRhang, bLhang, bRhang, file=sys.stderr)
        width = 50  # Canvas
        hitlen = self.hitlen
        lmax = max(aLhang, bLhang)
        rmax = max(aRhang, bRhang)
        bpwidth = lmax + hitlen + rmax
        ratio = width * 1. / bpwidth

        _ = lambda x: int(round(x * ratio, 0))
        a1, a2 = _(aLhang), _(aRhang)
        b1, b2 = _(bLhang), _(bRhang)
        hit = max(_(hitlen), 1)

        msg = " " * max(b1 - a1, 0)
        msg += achar * (a1 + hit + a2)
        msg += " " * (width - len(msg) + 2)
        msg += "{0} ({1})".format(self.aid, self.asize)
        print(msg, file=sys.stderr)

        msg = " " * max(a1, b1)
        msg += "|" * hit
        print(msg, file=sys.stderr)

        msg = " " * max(a1 - b1, 0)
        msg += bchar * (b1 + hit + b2)
        msg += " " * (width - len(msg) + 2)
        msg += "{0} ({1})".format(self.bid, self.bsize)
        print(msg, file=sys.stderr)
        print(self, file=sys.stderr)
686185
private static void displayResults(BufferedImage orig,
									   Planar<GrayF32> distortedImg,
									   ImageDistort allInside, ImageDistort fullView ) {
		// render the results
		Planar<GrayF32> undistortedImg = new Planar<>(GrayF32.class,
				distortedImg.getWidth(),distortedImg.getHeight(),distortedImg.getNumBands());

		allInside.apply(distortedImg, undistortedImg);
		BufferedImage out1 = ConvertBufferedImage.convertTo(undistortedImg, null,true);

		fullView.apply(distortedImg,undistortedImg);
		BufferedImage out2 = ConvertBufferedImage.convertTo(undistortedImg, null,true);

		// display in a single window where the user can easily switch between images
		ListDisplayPanel panel = new ListDisplayPanel();
		panel.addItem(new ImagePanel(orig), "Original");
		panel.addItem(new ImagePanel(out1), "Undistorted All Inside");
		panel.addItem(new ImagePanel(out2), "Undistorted Full View");

		ShowImages.showWindow(panel, "Removing Lens Distortion", true);
	}
3718
def gff(args):
    
    align_choices = ("left", "center", "right")
    p = OptionParser(gff.__doc__)
    p.add_option("--align", default="left", choices=align_choices,
                 help="Horizontal alignment [default: %default]")
    p.add_option("--noUTR", default=False, action="store_true",
                 help="Do not plot UTRs [default: %default]")
    opts, args = p.parse_args(args)

    if len(args) < 1:
        sys.exit(not p.print_help())

    fig = plt.figure(1, (8, 5))
    root = fig.add_axes([0, 0, 1, 1])

    gffiles = args
    ngenes = len(gffiles)

    canvas = .6
    setups, ratio = get_setups(gffiles, canvas=canvas, noUTR=opts.noUTR)
    align = opts.align
    xs = .2 if align == "left" else .8
    yinterval = canvas / ngenes
    ys = .8
    tip = .01
    for genename, mrnabed, cdsbeds in setups:
        ExonGlyph(root, xs, ys, mrnabed, cdsbeds, ratio=ratio, align=align)
        if align == "left":
            root.text(xs - tip, ys, genename, ha="right", va="center")
        elif align == "right":
            root.text(xs + tip, ys, genename, ha="left", va="center")
        ys -= yinterval

    root.set_xlim(0, 1)
    root.set_ylim(0, 1)
    root.set_axis_off()

    figname = "exons.pdf"
    savefig(figname, dpi=300)
881680
def draw_arith(ax, p0, size=1, alpha=0, arith=None, format=None,
               fontsize=10, **kwds):
    """
    if format is None: format = 'k-'
    a = size/2.0
    x0 = [0, 2.5*a, 0, 0]
    y0 = [a, 0, -a, a]

    cur_list = [(x0, y0)]
    cur_list = rotate_and_traslate(cur_list, alpha, p0)

    for curi in cur_list: ax.plot(curi[0], curi[1], format, **kwds)

    if arith is not None:
        pyplot.text(p0[0]+0.75*a, p0[1], arith, horizontalalignment='center',
                    verticalalignment='center', fontsize=fontsize)
632064
def draw_network(self, anim):
        

        g = nx.Graph()
        ntemp = []
        nodes_pos = {}
        demands = {}
        demands_pos = {}
        for no, node in self._nodes.items():
            g.add_node(node)
            ntemp.append(node)
            coord = self._problem._coord[no]
            nodes_pos[node] = tuple(coord)
            demands[node] = 'd=' + str(node.demand())
            demands_pos[node] = tuple([a+b for a, b in zip(coord, [2.5]*len(coord))])

        depot = self._nodes[self._problem._depot._name]
        for r in self.routes():
            n1 = r._nodes[0:len(r._nodes)-1]
            n2 = r._nodes[1:len(r._nodes)]
            e = list(zip(n1, n2))
            e.append((depot, r._nodes[0]))
            e.append((r._nodes[-1], depot))
            g.add_edges_from(e)

        plt.figure()
        ax = plt.gca()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

        if anim is not None:
            nx.draw_networkx(g, nodes_pos, with_labels=False, node_size=50)
            plt.savefig(anim.file_path +
                        anim.file_prefix +
                        (4 - len(str(anim.counter))) * '0' +
                        str(anim.counter) + '.png',
                        dpi=150,
                        bbox_inches='tight')
            anim.counter += 1
            plt.close()
        else:
            nx.draw_networkx(g, nodes_pos)
            nx.draw_networkx_labels(g, demands_pos, labels=demands)
            plt.show()
1308367
def Draw(self, *args, **kwargs):
        
        self.reset()
        output = None
        while self._rollover():
            if output is None:
                # Make our own copy of the drawn histogram
                output = self._tree.Draw(*args, **kwargs)
                if output is not None:
                    output = output.Clone()
                    # Make it memory resident (histograms)
                    if hasattr(output, 'SetDirectory'):
                        output.SetDirectory(0)
            else:
                newoutput = self._tree.Draw(*args, **kwargs)
                if newoutput is not None:
                    if isinstance(output, _GraphBase):
                        output.Append(newoutput)
                    else:  # histogram
                        output += newoutput
        return output
1180809
void drawEmptyBoard(Graphics g) {
        int x=x_offset, y=y_offset;
        Color old_col=g.getColor();

        g.setFont(def_font2);
        old_col=g.getColor();
        g.setColor(checksum_col);
        g.drawString(("Checksum: " + checksum), x_offset + field_size, y_offset - 20);
        g.setFont(def_font);
        g.setColor(old_col);

        for(int i=0; i < num_fields; i++) {
            for(int j=0; j < num_fields; j++) {  // draws 1 row
                g.drawRect(x, y, field_size, field_size);
                x+=field_size;
            }
            g.drawString((String.valueOf((num_fields - i - 1))), x + 20, y + field_size / 2);
            y+=field_size;
            x=x_offset;
        }

        for(int i=0; i < num_fields; i++) {
            g.drawString((String.valueOf(i)), x_offset + i * field_size + field_size / 2, y + 30);
        }
    }
1245191
def draw_figure(self,data_for_color=None, data_for_size=None, data_for_clouds=None, rot_bonds=None, color_for_clouds="Blues", color_type_color="viridis"):
        
        self.molecule = Molecule(self.topol_data)

        self.draw = Draw(self.topol_data,self.molecule,self.hbonds,self.pistacking,self.salt_bridges,self.lig_descr)
        self.draw.draw_molecule(data_for_color, data_for_size, data_for_clouds, rot_bonds, color_for_clouds, color_type_color)

        self.figure = Figure(self.molecule,self.topol_data,self.draw)
        self.figure.add_bigger_box()
        self.figure.manage_the_plots()
        self.figure.draw_white_circles()
        self.figure.put_everything_together()
        self.figure.write_final_draw_file(self.output_name)
125503
def render_graph(result, cfg, **kwargs):
    
    # Mapping from MIME types to formats accepted by RDFlib
    rdflib_formats = {'text/rdf+n3': 'n3',
                      'text/turtle': 'turtle',
                      'application/x-turtle': 'turtle',
                      'text/turtle': 'turtle',
                      'application/rdf+xml': 'xml',
                      'text/rdf': 'xml',
                      'application/rdf+xml': 'xml'}


    try:
        got = kwargs.get('format', 'text/rdf+n3')
        fmt = rdflib_formats[got]
    except KeyError:
        raise KrnlException('Unsupported format for graph processing: {!s}', got)

    g = ConjunctiveGraph()
    g.load(StringInputSource(result), format=fmt)

    display = cfg.dis[0] if is_collection(cfg.dis) else cfg.dis
    if display in ('png', 'svg'):
        try:
            literal = len(cfg.dis) > 1 and cfg.dis[1].startswith('withlit')
            opt = {'lang': cfg.lan, 'literal': literal, 'graphviz': []}
            data, metadata = draw_graph(g, fmt=display, options=opt)
            return {'data': data,
                    'metadata': metadata}
        except Exception as e:
            raise KrnlException('Exception while drawing graph: {!r}', e)
    elif display == 'table':
        it = rdf_iterator(g, set(cfg.lan), add_vtype=cfg.typ)
        n, data = html_table(it, limit=cfg.lmt, withtype=cfg.typ)
        data += div('Shown: {}, Total rows: {}', n if cfg.lmt else 'all',
                    len(g), css="tinfo")
        data = {'text/html': div(data)}
    elif len(g) == 0:
        data = {'text/html': div(div('empty graph', css='krn-warn'))}
    else:
        data = {'text/plain': g.serialize(format='nt').decode('utf-8')}

    return {'data': data,
            'metadata': {}}
1238520
private void renderHorizontal(Graphic g, int ty, double viewY)
    {
        final int inTileWidth = (int) Math.ceil(viewer.getWidth() / (double) map.getTileWidth());
        final int sx = (int) Math.floor((viewer.getX() + viewer.getViewX()) / map.getTileWidth());
        final double viewX = viewer.getX();

        for (int h = 0; h <= inTileWidth; h++)
        {
            final int tx = h + sx;
            if (!(tx < 0 || tx >= map.getInTileWidth()))
            {
                renderTile(g, tx, ty, viewX, viewY);
            }
        }
    }
939004
def display(self, ret, indent, prefix, out):
        '''
        
        '''
        if isinstance(ret, six.string_types):
            lines = ret.split('\n')
            for line in lines:
                out += '{0}{1}{2}{3}{4}\n'.format(
                        self.colors['RED'],
                        ' ' * indent,
                        prefix,
                        line,
                        self.colors['ENDC'])
        elif isinstance(ret, dict):
            for key in sorted(ret):
                val = ret[key]
                out += '{0}{1}{2}{3}{4}:\n'.format(
                        self.colors['CYAN'],
                        ' ' * indent,
                        prefix,
                        key,
                        self.colors['ENDC'])
                out = self.display(val, indent + 4, '', out)
        return out
627935
private void paintArrowDown(Graphics2D g, JComponent c, int width, int height) {
        int xOffset = width / 2 - 3;
        int yOffset = height / 2 - 5;

        g.translate(xOffset, yOffset);

        Shape s = shapeGenerator.createArrowLeft(1, 1, 4.2, 6);

        g.setPaint(getCommonArrowPaint(s, type));
        g.fill(s);

        g.translate(-xOffset, -yOffset);
    }