%prog rdotplotfile

    Dot plot to visualize relationship between two sequences, by plotting
    .rdotplot file (often generated by LASTZ)
771360
def rdotplot(args):
    
    p = OptionParser(rdotplot.__doc__)
    opts, args = p.parse_args(args)

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

    dotplot_template = """
    dots <- read.table('$rdotplotfile', header=T)
    png('$pngfile')
    plot(dots, type='l')
    dev.off()
    """

    rdotplotfile, = args
    assert rdotplotfile.endswith(".rdotplot")
    pngfile = rdotplotfile.replace(".rdotplot", ".png")

    rtemplate = RTemplate(dotplot_template, locals())
    rtemplate.run()
198239
def plot(result_pickle_file_path, show, plot_save_file):
    
    import pandas as pd
    from .plot import plot_result

    result_dict = pd.read_pickle(result_pickle_file_path)
    plot_result(result_dict, show, plot_save_file)
1227788
def generateVectors():
    

    ra_deg = 290.66666667
    dec_deg = +44.5
    #rollAngle_deg = 33.0
    rollAngle_deg = +123.
    boresight = r.vecFromRaDec(ra_deg, dec_deg)

    #Read in prime mission coords and convert to vectors
    inFile = "../etc/fov.txt"
    inFile = np.loadtxt(inFile)
    radecs = np.zeros( (len(inFile), 3))
    rotate = radecs*0
    for i, row in enumerate(inFile):
        radecs[i, :] = r.vecFromRaDec(inFile[i, 4], inFile[i,5])
        rotate[i, :] = r.rotateAroundVector(radecs[i], boresight,\
            -rollAngle_deg)




    #Slew to ra/dec of zero
    Ra = r.rightAscensionRotationMatrix(-ra_deg)
    Rd = r.declinationRotationMatrix(-dec_deg)
    R = np.dot(Rd, Ra)
    origin = rotate*0
    for i, row in enumerate(rotate):
        origin[i] = np.dot(R, rotate[i])

    mp.plot(origin[:,0], origin[:,1])

    #Print out the results
    #import pdb; pdb.set_trace()
    print("[")
    for i in range(len(inFile)):
        ch = channelFromModOut(inFile[i,0], inFile[i,1])
        print("[%3i., %3i., %3i., %13.7f, %13.7f, %13.7f], \\" %( \
            inFile[i, 0], inFile[i, 1], ch, \
            origin[i, 0], origin[i, 1], origin[i,2]))
    print("]")
213772
def Main():
  
  argument_parser = argparse.ArgumentParser(
      description='Validates dtFabric format definitions.')

  argument_parser.add_argument(
      'source', nargs='?', action='store', metavar='PATH', default=None,
      help=(
          'path of the file or directory containing the dtFabric format '
          'definitions.'))

  options = argument_parser.parse_args()

  if not options.source:
    print('Source value is missing.')
    print('')
    argument_parser.print_help()
    print('')
    return False

  if not os.path.exists(options.source):
    print('No such file: {0:s}'.format(options.source))
    print('')
    return False

  logging.basicConfig(
      level=logging.INFO, format='[%(levelname)s] %(message)s')


  source_is_directory = os.path.isdir(options.source)

  validator = DefinitionsValidator()

  if source_is_directory:
    source_description = os.path.join(options.source, '*.yaml')
  else:
    source_description = options.source

  print('Validating dtFabric definitions in: {0:s}'.format(source_description))
  if source_is_directory:
    result = validator.CheckDirectory(options.source)
  else:
    result = validator.CheckFile(options.source)

  if not result:
    print('FAILURE')
  else:
    print('SUCCESS')

  return result
1060775
def plotER(self,*args,**kwargs):
        
        if kwargs.pop('normed',False):
            kwargs['d2']= 'ERnorm'
        else:
            kwargs['d2']= 'ER'
        return self.plot(*args,**kwargs)
384258
def compare(args):
    
    p = OptionParser(compare.__doc__)
    opts, args, iopts = p.set_image_options(args, figsize="10x10")

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

    datafile, = args
    pf = datafile.rsplit(".", 1)[0]
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(ncols=2, nrows=2,
                                                 figsize=(iopts.w, iopts.h))
    plt.tight_layout(pad=3)

    bbox = {'facecolor': 'tomato', 'alpha': .2, 'ec': 'w'}
    pad = 2

    # Read benchmark data
    df = pd.read_csv("Evaluation.csv")
    truth = df["Truth"]
    axes = (ax1, ax2, ax3, ax4)
    progs = ("Manta", "Isaac", "GATK", "lobSTR")
    markers = ("bx-", "yo-", "md-", "c+-")

    for ax, prog, marker in zip(axes, progs, markers):
        ax.plot(truth, df[prog], marker)
        ax.plot(truth, truth, 'k--') # to show diagonal
        ax.axhline(infected_thr, color='tomato')
        ax.text(max(truth) - pad, infected_thr + pad, 'Risk threshold',
                bbox=bbox, ha="right")
        ax.axhline(ref_thr, color='tomato')
        ax.text(max(truth) - pad, ref_thr - pad, 'Reference repeat count',
                bbox=bbox, ha="right", va="top")
        ax.set_title(SIMULATED_HAPLOID)
        ax.set_xlabel(r'Num of CAG repeats inserted ($\mathit{h}$)')
        ax.set_ylabel('Num of CAG repeats called')
        ax.legend([prog, 'Truth'], loc='best')

    root = fig.add_axes([0, 0, 1, 1])
    pad = .03
    panel_labels(root, ((pad / 2, 1 - pad, "A"), (1 / 2., 1 - pad, "B"),
                        (pad / 2, 1 / 2.,  "C"), (1 / 2., 1 / 2. , "D")))
    normalize_axes(root)

    image_name = pf + "." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)
1267497
def main():
    
    fmt,plot='svg',0
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    elif '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        input=f.readlines()
    Data=[]
    for line in input:
        line.replace('\n','')
        if '\t' in line:   # read in the data from standard input
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        Data.append(float(rec[0]))
    
#
    if len(Data) >=10: 
        QQ={'unf1':1}
        pmagplotlib.plot_init(QQ['unf1'],5,5)
        pmagplotlib.plot_qq_unf(QQ['unf1'],Data,'QQ-Uniform') # make plot
    else:
        print('you need N> 10')
        sys.exit()
    pmagplotlib.draw_figs(QQ) 
    files={}
    for key in list(QQ.keys()):
        files[key]=key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(QQ,files)
    elif plot==1:
        files['qq']=file+'.'+fmt 
        pmagplotlib.save_plots(QQ,files)
    else:
        ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": pmagplotlib.save_plots(QQ,files)
1128962
def summary(args):
    
    from jcvi.utils.natsort import natsort_key

    p = OptionParser(summary.__doc__)
    p.add_option("--suffix", default="Mb",
            help="make the base pair counts human readable [default: %default]")
    p.add_option("--ids",
            help="write the ids that have >= 50% N's [default: %default]")
    p.set_outfile()

    opts, args = p.parse_args(args)

    if len(args) == 0:
        sys.exit(not p.print_help())

    idsfile = opts.ids
    header = "Seqid Real N's Total %_real".split()
    if idsfile:
        idsfile = open(idsfile, "w")
        nids = 0

    data = []
    for fastafile in args:
        for rec in SeqIO.parse(fastafile, "fasta"):
            seqlen = len(rec)
            nns = rec.seq.count('n') + rec.seq.count('N')
            reals = seqlen - nns
            pct = reals * 100. / seqlen
            pctreal = "{0:.1f}%".format(pct)
            if idsfile and pct < 50:
                nids += 1
                print(rec.id, file=idsfile)

            data.append((rec.id, reals, nns, seqlen, pctreal))

    data.sort(key=natsort_key)
    ids, reals, nns, seqlen, pctreal = zip(*data)
    reals = sum(reals)
    nns = sum(nns)
    seqlen = sum(seqlen)
    pctreal = "{0:.1f}%".format(reals * 100. / seqlen)
    data.append(("Total", reals, nns, seqlen, pctreal))

    write_csv(header, data, sep=" ", filename=opts.outfile, thousands=True)
    if idsfile:
        logging.debug("A total of {0} ids >= 50% N's written to {1}.".\
                      format(nids, idsfile.name))
        idsfile.close()

    return reals, nns, seqlen
614036
def makeFigFromFile(filename,*args,**kwargs):
    
    import matplotlib.pyplot as plt
    img = plt.imread(filename)
    fig,ax = plt.subplots(*args,**kwargs)
    ax.axis('off')
    ax.imshow(img)
    return fig
1262650
public static void main(String[] args) throws IOException {
		// File file = new File("/home/katja/samples/VirMC.exe");
		VisualizerBuilder builder = new VisualizerBuilder();
		builder.setColor(VISIBLE_ASCII, Color.red);
		builder.setColor(NON_ASCII, Color.green);
		builder.setColor(INVISIBLE_ASCII, Color.orange);
		builder.setColor(ENTROPY, Color.cyan);
		Visualizer vi = builder.build();
		// builder.setFileWidth(400).setHeight(400 - (400 % 8)).setPixelSize(8);
		File folder = new File("/home/katja/samples/torrentlocker_encrypted");
		System.out.println("starting to search");
		for (File file : folder.listFiles()) {
			System.out.println("processing file " + file.getAbsolutePath());
			final BufferedImage entropyImage = vi.createEntropyImage(file);
			final BufferedImage bytePlotImage = vi.createBytePlot(file);
			// final BufferedImage structureImage = vi.createImage(file);
			final BufferedImage legendImage = vi.createLegendImage(true, true,
					false);
			BufferedImage joinedImage = ImageUtil.appendImages(bytePlotImage,
					entropyImage);
			// joinedImage = ImageUtil.appendImages(joinedImage,
			// structureImage);
			joinedImage = ImageUtil.appendImages(joinedImage, legendImage);
			ImageIO.write(joinedImage, "png", new File(file.getAbsolutePath()
					+ ".png"));
		}
		// show(joinedImage);
	}
281820
def plot(self, key, part='re', scale='log', steps=50, legend=True, plotargs={}):
        
        try:
            import matplotlib.pyplot as plt
        except ImportError:
            raise ImportError("Please install matplotlib if you want to use the plot method")
        pdat = self.plotdata(key, part=part, scale=scale, steps=steps)
        plt.plot(*pdat, label=key, **plotargs)
        if scale == 'log':
            plt.xscale('log')
        if legend:
            plt.legend()
657997
def draw_lines():
    
    r = numpy.random.randn(200)
    fig = pyplot.figure()
    ax = fig.add_subplot(111)
    ax.plot(r)

    ax.grid(True)

    pyplot.savefig(lines_filename)
708021
def motif_tree_plot(outfile, tree, data, circle=True, vmin=None, vmax=None, dpi=300):
    
    try:
        from ete3 import Tree, faces, AttrFace, TreeStyle, NodeStyle
    except ImportError:
        print("Please install ete3 to use this functionality")
        sys.exit(1)

    # Define the tree
    t, ts = _get_motif_tree(tree, data, circle, vmin, vmax)
    
    # Save image
    t.render(outfile, tree_style=ts, w=100, dpi=dpi, units="mm");
    
    # Remove the bottom (empty) half of the figure
    if circle:
        img = Image.open(outfile)
        size = img.size[0]
        spacer = 50
        img.crop((0,0,size,size/2 + spacer)).save(outfile)
1139266
def graph_draw(dir: '/tmp', format: 'svg'.freeze)
      graph_save do |dotfile|
        base = File.basename(dotfile.path)
        dest = File.join(dir, "#{base}.#{format}")
        system("dot -T#{format} #{dotfile.path} -o #{dest}")
        dest
      end
    end
37672
def plotGenCost(generators):
    
    figure()
    plots = []
    for generator in generators:
        if generator.pcost_model == PW_LINEAR:
            x = [x for x, _ in generator.p_cost]
            y = [y for _, y in generator.p_cost]
        elif generator.pcost_model == POLYNOMIAL:
            x = scipy.arange(generator.p_min, generator.p_max, 5)
            y = scipy.polyval(scipy.array(generator.p_cost), x)
        else:
            raise
        plots.append(plot(x, y))
        xlabel("P (MW)")
        ylabel("Cost ($)")
    legend(plots, [g.name for g in generators])
    show()
436246
def render_output_pydot(self, dotdata, **kwargs):
        """"""
        if not HAS_PYDOT:
            raise CommandError("You need to install pydot python module")

        graph = pydot.graph_from_dot_data(dotdata)
        if not graph:
            raise CommandError("pydot returned an error")
        if isinstance(graph, (list, tuple)):
            if len(graph) > 1:
                sys.stderr.write("Found more then one graph, rendering only the first one.\n")
            graph = graph[0]

        output_file = kwargs['outputfile']
        formats = [
            'bmp', 'canon', 'cmap', 'cmapx', 'cmapx_np', 'dot', 'dia', 'emf',
            'em', 'fplus', 'eps', 'fig', 'gd', 'gd2', 'gif', 'gv', 'imap',
            'imap_np', 'ismap', 'jpe', 'jpeg', 'jpg', 'metafile', 'pdf',
            'pic', 'plain', 'plain-ext', 'png', 'pov', 'ps', 'ps2', 'svg',
            'svgz', 'tif', 'tiff', 'tk', 'vml', 'vmlz', 'vrml', 'wbmp', 'xdot',
        ]
        ext = output_file[output_file.rfind('.') + 1:]
        format_ = ext if ext in formats else 'raw'
        graph.write(output_file, format=format_)
1131440
def plot_prep_methods(df, prep, prepi, out_file_base, outtype, title=None,
                      size=None):
    
    samples = df[(df["bamprep"] == prep)]["sample"].unique()
    assert len(samples) >= 1, samples
    out_file = "%s-%s.%s" % (out_file_base, samples[0], outtype)
    df = df[df["category"].isin(cat_labels)]
    _seaborn(df, prep, prepi, out_file, title, size)
    return out_file