%prog unitigs best.edges

    Reads Celera Assembler's "best.edges" and extract all unitigs.
165106
def unitigs(args):
    
    p = OptionParser(unitigs.__doc__)
    p.add_option("--maxerr", default=2, type="int", help="Maximum error rate")
    opts, args = p.parse_args(args)

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

    bestedges, = args
    G = read_graph(bestedges, maxerr=opts.maxerr, directed=True)
    H = nx.Graph()
    intconv = lambda x: int(x.split("-")[0])
    for k, v in G.iteritems():
        if k == G.get(v, None):
            H.add_edge(intconv(k), intconv(v))

    nunitigs = nreads = 0
    for h in nx.connected_component_subgraphs(H, copy=False):
        st = [x for x in h if h.degree(x) == 1]
        if len(st) != 2:
            continue
        src, target = st
        path = list(nx.all_simple_paths(h, src, target))
        assert len(path) == 1
        path, = path
        print("|".join(str(x) for x in path))
        nunitigs += 1
        nreads += len(path)
    logging.debug("A total of {0} unitigs built from {1} reads."\
                    .format(nunitigs, nreads))
332258
function normalizeFgArgs(fgArgs) {
  var program, args, cb;
  var processArgsEnd = fgArgs.length;
  var lastFgArg = fgArgs[fgArgs.length - 1];
  if (typeof lastFgArg === "function") {
    cb = lastFgArg;
    processArgsEnd -= 1;
  } else {
    cb = function(done) { done(); };
  }

  if (Array.isArray(fgArgs[0])) {
    program = fgArgs[0][0];
    args = fgArgs[0].slice(1);
  } else {
    program = fgArgs[0];
    args = Array.isArray(fgArgs[1]) ? fgArgs[1] : fgArgs.slice(1, processArgsEnd);
  }

  return {program: program, args: args, cb: cb};
}
1021533
def select_edges(docgraph, conditions, data):
    """"""
    for (src_id, target_id, edge_attribs) in docgraph.edges(data=True):
        # if all conditions are fulfilled
        # we need to add edge_attribs to the namespace eval is working in
        if all((eval(cond, {'edge_attribs': edge_attribs})
                for cond in conditions)):
            if data:
                yield (src_id, target_id, edge_attribs)
            else:
                yield (src_id, target_id)
1162698
def allpaths(args):
    
    p = OptionParser(allpaths.__doc__)
    p.add_option("--ploidy", default="1", choices=("1", "2"),
                 help="Ploidy [default: %default]")
    opts, args = p.parse_args(args)

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

    folders = args
    for pf in folders:
        if not op.isdir(pf):
            continue
        assemble_dir(pf, target=["final.contigs.fasta", "final.assembly.fasta"],
                     ploidy=opts.ploidy)
770849
def _generate_edges(self, edge_prob):
        
        self.E, self.parent = [], {}
        for i in range(self.m):
            if random() < edge_prob and i > 0:
                p_i = choice(i)
                self.E.append((p_i, i))
                self.parent[i] = p_i
663532
def has_edge(self, p_from, p_to):
        
        return p_from in self._edges and p_to in self._edges[p_from]
470254
def edges(self):
        
        edge_str = ctypes.create_string_buffer(MAX_CHARS)

        cgaddag.gdg_edges(self.gdg, self.node, edge_str)

        return [char for char in edge_str.value.decode("ascii")]
1305795
def mappability(args):
    
    p = OptionParser(mappability.__doc__)
    p.add_option("--mer", default=50, type="int", help="User mer size")
    p.set_cpus()
    opts, args = p.parse_args(args)

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

    ref, = args
    K = opts.mer
    pf = ref.rsplit(".", 1)[0]
    mm = MakeManager()

    gem = pf + ".gem"
    cmd = "gem-indexer -i {} -o {}".format(ref, pf)
    mm.add(ref, gem, cmd)

    mer = pf + ".{}mer".format(K)
    mapb = mer + ".mappability"
    cmd = "gem-mappability -I {} -l {} -o {} -T {}".\
                format(gem, K, mer, opts.cpus)
    mm.add(gem, mapb, cmd)

    wig = mer + ".wig"
    cmd = "gem-2-wig -I {} -i {} -o {}".format(gem, mapb, mer)
    mm.add(mapb, wig, cmd)

    bw = mer + ".bw"
    cmd = "wigToBigWig {} {}.sizes {}".format(wig, mer, bw)
    mm.add(wig, bw, cmd)

    bg = mer + ".bedGraph"
    cmd = "bigWigToBedGraph {} {}".format(bw, bg)
    mm.add(bw, bg, cmd)

    merged = mer + ".filtered-1.merge.bed"
    cmd = "python -m jcvi.formats.bed filterbedgraph {} 1".format(bg)
    mm.add(bg, merged, cmd)

    mm.write()
1133964
def _determine_tool(files):
    """"""
    for file in files:
        linker_ext = file.split('.')[-1]
        if "sct" in linker_ext or "lin" in linker_ext:
            yield (str(file),"uvision")
        elif "ld" in linker_ext:
            yield (str(file),"make_gcc_arm")
        elif "icf" in linker_ext:
            yield (str(file),"iar_arm")
123126
def _to_edges(self, tokens):
        """"""
        # prepend self.order Nones
        chain = self._end_context + tokens + self._end_context

        has_space = False

        context = []

        for i in xrange(len(chain)):
            context.append(chain[i])

            if len(context) == self.order:
                if chain[i] == self.SPACE_TOKEN_ID:
                    context.pop()
                    has_space = True
                    continue

                yield tuple(context), has_space

                context.pop(0)
                has_space = False
1108225
def find_all_output_in_range(self, ifo, currSeg, useSplitLists=False):
        
        if not useSplitLists:
            # Slower, but simpler method
            outFiles = [i for i in self if ifo in i.ifo_list]
            outFiles = [i for i in outFiles \
                                      if i.segment_list.intersects_segment(currSeg)]
        else:
            # Faster, but more complicated
            # Basically only check if a subset of files intersects_segment by
            # using a presorted list. Sorting only happens once.
            if not self._check_split_list_validity():
                # FIXME: DO NOT hard code this.
                self._temporal_split_list(100)
            startIdx = int( (currSeg[0] - self._splitListsStart) / \
                                                          self._splitListsStep )
            # Add some small rounding here
            endIdx = (currSeg[1] - self._splitListsStart) / self._splitListsStep
            endIdx = int(endIdx - 0.000001)

            outFiles = []
            for idx in range(startIdx, endIdx + 1):
                if idx < 0 or idx >= self._splitListsNum:
                    continue
                outFilesTemp = [i for i in self._splitLists[idx] \
                                                            if ifo in i.ifo_list]
                outFiles.extend([i for i in outFilesTemp \
                                      if i.segment_list.intersects_segment(currSeg)])
                # Remove duplicates
                outFiles = list(set(outFiles))

        return self.__class__(outFiles)
884803
def fuse(args):
    
    from jcvi.algorithms.graph import BiGraph

    p = OptionParser(fuse.__doc__)
    opts, args = p.parse_args(args)

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

    bedfiles = [x for x in args if x.endswith(".bed")]
    anchorfiles = [x for x in args if x.endswith(".anchors")]

    # TODO: Use Markov clustering to sparsify the edges
    families = Grouper()
    for anchorfile in anchorfiles:
        af = AnchorFile(anchorfile)
        for a, b, block_id in af.iter_pairs():
            families.join(a, b)

    allowed = set(families.keys())
    logging.debug("Total families: {}, Gene members: {}"
                  .format(len(families), len(allowed)))

    # TODO: Use C++ implementation of BiGraph() when available
    # For now just serialize this to the disk
    G = BiGraph()
    for bedfile in bedfiles:
        bed = Bed(bedfile, include=allowed)
        #add_bed_to_graph(G, bed, families)
        print_edges(G, bed, families)
15812
def _init_edges(self, dst_srcs_list):
        """"""
        from goatools.gosubdag.go_paths import get_paths_goobjs, paths2edges
        edges_all = set()
        goid_all = set()
        go2obj = self.go2obj
        for dst, srcs in dst_srcs_list:
            go2obj_srcs = {}
            for goid in srcs:
                go2obj_srcs[goid] = go2obj[goid]
            go_paths, go_all = get_paths_goobjs(go2obj_srcs.values(), go_top=dst, go2obj=go2obj)
            edges_all |= paths2edges(go_paths)
            goid_all |= go_all
        self.edges = [(a.id, b.id) for a, b in edges_all]
        self.goid_all = goid_all
999798
def get_gnupg_components(sp=subprocess):
    """"""
    args = [util.which('gpgconf'), '--list-components']
    output = check_output(args=args, sp=sp)
    components = dict(re.findall('(.*):.*:(.*)', output.decode('utf-8')))
    log.debug('gpgconf --list-components: %s', components)
    return components
1320308
def p_edgesigs(self, p):
        ''
        p[0] = p[1] + (p[3],)
        p.set_lineno(0, p.lineno(1))
719051
def _rm_gos_edges_rel(self, rm_goids, edges_rel):
        """"""
        edges_ret = {}
        for rname, edges_cur in edges_rel.items():
            edges_new = self._rm_gos_edges(rm_goids, edges_cur)
            if edges_new:
                edges_ret[rname] = edges_new
        return edges_ret
341878
def prog(self, s=None):
        
        s = s or self.prog_msg
        self.printer(s, end='')