コード例 #1
0
    def writePhylipToOpenFile(self, flob, digitsAfterDecimal):

        gm = ["DistanceMatrix.writePhylipToOpenFile()"]
        assert self.dim, "Distance Matrix.writePhylipToOpenFile() no dim"
        f = flob

        f.write('%i\n' % self.dim)

        # Make the format strings.
        if digitsAfterDecimal > 8:
            totWid = digitsAfterDecimal + 5
        else:
            totWid = 11
        #colNameFormat = '%' + '-%is' % totWid
        if digitsAfterDecimal == 0:
            numberFormat = ' %' + '%ii   ' % (totWid - 4)
        elif digitsAfterDecimal > 0:
            numberFormat = '%' + '%i.%if' % (totWid, digitsAfterDecimal)
        else:
            gm.append("digitsAfterDecimal may not be below zero.")
            raise Glitch, gm

        longestNameLength = 0
        for i in self.names:
            if len(i) > longestNameLength:
                longestNameLength = len(i)
        nameFormat = '%' + '%is ' % longestNameLength

        for i in range(self.dim):
            if self.names:
                f.write('  ')
                f.write(nameFormat %
                        func.nexusFixNameIfQuotesAreNeeded(self.names[i]))
            for j in range(self.dim):
                #f.write('%10.6f' % self.matrix[i][j])
                f.write(numberFormat % self.matrix[i][j])
            f.write('\n')

        f.write('\n')
コード例 #2
0
    def writePhylipToOpenFile(self, flob, digitsAfterDecimal):

        gm = ["DistanceMatrix.writePhylipToOpenFile()"]
        assert self.dim, "Distance Matrix.writePhylipToOpenFile() no dim"
        f = flob

        f.write('%i\n' % self.dim)

        # Make the format strings.
        if digitsAfterDecimal > 8:
            totWid = digitsAfterDecimal + 5
        else:
            totWid = 11
        #colNameFormat = '%' + '-%is' % totWid
        if digitsAfterDecimal == 0:
            numberFormat = ' %' + '%ii   ' % (totWid - 4)
        elif digitsAfterDecimal > 0:
            numberFormat = '%' + '%i.%if' % (totWid, digitsAfterDecimal)
        else:
            gm.append("digitsAfterDecimal may not be below zero.")
            raise P4Error(gm)

        longestNameLength = 0
        for i in self.names:
            if len(i) > longestNameLength:
                longestNameLength = len(i)
        nameFormat = '%' + '%is ' % longestNameLength

        for i in range(self.dim):
            if self.names:
                f.write('  ')
                f.write(nameFormat %
                        func.nexusFixNameIfQuotesAreNeeded(self.names[i]))
            for j in range(self.dim):
                #f.write('%10.6f' % self.matrix[i][j])
                f.write(numberFormat % self.matrix[i][j])
            f.write('\n')

        f.write('\n')
コード例 #3
0
ファイル: Trees.py プロジェクト: Linhua-Sun/p4-phylogenetics
    def writeNexus(self, fName=None, append=0, withTranslation=0, writeTaxaBlock=1, likeMcmc=0):
        """Write the trees out in NEXUS format, in a trees block.

        If *fName* is None, the default, it is written to `sys.stdout`.

        #NEXUS is written unless we are *append*-ing.
        """

        gm = ['Trees.writeNexus()']

        if withTranslation:
            if not self.taxNames:
                gm.append("No taxNames.  Set taxNames if you want withTranslation.")
                raise Glitch, gm

            translationHash = {}
            i = 1
            for tName in self.taxNames:
                translationHash[tName] = i
                i += 1
        else:
            translationHash = None

        if fName == None or fName == sys.stdout:
            f = sys.stdout
            if not append:
                f.write('#NEXUS\n\n')
        else:
            if append:
                import os
                if os.path.isfile(fName):
                    try:
                        f = open(fName, 'a')
                    except IOError:
                        gm.append("Can't open %s for appending." % fName)
                        raise Glitch, gm
                else:
                    if 0:
                        print gm[0]
                        print "    'append' is requested,"
                        print "    but '%s' is not a regular file (doesn't exist?)." \
                              % fName
                        print "    Writing to a new file instead."
                    try:
                        f = open(fName, 'w')
                        f.write('#NEXUS\n\n')
                    except IOError:
                        gm.append("Can't open %s for writing." % fName)
                        raise Glitch, gm

            else:
                try:
                    f = open(fName, 'w')
                    f.write('#NEXUS\n\n')
                except IOError:
                    gm.append("Can't open %s for writing." % fName)
                    raise Glitch, gm

        if writeTaxaBlock:
            if self.taxNames:
                f.write('begin taxa;\n')
                f.write('  dimensions ntax=%s;\n' % self.nTax)
                f.write('  taxlabels')
                for tN in self.taxNames:
                    f.write(' %s' % func.nexusFixNameIfQuotesAreNeeded(tN))
                f.write(';\nend;\n\n')
            else:
                gm.append("writeTaxaBlock is set, but there is no taxNames.  How did *that* happen?!?")
                raise Glitch, gm




        f.write('begin trees;\n')

        # write the "translate" command
        if withTranslation:
            f.write('    translate\n')
            for i in range(self.nTax - 1):
                f.write('        %3i %s,\n' % (i + 1, func.nexusFixNameIfQuotesAreNeeded(self.taxNames[i])))
            f.write('        %3i %s\n' % (self.nTax, func.nexusFixNameIfQuotesAreNeeded(self.taxNames[-1])))
            f.write('    ;\n')

        # write the models comment
        if self.trees:
            first = self.trees[0]
            if likeMcmc:
                if not withTranslation:
                    gm.append("withTranslation is turned off, but likeMcmc is turned on.")
                    gm.append("This will cause grief in TreePartitions, so is prohibited.")
                    gm.append("Both on or both off, please.")
                    raise Glitch, gm
                f.write('    [&&p4 models p%i' % first.model.nParts)
                for pNum in range(first.model.nParts):
                    f.write(' c%i.%i' % (pNum, first.model.parts[pNum].nComps))
                    f.write(' r%i.%i' % (pNum, first.model.parts[pNum].nRMatrices))
                    f.write(' g%i.%i' % (pNum, first.model.parts[pNum].nGdasrvs))
                f.write(']\n')


        # write each tree
        for t in self.trees:
            if not self.writeBranchLengths:
                t.stripBrLens()
            
            if t.logLike:
                f.write('    [logLike for tree %s is %f]\n' % (t.name, t.logLike))

            f.write('    tree %s = [&U] ' % func.nexusFixNameIfQuotesAreNeeded(t.name))
            if t.recipWeight:
                #if t.recipWeight == 1:
                #    f.write('[&W 1] ')
                #else:
                f.write('[&W 1/%i] ' % t.recipWeight)
            if hasattr(t, 'weight'):
                f.write('[&W %f] ' % t.weight)

            t.writeNewick(f, withTranslation=withTranslation, translationHash=translationHash, doMcmcCommandComments=likeMcmc)

        f.write('end;\n\n')
        if f != sys.stdout:
            f.close()
コード例 #4
0
    def writeNexus(self, fName=None, append=0, withTranslation=0, writeTaxaBlock=1, likeMcmc=0):
        """Write the trees out in NEXUS format, in a trees block.

        If *fName* is None, the default, it is written to `sys.stdout`.

        #NEXUS is written unless we are *append*-ing.
        """

        gm = ['Trees.writeNexus()']

        if withTranslation:
            if not self.taxNames:
                gm.append("No taxNames.  Set taxNames if you want withTranslation.")
                raise Glitch, gm

            translationHash = {}
            i = 1
            for tName in self.taxNames:
                translationHash[tName] = i
                i += 1
        else:
            translationHash = None

        if fName == None or fName == sys.stdout:
            f = sys.stdout
            if not append:
                f.write('#NEXUS\n\n')
        else:
            if append:
                import os
                if os.path.isfile(fName):
                    try:
                        f = open(fName, 'a')
                    except IOError:
                        gm.append("Can't open %s for appending." % fName)
                        raise Glitch, gm
                else:
                    if 0:
                        print gm[0]
                        print "    'append' is requested,"
                        print "    but '%s' is not a regular file (doesn't exist?)." \
                              % fName
                        print "    Writing to a new file instead."
                    try:
                        f = open(fName, 'w')
                        f.write('#NEXUS\n\n')
                    except IOError:
                        gm.append("Can't open %s for writing." % fName)
                        raise Glitch, gm

            else:
                try:
                    f = open(fName, 'w')
                    f.write('#NEXUS\n\n')
                except IOError:
                    gm.append("Can't open %s for writing." % fName)
                    raise Glitch, gm

        if writeTaxaBlock:
            if self.taxNames:
                f.write('begin taxa;\n')
                f.write('  dimensions ntax=%s;\n' % self.nTax)
                f.write('  taxlabels')
                for tN in self.taxNames:
                    f.write(' %s' % func.nexusFixNameIfQuotesAreNeeded(tN))
                f.write(';\nend;\n\n')
            else:
                gm.append("writeTaxaBlock is set, but there is no taxNames.  How did *that* happen?!?")
                raise Glitch, gm




        f.write('begin trees;\n')

        # write the "translate" command
        if withTranslation:
            f.write('    translate\n')
            for i in range(self.nTax - 1):
                f.write('        %3i %s,\n' % (i + 1, func.nexusFixNameIfQuotesAreNeeded(self.taxNames[i])))
            f.write('        %3i %s\n' % (self.nTax, func.nexusFixNameIfQuotesAreNeeded(self.taxNames[-1])))
            f.write('    ;\n')

        # write the models comment
        if self.trees:
            first = self.trees[0]
            if likeMcmc:
                if not withTranslation:
                    gm.append("withTranslation is turned off, but likeMcmc is turned on.")
                    gm.append("This will cause grief in TreePartitions, so is prohibited.")
                    gm.append("Both on or both off, please.")
                    raise Glitch, gm
                f.write('    [&&p4 models p%i' % first.model.nParts)
                for pNum in range(first.model.nParts):
                    f.write(' c%i.%i' % (pNum, first.model.parts[pNum].nComps))
                    f.write(' r%i.%i' % (pNum, first.model.parts[pNum].nRMatrices))
                    f.write(' g%i.%i' % (pNum, first.model.parts[pNum].nGdasrvs))
                f.write(']\n')


        # write each tree
        for t in self.trees:
            if not self.writeBranchLengths:
                t.stripBrLens()
            
            if t.logLike:
                f.write('    [logLike for tree %s is %f]\n' % (t.name, t.logLike))

            f.write('    tree %s = [&U] ' % func.nexusFixNameIfQuotesAreNeeded(t.name))
            if t.recipWeight:
                #if t.recipWeight == 1:
                #    f.write('[&W 1] ')
                #else:
                f.write('[&W 1/%i] ' % t.recipWeight)
            t.writeNewick(f, withTranslation=withTranslation, translationHash=translationHash, doMcmcCommandComments=likeMcmc)

        f.write('end;\n\n')
        if f != sys.stdout:
            f.close()
コード例 #5
0
def writeNewick(
    self, fName=None, withTranslation=0, translationHash=None, doMcmcCommandComments=0, toString=False, append=False
):
    """Write the tree in Newick, aka Phylip, format.

    This is done in a Nexus-oriented way.  If taxNames have spaces or
    odd characters, they are single-quoted.  There is no restriction
    on the length of the taxon names.  A translationHash can be used.

    fName may also be an open file object.

    If 'toString' is turned on, then 'fName' should be None, and a Newick
    representation of the tree is returned as a string.

    The method 'writePhylip()' is the same as this, with fewer arguments.
    """

    gm = ["Tree.writeNewick()"]

    sList = []
    if withTranslation and not translationHash:
        gm.append("No translationHash.")
        raise Glitch, gm

    if fName and toString:
        gm.append("You cannot write to a file and string at the same time.")
        raise Glitch, gm

    if doMcmcCommandComments:
        if not self.model:
            gm.append("No model attached to tree.")
            gm.append("Set doMcmcCommandComments=0")
            raise Glitch, gm

    # print 'self.preAndPostOrderAreValid = %s' % self.preAndPostOrderAreValid
    if not self.preAndPostOrderAreValid:
        self.setPreAndPostOrder()
    # print "self.preOrder = %s" % self.preOrder

    nNodes = len([n for n in self.iterNodes()])  # Don't count un-used nodes.
    # print "nNodes = %i" % nNodes

    if nNodes == 1:
        # print "Single node.  isLeaf=%s, name=%s" % (self.root.isLeaf, self.root.name)
        if self.root.isLeaf:
            if withTranslation:
                sList.append("%s" % translationHash[self.root.name])
            elif self.root.name:
                sList.append("%s" % func.nexusFixNameIfQuotesAreNeeded(self.root.name))
            else:
                sList.append("()")
        else:
            # Will this ever happen?
            gm.append("Something is wrong.  There is only one node, and it is not terminal.")
            raise Glitch, gm

    elif nNodes > 1:
        writeBrLens = 0
        for n in self.iterNodesNoRoot():
            if n.br.len != 0.1:
                writeBrLens = 1
                break
        stack = []
        for n in self.iterPreOrder():
            stack.append(n)

            if n.leftChild:
                sList.append("(")
                continue

            while len(stack):
                n1 = stack.pop()
                # print "stacklen=%i, n1 name=%s" % (len(stack), n1.name)
                if n1.isLeaf:
                    if n1 == self.root:
                        sList.append(")")
                    if withTranslation:
                        sList.append("%s" % (translationHash[n1.name]))
                    else:
                        if n1.name:
                            sList.append("%s" % func.nexusFixNameIfQuotesAreNeeded(n1.name))
                        else:
                            if n1 != self.root:
                                gm.append("Terminal node with no name?")
                                raise Glitch, gm
                else:
                    sList.append(")")
                    if n1.name:
                        sList.append("%s" % func.nexusFixNameIfQuotesAreNeeded(n1.name))
                if writeBrLens:
                    if n1 != self.root:
                        sList.append(":%g" % n1.br.len)
                if doMcmcCommandComments:
                    sList.append(self._getMcmcCommandComment(n1))
                if n1.sibling:
                    sList.append(", ")
                    break
    sList.append(";\n")
    if toString:
        return "".join(sList)
    elif fName == None:
        print "".join(sList)
    elif type(fName) == type("string"):
        if append:
            fName2 = file(fName, "a")
        else:
            fName2 = file(fName, "w")
        fName2.write(string.join(sList, ""))
        #        fName2.write('\n')
        fName2.close()
    elif hasattr(fName, "write"):
        fName.write(string.join(sList, ""))
        # fName.write('\n')
        # Somebody else opened the fName, so somebody else can close it.
    else:
        gm.append("I don't understand (%s) passed to me to write to." % fName)
        raise Glitch, gm
コード例 #6
0
def writeNexus(self, fName=None, append=0, writeTaxaBlockIfTaxNamesIsSet=1, message=None):
    """Write the tree out in Nexus format, in a trees block.

    If fName is None, the default, it is written to sys.stdout.

    #NEXUS is written unless we are appending-- set append=1.

    If you want to write with a translation, use a Trees object.
    """

    gm = ["Tree.writeNexus()"]

    if fName == None or fName == sys.stdout:
        f = sys.stdout
        if not append:
            f.write("#NEXUS\n\n")
    else:
        if append:
            import os

            if os.path.isfile(fName):
                try:
                    f = open(fName, "a")
                except IOError:
                    gm.append("Can't open %s for appending." % fName)
                    raise Glitch, gm
            else:
                if 0:
                    print "Tree.writeNexus()"
                    print "    'append' is requested,"
                    print "    but '%s' is not a regular file (doesn't exist?)." % fName
                    print "    Writing to a new file instead."
                try:
                    f = open(fName, "w")
                    f.write("#NEXUS\n\n")
                except IOError:
                    gm.append("Can't open %s for writing." % fName)
                    raise Glitch, gm

        else:
            try:
                f = open(fName, "w")
                f.write("#NEXUS\n\n")
            except IOError:
                gm.append("Can't open %s for writing." % fName)
                raise Glitch, gm

    if writeTaxaBlockIfTaxNamesIsSet and self.taxNames:
        f.write("begin taxa;\n")
        f.write("  dimensions ntax=%s;\n" % self.nTax)
        f.write("  taxlabels")
        for i in self.taxNames:
            f.write(" %s" % func.nexusFixNameIfQuotesAreNeeded(i))
        f.write(";\nend;\n\n")

    f.write("begin trees;\n")
    if message:
        f.write("  [%s\n  ]\n" % message)
    if self.logLike:
        f.write("  [logLike for tree %s is %f]\n" % (self.name, self.logLike))

    f.write("  tree %s = [&U] " % func.nexusFixNameIfQuotesAreNeeded(self.name))
    if self.recipWeight:
        if self.recipWeight == 1:
            f.write("[&W 1] ")
        else:
            f.write("[&W 1/%i] " % self.recipWeight)
    if hasattr(self, "weight"):
        f.write("[&W %f] " % self.weight)

    self.writeNewick(f)
    f.write("end;\n\n")
    if f != sys.stdout:
        f.close()
コード例 #7
0
    def writeNexusToOpenFile(self, flob, writeTaxaBlock, append, digitsAfterDecimal):

        gm = ["DistanceMatrix.writeNexusToOpenFile()"]
        import string
        assert self.dim, "Distance Matrix.writeNexusToOpenFile() no dim"
        f = flob

        if append:
            pass
        else:
            f.write('#NEXUS\n\n')

        if writeTaxaBlock:
            f.write('begin taxa;\n')
            f.write('  dimensions ntax=%s;\n' % self.dim)
            f.write('  taxlabels')
            for i in range(self.dim):
                f.write(' %s' % func.nexusFixNameIfQuotesAreNeeded(self.names[i]))
            f.write(';\n')
            f.write('end;\n\n')


        f.write('begin distances;\n')
        if self.message:
            f.write("\n  [%s\n  ]\n" % self.message)
            
        f.write('  format triangle=both;\n')
        f.write('  matrix\n')

        # Make the format strings.
        if digitsAfterDecimal > 8:
            totWid = digitsAfterDecimal + 5
        else:
            totWid = 11
        #colNameFormat = '%' + '-%is' % totWid
        if digitsAfterDecimal == 0:
            numberFormat = ' %' + '%ii   ' % (totWid - 4)
        elif digitsAfterDecimal > 0:
            numberFormat = '%' + '%i.%if' % (totWid, digitsAfterDecimal)
        else:
            gm.append("digitsAfterDecimal may not be below zero.")
            raise Glitch, gm

        if self.names:
            longestNameLength = 0
            for i in self.names:
                if len(i) > longestNameLength:
                    longestNameLength = len(i)
            nameFormat = '%' + '%is ' % longestNameLength
            f.write('  [')
            f.write(nameFormat % ' ')
            for i in self.names:
                #f.write('%-10s' % i[:9])
                colName = '%s' % i[:totWid - 1]
                f.write(string.center(colName, totWid))
            f.write(']\n')

        for i in range(self.dim):
            if self.names:
                f.write('  ')
                f.write(nameFormat % func.nexusFixNameIfQuotesAreNeeded(self.names[i]))
            for j in range(self.dim):
                #f.write('%10.6f' % self.matrix[i][j])
                f.write(numberFormat % self.matrix[i][j])
            f.write('\n')

        f.write('  ;\n')
        f.write('end;\n')
コード例 #8
0
ファイル: Tree_write.py プロジェクト: supertree-toolkit/stk
def writeNewick(self, fName=None, withTranslation=0, translationHash=None, doMcmcCommandComments=0, toString=False, append=False):
    """Write the tree in Newick, aka Phylip, format.

    This is done in a Nexus-oriented way.  If taxNames have spaces or
    odd characters, they are single-quoted.  There is no restriction
    on the length of the taxon names.  A translationHash can be used.

    fName may also be an open file object.

    If 'toString' is turned on, then 'fName' should be None, and a Newick
    representation of the tree is returned as a string.

    The method 'writePhylip()' is the same as this, with fewer arguments.
    """
    
    gm = ['Tree.writeNewick()']

    sList = []
    if withTranslation and not translationHash:
        gm.append("No translationHash.")
        raise Glitch, gm

    if fName and toString:
        gm.append("You cannot write to a file and string at the same time.")
        raise Glitch, gm

    if doMcmcCommandComments:
        if not self.model:
            gm.append("No model attached to tree.")
            gm.append("Set doMcmcCommandComments=0")
            raise Glitch, gm


    #print 'self.preAndPostOrderAreValid = %s' % self.preAndPostOrderAreValid
    if not self.preAndPostOrderAreValid:
        self.setPreAndPostOrder()
    #print "self.preOrder = %s" % self.preOrder

    nNodes = len([n for n in self.iterNodes()]) # Don't count un-used nodes.
    #print "nNodes = %i" % nNodes

    if nNodes == 1:
        #print "Single node.  isLeaf=%s, name=%s" % (self.root.isLeaf, self.root.name)
        if self.root.isLeaf:
            if withTranslation:
                sList.append('%s' % translationHash[self.root.name])
            elif self.root.name:
                sList.append('%s' % func.nexusFixNameIfQuotesAreNeeded(self.root.name))
            else:
                sList.append('()')
        else:
            # Will this ever happen?
            gm.append("Something is wrong.  There is only one node, and it is not terminal.")
            raise Glitch, gm

    elif nNodes > 1:
        writeBrLens = 0
        for n in self.iterNodesNoRoot():
            if n.br.len != 0.1:
                writeBrLens = 1
                break
        stack = []
        for n in self.iterPreOrder():
            stack.append(n)

            if n.leftChild:
                sList.append('(')
                continue

            while len(stack):
                n1 = stack.pop()
                #print "stacklen=%i, n1 name=%s" % (len(stack), n1.name)
                if n1.isLeaf:
                    if n1 == self.root:
                        sList.append(')')
                    if withTranslation:
                        sList.append('%s' % (translationHash[n1.name]))
                    else:
                        if n1.name:
                            sList.append('%s' % func.nexusFixNameIfQuotesAreNeeded(n1.name))
                        else:
                            if n1 != self.root:
                                gm.append("Terminal node with no name?")
                                raise Glitch, gm
                else:
                    sList.append(')')
                    if n1.name:
                        sList.append('%s' % func.nexusFixNameIfQuotesAreNeeded(n1.name))
                if writeBrLens:
                    if n1 != self.root:
                        sList.append(':%g' % n1.br.len)
                if doMcmcCommandComments:
                    sList.append(self._getMcmcCommandComment(n1))
                if n1.sibling:
                    sList.append(', ')
                    break
    sList.append(';\n')
    if toString:
        return "".join(sList)
    elif fName == None:
        print  "".join(sList)
    elif type(fName) == type('string'):
        if append:
            fName2 = file(fName, 'a')
        else:
            fName2 = file(fName, 'w')
        fName2.write(string.join(sList, ''))
#        fName2.write('\n')
        fName2.close()
    elif hasattr(fName, 'write'):
        fName.write(string.join(sList, ''))
        #fName.write('\n')
        # Somebody else opened the fName, so somebody else can close it.
    else:
        gm.append("I don't understand (%s) passed to me to write to." % fName)
        raise Glitch, gm
コード例 #9
0
ファイル: Tree_write.py プロジェクト: supertree-toolkit/stk
def writeNexus(self, fName=None, append=0, writeTaxaBlockIfTaxNamesIsSet=1, message=None):
    """Write the tree out in Nexus format, in a trees block.

    If fName is None, the default, it is written to sys.stdout.

    #NEXUS is written unless we are appending-- set append=1.

    If you want to write with a translation, use a Trees object.
    """

    gm = ['Tree.writeNexus()']

    if fName == None or fName == sys.stdout:
        f = sys.stdout
        if not append:
            f.write('#NEXUS\n\n')
    else:
        if append:
            import os
            if os.path.isfile(fName):
                try:
                    f = open(fName, 'a')
                except IOError:
                    gm.append("Can't open %s for appending." % fName)
                    raise Glitch, gm
            else:
                if 0:
                    print "Tree.writeNexus()"
                    print "    'append' is requested,"
                    print "    but '%s' is not a regular file (doesn't exist?)." \
                          % fName
                    print "    Writing to a new file instead."
                try:
                    f = open(fName, 'w')
                    f.write('#NEXUS\n\n')
                except IOError:
                    gm.append("Can't open %s for writing." % fName)
                    raise Glitch, gm

        else:
            try:
                f = open(fName, 'w')
                f.write('#NEXUS\n\n')
            except IOError:
                gm.append("Can't open %s for writing." % fName)
                raise Glitch, gm

    if writeTaxaBlockIfTaxNamesIsSet and self.taxNames:
        f.write('begin taxa;\n')
        f.write('  dimensions ntax=%s;\n' % self.nTax)
        f.write('  taxlabels')
        for i in self.taxNames:
            f.write(' %s' % func.nexusFixNameIfQuotesAreNeeded(i))
        f.write(';\nend;\n\n')

    f.write('begin trees;\n')
    if message:
        f.write('  [%s\n  ]\n' % message)
    if self.logLike:
        f.write('  [logLike for tree %s is %f]\n' % (self.name, self.logLike))

    f.write('  tree %s = [&U] ' % func.nexusFixNameIfQuotesAreNeeded(self.name))
    if self.recipWeight:
        if self.recipWeight == 1:
            f.write('[&W 1] ')
        else:
            f.write('[&W 1/%i] ' % self.recipWeight)

    self.writeNewick(f)
    f.write('end;\n\n')
    if f != sys.stdout:
        f.close()
コード例 #10
0
    def writeNexusToOpenFile(self, flob, writeTaxaBlock, append,
                             digitsAfterDecimal):

        gm = ["DistanceMatrix.writeNexusToOpenFile()"]
        import string
        assert self.dim, "Distance Matrix.writeNexusToOpenFile() no dim"
        f = flob

        if append:
            pass
        else:
            f.write('#NEXUS\n\n')

        if writeTaxaBlock:
            f.write('begin taxa;\n')
            f.write('  dimensions ntax=%s;\n' % self.dim)
            f.write('  taxlabels')
            for i in range(self.dim):
                f.write(' %s' %
                        func.nexusFixNameIfQuotesAreNeeded(self.names[i]))
            f.write(';\n')
            f.write('end;\n\n')

        f.write('begin distances;\n')
        if self.message:
            f.write("\n  [%s\n  ]\n" % self.message)

        f.write('  format triangle=both;\n')
        f.write('  matrix\n')

        # Make the format strings.
        if digitsAfterDecimal > 8:
            totWid = digitsAfterDecimal + 5
        else:
            totWid = 11
        #colNameFormat = '%' + '-%is' % totWid
        if digitsAfterDecimal == 0:
            numberFormat = ' %' + '%ii   ' % (totWid - 4)
        elif digitsAfterDecimal > 0:
            numberFormat = '%' + '%i.%if' % (totWid, digitsAfterDecimal)
        else:
            gm.append("digitsAfterDecimal may not be below zero.")
            raise Glitch, gm

        if self.names:
            longestNameLength = 0
            for i in self.names:
                if len(i) > longestNameLength:
                    longestNameLength = len(i)
            nameFormat = '%' + '%is ' % longestNameLength
            f.write('  [')
            f.write(nameFormat % ' ')
            for i in self.names:
                #f.write('%-10s' % i[:9])
                colName = '%s' % i[:totWid - 1]
                f.write(string.center(colName, totWid))
            f.write(']\n')

        for i in range(self.dim):
            if self.names:
                f.write('  ')
                f.write(nameFormat %
                        func.nexusFixNameIfQuotesAreNeeded(self.names[i]))
            for j in range(self.dim):
                #f.write('%10.6f' % self.matrix[i][j])
                f.write(numberFormat % self.matrix[i][j])
            f.write('\n')

        f.write('  ;\n')
        f.write('end;\n')