Project

General

Profile

1
# XML "function" nodes that evaluate their contents to text
2

    
3
import datetime
4
import re
5

    
6
import dates
7
import exc
8
import maps
9
import term
10
import xml_dom
11

    
12
class SyntaxException(Exception):
13
    def __init__(self, cause):
14
        Exception.__init__(self, 'Invalid XML function syntax: '
15
            +exc.str_(cause))
16

    
17
class FormatException(SyntaxException): pass
18

    
19
def map_items(func, items):
20
    return [(name, func(value)) for name, value in items]
21

    
22
def conv_items(type_, items):
23
    def conv(val):
24
        try: return type_(val)
25
        except ValueError, e: raise SyntaxException(e)
26
    return map_items(conv, xml_dom.TextEntryOnlyIter(items))
27

    
28
def alt(items):
29
    items = list(items)
30
    items.sort()
31
    return items[0][1] # value of lowest-numbered item
32

    
33
def merge(items):
34
    items = list(items)
35
    items.sort()
36
    return maps.merge_values(*[v for k, v in items])
37

    
38
def label(items):
39
    items = dict(conv_items(str, items)) # get *once* from iter and check types
40
    try:
41
        label = items['label']
42
        value = items['value']
43
    except KeyError, e: raise SyntaxException(e)
44
    return label+': '+value
45

    
46
def range_(items):
47
    items = dict(conv_items(float, items))
48
    from_ = items.get('from', None)
49
    to = items.get('to', None)
50
    if from_ == None or to == None: return None
51
    return str(to - from_)
52

    
53
def avg(items):
54
    count = 0
55
    sum_ = 0.
56
    for name, value in conv_items(float, items):
57
        count += 1
58
        sum_ += value
59
    return str(sum_/count)
60

    
61
class CvException(Exception):
62
    def __init__(self):
63
        Exception.__init__(self, 'CV (coefficient of variation) values are only'
64
            ' allowed for ratio scale data '
65
            '(see <http://en.wikipedia.org/wiki/Coefficient_of_variation>)')
66

    
67
def no_cv(items):
68
    try: name, value = items.next()
69
    except StopIteration: return None
70
    if re.match('^(?i)CV *\d+$', value): raise SyntaxException(CvException())
71
    return value
72

    
73
def date(items):
74
    items = conv_items(str, items) # get *once* from iter and check types
75
    try: str_ = dict(items)['date']
76
    except KeyError:
77
        items = dict(filter(lambda (k, v): v != 0, conv_items(int, items)))
78
        items.setdefault('year', 1900)
79
        items.setdefault('month', 1)
80
        items.setdefault('day', 1)
81
        try: date = datetime.date(**items)
82
        except ValueError, e: raise SyntaxException(e)
83
    else:
84
        try: year = float(str_)
85
        except ValueError:
86
            try: import dateutil.parser
87
            except ImportError: return str_
88
            try: date = dateutil.parser.parse(str_)
89
            except ValueError, e: raise SyntaxException(e)
90
        else: date = (datetime.date(int(year), 1, 1) +
91
            datetime.timedelta(round((year % 1.)*365)))
92
    try: return dates.strftime('%Y-%m-%d', date)
93
    except ValueError, e: raise FormatException(e)
94

    
95
_name_parts_slices_items = [
96
    ('first', slice(None, 1)),
97
    ('middle', slice(1, -1)),
98
    ('last', slice(-1, None)),
99
]
100
name_parts_slices = dict(_name_parts_slices_items)
101
name_parts = [name for name, slice_ in _name_parts_slices_items]
102

    
103
def name(items):
104
    items = dict(items)
105
    parts = []
106
    for part in name_parts:
107
        if part in items: parts.append(items[part])
108
    return ' '.join(parts)
109

    
110
def name_part(items):
111
    out_items = []
112
    for part, value in items:
113
        try: slice_ = name_parts_slices[part]
114
        except KeyError, e: raise SyntaxException(e)
115
        else: out_items.append((part, ' '.join(value.split(' ')[slice_])))
116
    return name(out_items)
117

    
118
# Function names must start with _ to avoid collisions with real tags
119
# Functions take arguments (items)
120
funcs = {'_alt': alt, '_merge': merge, '_label': label, '_range': range_,
121
    '_avg': avg, '_noCV': no_cv, '_date': date, '_name': name,
122
    '_namePart': name_part}
123

    
124
def process(node, on_error=exc.raise_):
125
    for child in xml_dom.NodeElemIter(node): process(child, on_error)
126
    name = node.tagName
127
    if name.startswith('_') and name in funcs:
128
        try: value = funcs[name](xml_dom.NodeTextEntryIter(node))
129
        except SyntaxException, e:
130
            str_ = str(node)
131
            exc.add_msg(e, 'function:\n'+str_)
132
            xml_dom.replace(node, node.ownerDocument.createComment(
133
                '\n'+term.emph_multiline(str_)))
134
            on_error(e)
135
        else: xml_dom.replace_with_text(node, value)
(13-13/14)