1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
|
#! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this work or any portion thereof in published work,
## please cite it as:
##
## Sukumaran, J. and M. T. Holder. 2010. DendroPy: a Python library
## for phylogenetic computing. Bioinformatics 26: 1569-1571.
##
##############################################################################
"""
Various text-manipulating and formatting utilities.
"""
import re
import sys
import time
import itertools
import locale
import codecs
###############################################################################
## Cross-version compatibility
try:
from StringIO import StringIO # Python 2 legacy support: StringIO in this module is the one needed (not io)
except ImportError:
from io import StringIO # Python 3
###############################################################################
## Unicode/String Conversions
ENCODING = locale.getdefaultlocale()[1]
if ENCODING == None:
ENCODING = 'UTF-8'
if ENCODING == None:
ENCODING = 'UTF-8'
def bytes_to_text(s):
"""
Converts a byte string (as read from, e.g., standard input)
to a text string.
In Python 3, this is from type ``bytes`` to ``str``.
In Python 2, this is, confusingly, from type ``str`` to ``unicode``.
"""
s = codecs.decode(s, ENCODING)
if sys.hexversion < 0x03000000:
s = codecs.encode(s, "utf-8")
return s
def parse_curie_standard_qualified_name(prefixed_name, sep=":"):
if sep not in prefixed_name:
raise ValueError("'{}' is not a valid CURIE-standard qualified name".format(prefixed_name))
return prefixed_name.split(":", 1)
## From:
# The Peyotl module of the Open Tree of Life Project
# Mark T. Holder
# https://github.com/mtholder/peyotl
# https://github.com/mtholder/peyotl/blob/c3a544211edc669e664bae28095d52cecfa004f3/peyotl/utility/str_util.py#L5-L25
if sys.version_info.major == 2:
def is_str_type(x):
return isinstance(x, basestring)
else:
def is_str_type(x):
return isinstance(x, str)
###############################################################################
##
def camel_case(s):
components = s.split('_')
return components[0] + "".join(x.title() for x in components[1:])
def snake_case(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
###############################################################################
##
def unique_taxon_label_map(taxa, taxon_label_map=None, max_label_len=0, logger=None):
"""
Given a list of taxa, returns a dictionary with the Taxon objects as
keys and string labels as values, where the labels are guaranteed to
be unique. If ``taxon_label_map`` is pre-populated (as <Taxon> : 'label'),
then those labels will be used as the basis for the label composition,
otherwise the original taxon object label will be used. ``max_label_len``
can be used to restrict the maximum length of the labels.
"""
if taxon_label_map is None:
taxon_label_map = {}
for t in taxa:
taxon_label_map[t] = t.label
labels = []
for t in taxon_label_map:
label = taxon_label_map[t]
idx = 1
if label in labels:
candidate_label = label
while candidate_label in labels:
idx += 1
if max_label_len > 0:
k = max_label_len - len(str(idx))
if k < 1:
raise ValueError("Unable to make labels unique with maximum label length of %d" % max_label_len)
candidate_label = label[:k] + str(idx)
else:
candidate_label = label + str(idx)
label = candidate_label
labels.append(label)
taxon_label_map[t] = label
return taxon_label_map
###############################################################################
##
def format_dict_table(rows, column_names=None, max_column_width=None, border_style=2):
"""
Returns a string representation of a tuple of dictionaries in a
table format. This method can read the column names directly off the
dictionary keys, but if a tuple of these keys is provided in the
'column_names' variable, then the order of column_names will follow
the order of the fields/keys in that variable.
"""
if column_names or len(rows) > 0:
lengths = {}
rules = {}
if column_names:
column_list = column_names
else:
try:
column_list = rows[0].keys()
except:
column_list = None
if column_list:
# characters that make up the table rules
border_style = int(border_style)
#border_style = 0
if border_style == 0:
vertical_rule = ' '
horizontal_rule = ''
rule_junction = ''
elif border_style == 1:
vertical_rule = ' '
horizontal_rule = '-'
rule_junction = '-'
else:
vertical_rule = ' | '
horizontal_rule = '-'
rule_junction = '-+-'
if border_style >= 3:
left_table_edge_rule = '| '
right_table_edge_rule = ' |'
left_table_edge_rule_junction = '+-'
right_table_edge_rule_junction = '-+'
else:
left_table_edge_rule = ''
right_table_edge_rule = ''
left_table_edge_rule_junction = ''
right_table_edge_rule_junction = ''
if max_column_width:
column_list = [c[:max_column_width] for c in column_list]
trunc_rows = []
for row in rows:
new_row = {}
for k in row.keys():
new_row[k[:max_column_width]] = str(row[k])[:max_column_width]
trunc_rows.append(new_row)
rows = trunc_rows
for col in column_list:
rls = [len(str(row[col])) for row in rows]
lengths[col] = max(rls+[len(col)])
rules[col] = horizontal_rule*lengths[col]
template_elements = ["%%(%s)-%ss" % (col, lengths[col]) for col in column_list]
row_template = vertical_rule.join(template_elements)
border_template = rule_junction.join(template_elements)
full_line = left_table_edge_rule_junction + (border_template % rules) + right_table_edge_rule_junction
display = []
if border_style > 0:
display.append(full_line)
display.append(left_table_edge_rule + (row_template % dict(zip(column_list, column_list))) + right_table_edge_rule)
if border_style > 0:
display.append(full_line)
for row in rows:
display.append(left_table_edge_rule + (row_template % row) + right_table_edge_rule)
if border_style > 0:
display.append(full_line)
return "\n".join(display)
else:
return ''
else:
return ''
|