exports vesseltree to esofspy format

    :param vesseltree: filename or vesseltree dictionary structure
    :param outputfilename: output file name
    :param axisorder: order of axis can be specified with this option
    :return:
544303
def vt2esofspy(vesseltree, outputfilename="tracer.txt", axisorder=[0, 1, 2]):
    

    if (type(vesseltree) == str) and os.path.isfile(vesseltree):
        import io3d
        vt = io3d.misc.obj_from_file(vesseltree)
    else:
        vt = vesseltree
    print(vt['general'])
    print(vt.keys())
    vtgm = vt['graph']['microstructure']
    lines = []
    vs = vt['general']['voxel_size_mm']
    sh = vt['general']['shape_px']

    # switch axis
    ax = axisorder

    lines.append("#Tracer+\n")
    lines.append("#voxelsize mm %f %f %f\n" % (vs[ax[0]], vs[ax[1]], vs[ax[2]]))
    lines.append("#shape %i %i %i\n" % (sh[ax[0]], sh[ax[1]], sh[ax[2]]))
    lines.append(str(len(vtgm) * 2)+"\n")

    i = 1
    for id in vtgm:
        # edge['']
        try:
            nda = vtgm[id]['nodeA_ZYX']
            ndb = vtgm[id]['nodeB_ZYX']
            lines.append("%i\t%i\t%i\t%i\n" % (nda[ax[0]], nda[ax[1]], nda[ax[2]], i))
            lines.append("%i\t%i\t%i\t%i\n" % (ndb[ax[0]], ndb[ax[1]], ndb[ax[2]], i))
            i += 1
        except:
            pass


    lines.append("%i\t%i\t%i\t%i" % (0, 0, 0, 0))
    lines[3] = str(i - 1) + "\n"
    with open(outputfilename, 'wt') as f:
        f.writelines(lines)
319515
def build_output_table(cls, name='inputTableName', output_name='output'):
        
        obj = cls(name)
        obj.exporter = 'get_output_table_name'
        obj.output_name = output_name
        return obj
793815
def writeWarp(self, warpDict):
        
        warpElement = ET.Element("warp")
        axisNames = sorted(warpDict.keys())
        for name in axisNames:
            axisElement = ET.Element("axis")
            axisElement.attrib['name'] = name
            for a, b in warpDict[name]:
                warpPt = ET.Element("map")
                warpPt.attrib['input'] = str(a)
                warpPt.attrib['output'] = str(b)
                axisElement.append(warpPt)
            warpElement.append(axisElement)
        self.root.append(warpElement)
781713
def axis(self, name):
        
        for axis in self.axes():
            if axis.name() == name:
                return axis
        return None
468070
def _dash_f_e_to_dict(self, info_filename, tree_filename):
        
        with open(info_filename) as fl:
            models, likelihood, partition_params = self._dash_f_e_parser.parseFile(fl).asList()

        with open(tree_filename) as fl:
            tree = fl.read()

        d = {'likelihood': likelihood, 'ml_tree': tree, 'partitions': {}}

        for model, params in zip(models, partition_params):
            subdict = {}
            index, name, _, alpha, rates, freqs = params
            subdict['alpha'] = alpha
            subdict['name'] = name
            subdict['rates'] = rates
            subdict['frequencies'] = freqs
            subdict['model'] = model
            d['partitions'][index] = subdict

        return d
6324
def _get_output_nodes(self, output_path, error_path):
        
        from pymatgen.io.nwchem import NwOutput
        from aiida.orm.data.structure import StructureData
        from aiida.orm.data.array.trajectory import TrajectoryData

        ret_dict = []
        nwo = NwOutput(output_path)
        for out in nwo.data:
            molecules = out.pop('molecules', None)
            structures = out.pop('structures', None)
            if molecules:
                structlist = [StructureData(pymatgen_molecule=m)
                              for m in molecules]
                ret_dict.append(('trajectory',
                                 TrajectoryData(structurelist=structlist)))
            if structures:
                structlist = [StructureData(pymatgen_structure=s)
                              for s in structures]
                ret_dict.append(('trajectory',
                                 TrajectoryData(structurelist=structlist)))
            ret_dict.append(('output', ParameterData(dict=out)))

        # Since ParameterData rewrites it's properties (using _set_attr())
        # with keys from the supplied dictionary, ``source`` has to be
        # moved to another key. See issue #9 for details:
        # (https://bitbucket.org/epfl_theos/aiida_epfl/issues/9)
        nwo.job_info['program_source'] = nwo.job_info.pop('source', None)
        ret_dict.append(('job_info', ParameterData(dict=nwo.job_info)))
        
        return ret_dict
1257775
def axes(self):
        
        ret = utils.DefaultOrderedDict(lambda: self[1:0])
        for arr in self:
            if arr.psy.plotter is not None:
                ret[arr.psy.plotter.ax].append(arr)
        return OrderedDict(ret)
285710
def write_export_node_to_file(file_object, export_elements):
        
        for export_element in export_elements:
            # Order,Activity,Condition,Who,Subprocess,Terminated
            file_object.write(
                export_element["Order"] + "," + export_element["Activity"] + "," + export_element["Condition"] + "," +
                export_element["Who"] + "," + export_element["Subprocess"] + "," + export_element["Terminated"] + "\n")
630734
def tree_to_file(tree:'BubbleTree', outfile:str):
    """"""
    with open(outfile, 'w') as fd:
        fd.write(tree_to_gexf(tree))
1345779
def output_to_graphviz(file, namer=_graphviz_default_namer, block=None):
    
    print(block_to_graphviz_string(block, namer), file=file)
387925
def facetrecordtrees(table, key, start='start', stop='stop'):
    

    import intervaltree
    getstart = attrgetter(start)
    getstop = attrgetter(stop)
    getkey = attrgetter(key)
    trees = dict()
    for rec in records(table):
        k = getkey(rec)
        if k not in trees:
            trees[k] = intervaltree.IntervalTree()
        trees[k].addi(getstart(rec), getstop(rec), rec)
    return trees
1052428
def _get_output_nodes(self, output_path, error_path):
        
        from aiida.orm.data.array.trajectory import TrajectoryData
        import re

        state = None
        step = None
        scale = None
        with open(output_path) as f:
            lines = [x.strip('\n') for x in f.readlines()]

        result_dict = dict()
        trajectory = None
        for line in lines:
            if state is None and re.match('^\s*NWChem SCF Module\s*$',line):
                state = 'nwchem-scf-module'
                continue
            if state is None and re.match('^\s*NWChem Geometry Optimization\s*$',line):
                state = 'nwchem-geometry-optimisation'
                trajectory = TrajectoryData()
                continue
            if state == 'nwchem-scf-module' and re.match('^\s*Final RHF \s*results\s*$',line):
                state = 'final-rhf-results'
                continue
            if re.match('^\s*\-*\s*$',line):
                continue
            if state == 'final-rhf-results':
                result = re.match('^\s*([^=]+?)\s*=\s*([\-\d\.]+)$',line)
                if result:
                    key = re.sub('[^a-zA-Z0-9]+', '_', result.group(1).lower())
                    result_dict[key] = result.group(2)
                else:
                    state = 'nwchem-scf-module'
            if state == 'nwchem-geometry-optimisation' and re.match('^\s*Step\s+\d+\s*$',line):
                result = re.match('^\s*Step\s+(\d+)\s*$',line)
                step = result.group(1)
                continue
            if state == 'nwchem-geometry-optimisation' and \
                re.match('^\s*Output coordinates in a.u.',line):
                state = 'nwchem-geometry-optimisation-coordinates'
                result = re.match('scale by \s(*[\-\d\.]+)',line)
                scale = result.group(1)
                continue
        return [('parameters', ParameterData(dict=result_dict))]
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
253326
def export_frame_coordinates(topology, trajectory, nframe, output=None):
    
    if output is None:
        basename, ext = os.path.splitext(trajectory)
        output = '{}.frame{}.inpcrd'.format(basename, nframe)

    # ParmEd sometimes struggles with certain PRMTOP files
    if os.path.splitext(topology)[1] in ('.top', '.prmtop'):
        top = AmberPrmtopFile(topology)
        mdtop = mdtraj.Topology.from_openmm(top.topology)
        traj = mdtraj.load_frame(trajectory, int(nframe), top=mdtop)
        structure = parmed.openmm.load_topology(top.topology, system=top.createSystem())
        structure.box_vectors = top.topology.getPeriodicBoxVectors()

    else:  # standard protocol (the topology is loaded twice, though)
        traj = mdtraj.load_frame(trajectory, int(nframe), top=topology)
        structure = parmed.load_file(topology)

    structure.positions = traj.openmm_positions(0)

    if traj.unitcell_vectors is not None:  # if frame provides box vectors, use those
        structure.box_vectors = traj.openmm_boxes(0)

    structure.save(output, overwrite=True)
736417
def _prepare_axes(node, sort_key):
    
    links = node.links
    o_links = node._overlapping_links
    overlap = {ax2 for ax in links for ax2 in o_links.get(ax, [])}
    axes = []
    for axis in sorted(links.keys(), key=sort_key):
        if axis in overlap: continue
        tgt = links[axis]
        if axis in o_links:
            s, e = axis[0], axis[-1]
            axis = '%s%s%s' % (
                s, '&'.join(a[1:-1] for a in [axis] + o_links[axis]), e
            )
        axes.append((axis, tgt))
    return axes
1321093
def show_tree(nickname, server, org_vm, reference_direction='snia'):
    
    scoping_result_role = "Dependent" if reference_direction == 'snia' \
        else "Antecedent"
    profiles = server.profiles

    reg_profiles = {}
    for profile in profiles:
        reg_profiles[profile.path.to_wbem_uri(format="canonical")] = profile

    # defines element to subelement
    tree_dict = defaultdict(list)

    for profile in profiles:
        paths = server.conn.AssociatorNames(
            profile.path,
            AssocClass='CIM_ElementConformsToProfile',
            ResultClass="CIM_RegisteredProfile",
            ResultRole="ManagedElement")
        if paths:
            print('%s: associators ELEMENTCONFORMSTO %s' %
                  (nickname, profile.path.to_wbem_uri(format="canonical")))
            for path in paths:
                print("  %s" % path)
        profile.path.host = None
        profile_path_str = profile.path.to_wbem_uri(format="canonical")
        for path in paths:
            tree_dict[profile_path_str].append(
                path.to_wbem_uri(format="canonical"))

        # Go down one level on the profile side, to the scoping profile
        referenced_profile_paths = server.conn.AssociatorNames(
            ObjectName=profile.path,
            AssocClass="CIM_ReferencedProfile",
            ResultRole=scoping_result_role)
        if referenced_profile_paths:
            print('%s AssocNames CIM_ReferencedProfile %s' %
                  (nickname, profile.path.to_wbem_uri(format="canonical")))

            for path in referenced_profile_paths:
                print("  %s" % path.to_wbem_uri(format="canonical"))

            for path in referenced_profile_paths:
                path.host = None
            tree_dict[profile_path_str].append(
                path.to_wbem_uri(format="canonical"))

    for key, values in tree_dict.items():
        print('%s\n  %s' % (key, "\n  ".join(values)))

    name_dict = {}
    for key, values in tree_dict.items():
        prof = reg_profiles[key]
        pn = profile_name(org_vm, prof)
        pvalues = []
        for value in values:
            profx = reg_profiles[value]
            pvalues.append(profile_name(org_vm, profx))
        name_dict[pn] = pvalues
    for key, values in name_dict.items():
        print('%s\n  %s' % (key, "\n  ".join(values)))
663851
def _tree_filename(self):
        
        if self.Parameters['--out']:
            aln_filename = self._absolute(self.Parameters['--out'].Value)
        else:
            raise ValueError, "No tree output file specified."
        return aln_filename