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