Project

General

Profile

1 996 aaronmk
# XML "function" nodes that transform their contents
2 86 aaronmk
3 111 aaronmk
import datetime
4 968 aaronmk
import re
5 111 aaronmk
6 818 aaronmk
import dates
7 300 aaronmk
import exc
8 917 aaronmk
import maps
9 827 aaronmk
import term
10 86 aaronmk
import xml_dom
11
12 995 aaronmk
##### Exceptions
13
14 962 aaronmk
class SyntaxException(Exception):
15 797 aaronmk
    def __init__(self, cause):
16 962 aaronmk
        Exception.__init__(self, 'Invalid XML function syntax: '
17
            +exc.str_(cause))
18 278 aaronmk
19 843 aaronmk
class FormatException(SyntaxException): pass
20
21 995 aaronmk
##### Functions
22
23
funcs = {}
24
25
def process(node, on_error=exc.raise_):
26
    for child in xml_dom.NodeElemIter(node): process(child, on_error)
27
    name = node.tagName
28
    if name.startswith('_') and name in funcs:
29
        try: value = funcs[name](xml_dom.NodeTextEntryIter(node))
30
        except SyntaxException, e:
31
            str_ = str(node)
32
            exc.add_msg(e, 'function:\n'+str_)
33
            xml_dom.replace(node, node.ownerDocument.createComment(
34
                '\n'+term.emph_multiline(str_)))
35
            on_error(e)
36
        else: xml_dom.replace_with_text(node, value)
37
38 86 aaronmk
def map_items(func, items):
39
    return [(name, func(value)) for name, value in items]
40
41 278 aaronmk
def conv_items(type_, items):
42 787 aaronmk
    def conv(val):
43
        try: return type_(val)
44
        except ValueError, e: raise SyntaxException(e)
45 793 aaronmk
    return map_items(conv, xml_dom.TextEntryOnlyIter(items))
46 278 aaronmk
47 995 aaronmk
#### XML functions
48
49
# Function names must start with _ to avoid collisions with real tags
50
# Functions take arguments (items)
51
52
def _ignore(items):
53 994 aaronmk
    '''Used to "comment out" an XML subtree'''
54
    return None
55 995 aaronmk
funcs['_ignore'] = _ignore
56 994 aaronmk
57 995 aaronmk
def _alt(items):
58 113 aaronmk
    items = list(items)
59
    items.sort()
60
    return items[0][1] # value of lowest-numbered item
61 995 aaronmk
funcs['_alt'] = _alt
62 113 aaronmk
63 995 aaronmk
def _merge(items):
64 917 aaronmk
    items = list(items)
65
    items.sort()
66
    return maps.merge_values(*[v for k, v in items])
67 995 aaronmk
funcs['_merge'] = _merge
68 917 aaronmk
69 995 aaronmk
def _label(items):
70 917 aaronmk
    items = dict(conv_items(str, items)) # get *once* from iter and check types
71
    try:
72
        label = items['label']
73
        value = items['value']
74
    except KeyError, e: raise SyntaxException(e)
75
    return label+': '+value
76 995 aaronmk
funcs['_label'] = _label
77 917 aaronmk
78 995 aaronmk
def _range(items):
79 278 aaronmk
    items = dict(conv_items(float, items))
80 965 aaronmk
    from_ = items.get('from', None)
81
    to = items.get('to', None)
82
    if from_ == None or to == None: return None
83 326 aaronmk
    return str(to - from_)
84 995 aaronmk
funcs['_range'] = _range
85 86 aaronmk
86 995 aaronmk
def _avg(items):
87 86 aaronmk
    count = 0
88
    sum_ = 0.
89 278 aaronmk
    for name, value in conv_items(float, items):
90 86 aaronmk
        count += 1
91
        sum_ += value
92
    return str(sum_/count)
93 995 aaronmk
funcs['_avg'] = _avg
94 86 aaronmk
95 968 aaronmk
class CvException(Exception):
96
    def __init__(self):
97
        Exception.__init__(self, 'CV (coefficient of variation) values are only'
98
            ' allowed for ratio scale data '
99
            '(see <http://en.wikipedia.org/wiki/Coefficient_of_variation>)')
100
101 995 aaronmk
def _noCV(items):
102 968 aaronmk
    try: name, value = items.next()
103
    except StopIteration: return None
104
    if re.match('^(?i)CV *\d+$', value): raise SyntaxException(CvException())
105
    return value
106 995 aaronmk
funcs['_noCV'] = _noCV
107 968 aaronmk
108 995 aaronmk
def _date(items):
109 917 aaronmk
    items = conv_items(str, items) # get *once* from iter and check types
110 786 aaronmk
    try: str_ = dict(items)['date']
111
    except KeyError:
112
        items = dict(filter(lambda (k, v): v != 0, conv_items(int, items)))
113
        items.setdefault('year', 1900)
114
        items.setdefault('month', 1)
115
        items.setdefault('day', 1)
116
        try: date = datetime.date(**items)
117
        except ValueError, e: raise SyntaxException(e)
118
    else:
119 324 aaronmk
        try: year = float(str_)
120
        except ValueError:
121
            try: import dateutil.parser
122
            except ImportError: return str_
123
            try: date = dateutil.parser.parse(str_)
124
            except ValueError, e: raise SyntaxException(e)
125
        else: date = (datetime.date(int(year), 1, 1) +
126
            datetime.timedelta(round((year % 1.)*365)))
127 818 aaronmk
    try: return dates.strftime('%Y-%m-%d', date)
128 843 aaronmk
    except ValueError, e: raise FormatException(e)
129 995 aaronmk
funcs['_date'] = _date
130 86 aaronmk
131 328 aaronmk
_name_parts_slices_items = [
132
    ('first', slice(None, 1)),
133
    ('middle', slice(1, -1)),
134
    ('last', slice(-1, None)),
135
]
136
name_parts_slices = dict(_name_parts_slices_items)
137
name_parts = [name for name, slice_ in _name_parts_slices_items]
138
139 995 aaronmk
def _name(items):
140 89 aaronmk
    items = dict(items)
141 102 aaronmk
    parts = []
142 328 aaronmk
    for part in name_parts:
143
        if part in items: parts.append(items[part])
144 102 aaronmk
    return ' '.join(parts)
145 995 aaronmk
funcs['_name'] = _name
146 102 aaronmk
147 995 aaronmk
def _namePart(items):
148 328 aaronmk
    out_items = []
149
    for part, value in items:
150
        try: slice_ = name_parts_slices[part]
151
        except KeyError, e: raise SyntaxException(e)
152
        else: out_items.append((part, ' '.join(value.split(' ')[slice_])))
153 995 aaronmk
    return _name(out_items)
154
funcs['_namePart'] = _namePart