Make a tree with RAxML.
967236
def build_tree_raxml(self,
                   new_path    = None,
                   seq_type    = 'nucl' or 'prot',
                   num_threads = None,
                   free_cores  = 2,
                   keep_dir    = False):
        """"""
        # Check output #
        if new_path is None: new_path = self.prefix_path + '.tree'
        # What model to choose #
        if seq_type == 'nucl': model = "GTRGAMMA"
        if seq_type == 'prot': model = "PROTGAMMAJTTF"
        # Threads #
        if num_threads is None: num_threads = multiprocessing.cpu_count() - free_cores
        else:                   num_threads = int(num_threads) - free_cores
        num_threads = max(1, num_threads)
        # Run it #
        temp_dir = new_temp_dir()
        sh.raxml811('-m', model, "-T", num_threads, '-p', 1, '-s', self.path, '-n', 'tree', '-w', temp_dir, '-f', 'a', '-x', 1, '-N', 'autoMR')
        # Move into place #
        if keep_dir:
            shutil.rmtree(new_path)
            shutil.move(temp_dir, new_path)
        if not keep_dir:
            shutil.move(temp_dir + 'RAxML_bestTree.tree', new_path)
        # Return #
        return FilePath(new_path)
332403
def parse_to_tree(text):
    """"""
    xml_text = cabocha.as_xml(text)
    tree = Tree(xml_text)
    return tree
310309
def build_tree(self, directory):
        ''''''
        confile = os.path.join(directory, 'config.yml')
        conf = {}
        if os.path.exists(confile):
            conf = yaml.load(open(confile).read())

        class node(defaultdict):
            name = ''
            parent = None
            tmpl = None
            rect = None
            mask = None

            def __str__(self):
                obj = self
                names = []
                while obj.parent is not None:
                    names.append(obj.name)
                    obj = obj.parent
                return '-'.join(names[::-1])

        def tree():
            return node(tree)

        root = tree()
        for s in os.listdir(directory):
            if not s.endswith('.png') or s.endswith('_mask.png'): 
                continue
            obj = root
            for i in s[:-4].split('-'):
                obj[i].name = i
                obj[i].parent = obj
                obj = obj[i]
            obj.tmpl = cv2.imread(os.path.join(directory, s))
            obj.rect = conf.get(s[:-4], {}).get('rect')
            maskimg = conf.get(s[:-4], {}).get('mask')
            if maskimg is not None:
                maskimg = os.path.join(directory, maskimg)
                if os.path.exists(maskimg):
                    obj.mask = cv2.imread(maskimg)

        self.tree = root
        self.current_scene = []
        self.confile = confile
        self.conf = conf
53577
def SH_raxml(reftree, querytree, phy_file, shout="SH_out.txt"):
    
    assert op.isfile(reftree)
    shout = must_open(shout, "a")

    raxml_work = op.abspath(op.join(op.dirname(phy_file), "raxml_work"))
    mkdir(raxml_work)
    raxml_cl = RaxmlCommandline(cmd=RAXML_BIN("raxmlHPC"), \
    sequences=phy_file, algorithm="h", model="GTRGAMMA", \
    name="SH", starting_tree=reftree, bipartition_filename=querytree, \
    working_dir=raxml_work)

    logging.debug("Running SH test in RAxML: %s" % raxml_cl)
    o, stderr = raxml_cl()
    # hard coded
    try:
        pval = re.search('(Significantly.*:.*)', o).group(0)
    except:
        print("SH test failed.", file=sys.stderr)
    else:
        pval = pval.strip().replace("\t"," ").replace("%","\%")
        print("{0}\t{1}".format(op.basename(querytree), pval), file=shout)
        logging.debug("SH p-value appended to %s" % shout.name)

    shout.close()
    return shout.name
451134
void  build() {
           // If there were no rules, just return.  This situation can easily arise
           //   for the reverse rules.
           if (fRB.fTreeRoots[fRootIx]==null) {
               return;
           }

           //
           // Walk through the tree, replacing any references to $variables with a copy of the
           //   parse tree for the substition expression.
           //
           fRB.fTreeRoots[fRootIx] = fRB.fTreeRoots[fRootIx].flattenVariables();
           if (fRB.fDebugEnv!=null && fRB.fDebugEnv.indexOf("ftree")>=0) {
               System.out.println("Parse tree after flattening variable references.");
               fRB.fTreeRoots[fRootIx].printTree(true);
           }

           //
           // If the rules contained any references to {bof}
           //   add a {bof} <cat> <former root of tree> to the
           //   tree.  Means that all matches must start out with the
           //   {bof} fake character.
           //
           if (fRB.fSetBuilder.sawBOF()) {
               RBBINode bofTop    = new RBBINode(RBBINode.opCat);
               RBBINode bofLeaf   = new RBBINode(RBBINode.leafChar);
               bofTop.fLeftChild  = bofLeaf;
               bofTop.fRightChild = fRB.fTreeRoots[fRootIx];
               bofLeaf.fParent    = bofTop;
               bofLeaf.fVal       = 2;      // Reserved value for {bof}.
               fRB.fTreeRoots[fRootIx] = bofTop;
           }

           //
           // Add a unique right-end marker to the expression.
           //   Appears as a cat-node, left child being the original tree,
           //   right child being the end marker.
           //
           RBBINode cn = new RBBINode(RBBINode.opCat);
           cn.fLeftChild = fRB.fTreeRoots[fRootIx];
           fRB.fTreeRoots[fRootIx].fParent = cn;
           cn.fRightChild = new RBBINode(RBBINode.endMark);
           cn.fRightChild.fParent = cn;
           fRB.fTreeRoots[fRootIx] = cn;

           //
           //  Replace all references to UnicodeSets with the tree for the equivalent
           //      expression.
           //
           fRB.fTreeRoots[fRootIx].flattenSets();
           if (fRB.fDebugEnv!=null && fRB.fDebugEnv.indexOf("stree")>=0) {
               System.out.println("Parse tree after flattening Unicode Set references.");
               fRB.fTreeRoots[fRootIx].printTree(true);
           }


           //
           // calculate the functions nullable, firstpos, lastpos and followpos on
           // nodes in the parse tree.
           //    See the alogrithm description in Aho.
           //    Understanding how this works by looking at the code alone will be
           //       nearly impossible.
           //
           calcNullable(fRB.fTreeRoots[fRootIx]);
           calcFirstPos(fRB.fTreeRoots[fRootIx]);
           calcLastPos(fRB.fTreeRoots[fRootIx]);
           calcFollowPos(fRB.fTreeRoots[fRootIx]);
           if (fRB.fDebugEnv!=null && fRB.fDebugEnv.indexOf("pos")>=0) {
               System.out.print("\n");
               printPosSets(fRB.fTreeRoots[fRootIx]);
           }

           //
           //  For "chained" rules, modify the followPos sets
           //
           if (fRB.fChainRules) {
               calcChainedFollowPos(fRB.fTreeRoots[fRootIx]);
           }

           //
           //  BOF (start of input) test fixup.
           //
           if (fRB.fSetBuilder.sawBOF()) {
               bofFixup();
           }

           //
           // Build the DFA state transition tables.
           //
           buildStateTable();
           flagAcceptingStates();
           flagLookAheadStates();
           flagTaggedStates();

           //
           // Update the global table of rule status {tag} values
           // The rule builder has a global vector of status values that are common
           //    for all tables.  Merge the ones from this table into the global set.
           //
           mergeRuleStatusVals();

           if (fRB.fDebugEnv!=null && fRB.fDebugEnv.indexOf("states")>=0) {printStates();}
       }
499418
function buildTree(index, api) {
  const modules = {};

  const dependency = (module, parent) => {
    const filepath = api.resolve(module, parent);
    if (modules[filepath] != null) {
      return modules[filepath];
    }

    const src = api.getFileContents(module, parent, "utf8");
    const basic = api.parser(src);
    const [nestedImports, hasMemory] = parseImports(basic, api);

    const deps = {};

    Object.keys(nestedImports).forEach(mod => {
      if (mod.indexOf(".") === 0) {
        const dep = dependency(mod, filepath);
        deps[mod] = dep;
      }
    });

    const patched = inferImportTypes(basic, deps, api);
    const ast = api.semantics(patched);

    api.validate(ast, {
      lines: src.split("\n"),
      filename: module.split("/").pop(),
    });

    const result = {
      ast,
      deps,
      filepath,
      hasMemory,
    };
    modules[filepath] = result;

    return result;
  };

  const root = dependency(index, null);

  return {
    root,
    modules,
  };
}
250940
def fromxml(node):
        """"""
        if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
            node = parsexmlstring(node)

        args = []

        if node.tag == 'profile':
            for node in node:
                if node.tag == 'input':
                    for subnode in node:
                        if subnode.tag.lower() == 'inputtemplate':
                            args.append(InputTemplate.fromxml(subnode))
                elif node.tag == 'output':
                    for subnode in node:
                        if subnode.tag.lower() == 'outputtemplate':
                            args.append(OutputTemplate.fromxml(subnode))
                        elif subnode.tag.lower() == 'parametercondition':
                            args.append(ParameterCondition.fromxml(subnode))
        return Profile(*args)
1192881
def make_tree(file):
    """"""
    max_files_count = current_app.config.get('PREVIEWER_ZIP_MAX_FILES', 1000)
    tree = {'type': 'folder', 'id': -1, 'children': {}}

    try:
        with file.open() as fp:
            zf = zipfile.ZipFile(fp)
            # Detect filenames encoding.
            sample = ' '.join(zf.namelist()[:max_files_count])
            if not isinstance(sample, binary_type):
                sample = sample.encode('utf-16be')
            encoding = chardet.detect(sample).get('encoding', 'utf-8')
            for i, info in enumerate(zf.infolist()):
                if i > max_files_count:
                    raise BufferError('Too many files inside the ZIP file.')
                comps = info.filename.split(os.sep)
                node = tree
                for c in comps:
                    if not isinstance(c, text_type):
                        c = c.decode(encoding)
                    if c not in node['children']:
                        if c == '':
                            node['type'] = 'folder'
                            continue
                        node['children'][c] = {
                            'name': c,
                            'type': 'item',
                            'id': 'item{0}'.format(i),
                            'children': {}
                        }
                    node = node['children'][c]
                node['size'] = info.file_size
    except BufferError:
        return tree, True, None
    except (zipfile.LargeZipFile):
        return tree, False, 'Zipfile is too large to be previewed.'
    except Exception as e:
        current_app.logger.warning(str(e), exc_info=True)
        return tree, False, 'Zipfile is not previewable.'

    return tree, False, None
214363
def build_ml_raxml(alignment, outfile, work_dir=".", **kwargs):
    
    work_dir = op.join(work_dir, "work")
    mkdir(work_dir)
    phy_file = op.join(work_dir, "aln.phy")
    AlignIO.write(alignment, file(phy_file, "w"), "phylip-relaxed")

    raxml_work = op.abspath(op.join(op.dirname(phy_file), "raxml_work"))
    mkdir(raxml_work)
    raxml_cl = RaxmlCommandline(cmd=RAXML_BIN("raxmlHPC"), \
        sequences=phy_file, algorithm="a", model="GTRGAMMA", \
        parsimony_seed=12345, rapid_bootstrap_seed=12345, \
        num_replicates=100, name="aln", \
        working_dir=raxml_work, **kwargs)

    logging.debug("Building ML tree using RAxML: %s" % raxml_cl)
    stdout, stderr = raxml_cl()

    tree_file = "{0}/RAxML_bipartitions.aln".format(raxml_work)
    if not op.exists(tree_file):
        print("***RAxML failed.", file=sys.stderr)
        sh("rm -rf %s" % raxml_work, log=False)
        return None
    sh("cp {0} {1}".format(tree_file, outfile), log=False)

    logging.debug("ML tree printed to %s" % outfile)
    sh("rm -rf %s" % raxml_work)

    return outfile, phy_file
993841
def fromXml(cls, xdata, filepath=''):
        
        builder = cls()
        builder.loadXml(xdata, filepath=filepath)
        return builder
841845
def make_paragraphs(cls, root):
        """"""
        handler = cls()
        lxml.sax.saxify(root, handler)
        return handler.paragraphs
690572
def copy_tree(src, dst):
    """"""
    for root, subdirs, files in os.walk(src):
        current_dest = root.replace(src, dst)
        if not os.path.exists(current_dest):
            os.makedirs(current_dest)
        for f in files:
            shutil.copy(os.path.join(root, f), os.path.join(current_dest, f))
447846
def fromxml(node):
        """"""
        if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
            node = parsexmlstring(node)
        assert node.tag.lower() == 'action'

        kwargs = {}
        args = []
        if 'id' in node.attrib:
            kwargs['id'] = node.attrib['id']
        elif 'name' in node.attrib:
            kwargs['name'] = node.attrib['name']
        elif 'description' in node.attrib:
            kwargs['description'] = node.attrib['description']
        elif 'method' in node.attrib:
            kwargs['method'] = node.attrib['method']
        elif 'mimetype' in node.attrib:
            kwargs['mimetype'] = node.attrib['mimetype']
        elif 'allowanonymous' in node.attrib:
            if node.attrib['allowanonymous'] == "yes":
                kwargs['allowanonymous'] = True

        found = False
        for subnode in node:
            if subnode.tag.lower() == 'parametercondition':
                kwargs[node.tag] = ParameterCondition.fromxml(subnode)
            elif subnode.tag in vars(clam.common.parameters):
                args.append(vars(clam.common.parameters)[subnode.tag].fromxml(subnode))
        if not found:
            raise Exception("No condition found in ParameterCondition!")
        return Action(*args, **kwargs)
173263
def as_tree(context):
    """"""

    tree = _build_tree(context, 2, 1)
    if type(tree) == dict:
        tree = [tree] 
    
    return Response(content_type='application/json', body=json.dumps(tree))
1183866
def __make_tree(self):
        """"""

        # create div with "container" class
        div = E.DIV(E.CLASS("container"))

        # append header with title
        div.append(E.H2(self.__title))

        # next, iterate through subtrees appending each tree to div
        for subtree in self.__subtrees:
            div.append(subtree.get_html())

        # Connect div to body
        body = E.BODY(div)

        # attach body to html
        self.__htmltree = E.HTML(
            E.HEAD(
                E.TITLE(self.__title)
                ),
            body
            )
1116766
private void buildTree(MapModel mapModel) {
		treeGrid.setWidth100();
		treeGrid.setHeight100();
		treeGrid.setShowHeader(false);
		tree = new RefreshableTree();
		final TreeNode nodeRoot = new TreeNode("ROOT");
		tree.setRoot(nodeRoot); // invisible ROOT node (ROOT node is required)

		ClientLayerTreeInfo layerTreeInfo = mapModel.getMapInfo().getLayerTree();
		if (layerTreeInfo != null) {
			ClientLayerTreeNodeInfo treeNode = layerTreeInfo.getTreeNode();
			processNode(treeNode, nodeRoot, tree, mapModel, false);
		}

		treeGrid.setData(tree);
		treeGrid.addLeafClickHandler(this);
		treeGrid.addFolderClickHandler(this);

		// -- add event listeners to layers
		for (Layer<?> layer : mapModel.getLayers()) {
			registrations.add(layer.addLayerChangedHandler(new LayerChangedHandler() {
				public void onLabelChange(LayerLabeledEvent event) {
				}

				public void onVisibleChange(LayerShownEvent event) {
					for (TreeNode node : tree.getAllNodes()) {
						if (node.getName().equals(event.getLayer().getLabel())) {
							if (node instanceof LayerTreeTreeNode) {
								((LayerTreeTreeNode) node).updateIcon();
							}
						}
					}
				}
			}));
		}
	}
831756
def _build_catalog(self, url, xml_content):
        '''
        
        '''
        try:
            tree = etree.XML(xml_content)
        except BaseException:
            return

        # Get a list of URLs
        references = self._compile_references(url, tree)
        # Using multiple processes, make HTTP requests for each child catalog
        jobs = [self.pool.apply_async(request_xml, args=(ref,)) for ref in references]
        responses = [j.get() for j in jobs]

        # This is essentially the graph traversal step
        for i, response in enumerate(responses):
            for ds in self._build_catalog(references[i], response):
                yield ds

        # Yield the leaves
        for ds in self._yield_leaves(url, tree):
            yield ds