Project

General

Profile

1
# XML "function" nodes that transform their contents
2

    
3
import datetime
4
import operator
5
import os
6
import re
7
import sre_constants
8
import warnings
9

    
10
import angles
11
import dates
12
import exc
13
import format
14
import maps
15
import scalar
16
import sql
17
import sql_io
18
import strings
19
import term
20
import units
21
import util
22
import xml_dom
23
import xpath
24

    
25
##### Exceptions
26

    
27
class SyntaxError(exc.ExceptionWithCause):
28
    def __init__(self, cause):
29
        exc.ExceptionWithCause.__init__(self, 'Invalid XML function syntax',
30
            cause)
31

    
32
class FormatException(exc.ExceptionWithCause):
33
    def __init__(self, cause):
34
        exc.ExceptionWithCause.__init__(self, 'Invalid input value', cause)
35

    
36
##### Helper functions
37

    
38
def map_names(func, params):
39
    return [(func(name), value) for name, value in params]
40

    
41
def variadic_args(node):
42
    args = map_names(float, xml_dom.NodeEntryIter(node))
43
    args.sort()
44
    return [value for name, value in args]
45

    
46
def map_items(func, items):
47
    return [(name, func(value)) for name, value in items]
48

    
49
def cast(type_, val):
50
    '''Throws FormatException if can't cast'''
51
    try: return type_(val)
52
    except ValueError, e: raise FormatException(e)
53

    
54
def conv_items(type_, items):
55
    return map_items(lambda val: cast(type_, val),
56
        xml_dom.TextEntryOnlyIter(items))
57

    
58
def pop_value(items, name='value'):
59
    '''@param name Name of value param, or None to accept any name'''
60
    try: last = items.pop() # last entry contains value
61
    except IndexError: return None # input is empty and no actions
62
    if name != None and last[0] != name: return None # input is empty
63
    return last[1]
64

    
65
def merge_tagged(root):
66
    '''Merges siblings in root that are marked as mergeable.
67
    Used to recombine pieces of nodes that were split apart in the mappings.
68
    '''
69
    for name in set((c.tagName for c in xpath.get(root, '*[@merge=1]'))):
70
        xml_dom.merge_by_name(root, name)
71
    
72
    # Recurse
73
    for child in xml_dom.NodeElemIter(root): merge_tagged(child)
74

    
75
funcs = {}
76
simplifying_funcs = {}
77

    
78
##### Public functions
79

    
80
var_name_prefix = '$'
81

    
82
def is_var_name(str_): return str_.startswith(var_name_prefix)
83

    
84
def is_var(node):
85
    return xml_dom.is_text_node(node) and is_var_name(xml_dom.value(node))
86

    
87
def is_func_name(name):
88
    return name.startswith('_') and name != '_' # '_' is default root node name
89

    
90
def is_func(node): return is_func_name(node.tagName)
91

    
92
def is_xml_func_name(name): return is_func_name(name) and name in funcs
93

    
94
def is_xml_func(node): return is_xml_func_name(node.tagName)
95

    
96
def is_scalar(value):
97
    return scalar.is_scalar(value) and not (util.is_str(value)
98
        and is_var_name(value))
99

    
100
def passthru(node):
101
    '''Passes through single child node. First prunes the node.'''
102
    xml_dom.prune(node)
103
    children = list(xml_dom.NodeEntryIter(node))
104
    if len(children) == 1: xml_dom.replace(node, children[0][1])
105

    
106
def simplify(node):
107
    '''Simplifies an XML tree.
108
    * Merges nodes tagged as mergable
109
    * Runs simplifying functions
110
    '''
111
    for child in xml_dom.NodeElemIter(node): simplify(child)
112
    merge_tagged(node)
113
    
114
    name = node.tagName
115
    
116
    # Pass-through optimizations
117
    if is_func_name(name):
118
        try: func = simplifying_funcs[name]
119
        except KeyError: xml_dom.prune_empty(node)
120
        else: func(node)
121
    # Pruning optimizations
122
    else: # these should not run on functions because they would remove args
123
        xml_dom.prune_children(node)
124

    
125
def process(node, on_error=exc.reraise, is_rel_func=None, db=None):
126
    '''Evaluates the XML functions in an XML tree.
127
    @param is_rel_func None|f(str) Tests if a name is a relational function.
128
        * If != None: Non-relational functions are removed, or relational
129
          functions are treated specially, depending on the db param (below).
130
    @param db
131
        * If None: Non-relational functions other than structural functions are
132
          replaced with their last parameter (usually the value), not evaluated.
133
          This is used in column-based mode to remove XML-only functions.
134
        * If != None: Relational functions are evaluated directly. This is used
135
          in row-based mode to combine relational and XML functions.
136
    '''
137
    has_rel_funcs = is_rel_func != None
138
    assert db == None or has_rel_funcs # rel_funcs required if db set
139
    
140
    for child in xml_dom.NodeElemIter(node):
141
        process(child, on_error, is_rel_func, db)
142
    merge_tagged(node)
143
    
144
    name = node.tagName
145
    if not is_func_name(name): return node # not any kind of function
146
    
147
    row_mode = has_rel_funcs and db != None
148
    column_mode = has_rel_funcs and db == None
149
    func = funcs.get(name, None)
150
    items = list(xml_dom.NodeTextEntryIter(node))
151
    
152
    # Parse function
153
    if len(items) == 1 and items[0][0].isdigit(): # has single numeric param
154
        # pass-through optimization for aggregating functions with one arg
155
        value = items[0][1] # pass through first arg
156
    elif row_mode and (is_rel_func(name) or func == None): # row-based mode
157
        if items and reduce(operator.or_, (xml_dom.is_node(v)
158
            for n, v in items)): return # preserve complex funcs
159
        # Evaluate using DB
160
        try: value = sql_io.put(db, name, dict(items), on_error=on_error)
161
        except sql.DoesNotExistException: return # preserve unknown funcs
162
            # possibly a built-in function of db_xml.put()
163
    elif column_mode or func == None:
164
        # local XML function can't be used or does not exist
165
        if column_mode and is_rel_func(name): return # preserve relational funcs
166
        # otherwise XML-only in column mode, or DB-only in XML output mode
167
        value = pop_value(items, None) # just replace with last param
168
    else: # local XML function
169
        try: value = func(items, node)
170
        except Exception, e: # also catch non-wrapped exceptions (XML func bugs)
171
            # Save in case another exception raised, overwriting sys.exc_info()
172
            exc.add_traceback(e)
173
            str_ = strings.ustr(node)
174
            exc.add_msg(e, 'function:\n'+str_)
175
            xml_dom.replace(node, xml_dom.mk_comment(node.ownerDocument,
176
                '\n'+term.emph_multiline(str_)))
177
                
178
            on_error(e)
179
            return # in case on_error() returns
180
    
181
    xml_dom.replace_with_text(node, value)
182

    
183
##### Simplifying functions
184

    
185
# Function names must start with _ to avoid collisions with real tags
186
# Functions take params (node) and have no return value
187

    
188
#### Logic
189

    
190
simplifying_funcs['_and'] = passthru
191
simplifying_funcs['_or'] = passthru
192

    
193
def _exists(node):
194
    '''Returns whether its node is non-empty'''
195
    xml_dom.replace_with_text(node, not xml_dom.is_empty(node))
196
simplifying_funcs['_exists'] = _exists
197

    
198
def _if(node):
199
    '''
200
    *Must* be run to remove conditions that functions._if() can't handle.
201
    Note: Can add `@name` attr to distinguish separate _if statements.
202
    '''
203
    params = dict(xml_dom.NodeEntryIter(node))
204
    then = params.get('then', None)
205
    cond = params.get('cond', None)
206
    else_ = params.get('else', None)
207
    
208
    if cond == None: xml_dom.replace(node, else_) # always False
209
    elif then == else_: xml_dom.replace(node, then) # always same value
210
    elif is_var(cond): pass # can't simplify variable conditions
211
    elif xml_dom.is_text_node(cond) and bool(xml_dom.value(cond)): # always True
212
        xml_dom.replace(node, then)
213
simplifying_funcs['_if'] = _if
214

    
215
def _nullIf(node):
216
    '''
217
    *Must* be run to remove conditions that functions._nullIf() can't handle.
218
    '''
219
    params = dict(xml_dom.NodeEntryIter(node))
220
    null = params.get('null', None)
221
    value = params.get('value', None)
222
    
223
    if value == None: xml_dom.prune_parent(node) # empty
224
    elif null == None: xml_dom.replace(node, value) # nothing to null out
225
simplifying_funcs['_nullIf'] = _nullIf
226

    
227
#### Comparison
228

    
229
def _eq(node):
230
    params = dict(xml_dom.NodeTextEntryIter(node))
231
    left = params.get('left', None)
232
    right = params.get('right', None)
233
    
234
    if is_scalar(left) and is_scalar(right): # constant
235
        xml_dom.replace_with_text(node, left == right)
236
    elif left == right: xml_dom.replace_with_text(node, True) # always True
237
simplifying_funcs['_eq'] = _eq
238

    
239
#### Merging
240

    
241
simplifying_funcs['_alt'] = passthru
242
simplifying_funcs['_join'] = passthru
243
simplifying_funcs['_join_words'] = passthru
244
simplifying_funcs['_merge'] = passthru
245
simplifying_funcs['_min'] = passthru
246
simplifying_funcs['_max'] = passthru
247

    
248
def _first(node):
249
    '''Chooses the first non-empty param (sorting by numeric param name)'''
250
    xml_dom.prune_children(node)
251
    args = variadic_args(node)
252
    try: first = args[0]
253
    except IndexError: first = None
254
    xml_dom.replace(node, first)
255
simplifying_funcs['_first'] = _first
256

    
257
#### Environment access
258

    
259
def _env(node):
260
    params = dict(xml_dom.NodeTextEntryIter(node))
261
    try: name = params['name']
262
    except KeyError, e: raise SyntaxError(e)
263
    
264
    xml_dom.replace_with_text(node, os.environ[name])
265
simplifying_funcs['_env'] = _env
266

    
267
##### XML functions
268

    
269
# Function names must start with _ to avoid collisions with real tags
270
# Functions take arguments (items, node)
271

    
272
#### Transforming values
273

    
274
def _replace(items, node):
275
    items = conv_items(strings.ustr, items) # get *once* from iter, check types
276
    value = pop_value(items)
277
    if value == None: return None # input is empty
278
    try:
279
        for repl, with_ in items:
280
            if re.match(r'^\w+$', repl):
281
                repl = r'(?<![^\W_])'+repl+r'(?![^\W_])' # match whole word
282
            value = re.sub(repl, with_, value)
283
    except sre_constants.error, e: raise SyntaxError(e)
284
    return util.none_if(value.strip(), u'') # empty strings always mean None
285
funcs['_replace'] = _replace
286

    
287
#### Quantities
288

    
289
def _units(items, node):
290
    value = pop_value(items)
291
    if value == None: return None # input is empty
292
    
293
    quantity = units.str2quantity(value)
294
    try:
295
        for action, units_ in items:
296
            units_ = util.none_if(units_, u'')
297
            if action == 'default': units.set_default_units(quantity, units_)
298
            elif action == 'to':
299
                try: quantity = units.convert(quantity, units_)
300
                except ValueError, e: raise FormatException(e)
301
            else: raise SyntaxError(ValueError('Invalid action: '+action))
302
    except units.MissingUnitsException, e: raise FormatException(e)
303
    return units.quantity2str(quantity)
304
funcs['_units'] = _units
305

    
306
def parse_range(str_, range_sep='-'):
307
    default = (str_, None)
308
    start, sep, end = str_.partition(range_sep)
309
    if sep == '': return default # not a range
310
    if start == '' and range_sep == '-': return default # negative number
311
    return tuple(d.strip() for d in (start, end))
312

    
313
def _rangeStart(items, node):
314
    items = dict(conv_items(strings.ustr, items))
315
    try: value = items['value']
316
    except KeyError: return None # input is empty
317
    return parse_range(value)[0]
318
funcs['_rangeStart'] = _rangeStart
319

    
320
def _rangeEnd(items, node):
321
    items = dict(conv_items(strings.ustr, items))
322
    try: value = items['value']
323
    except KeyError: return None # input is empty
324
    return parse_range(value)[1]
325
funcs['_rangeEnd'] = _rangeEnd
326

    
327
def _range(items, node):
328
    items = dict(conv_items(float, items))
329
    from_ = items.get('from', None)
330
    to = items.get('to', None)
331
    if from_ == None or to == None: return None
332
    return str(to - from_)
333
funcs['_range'] = _range
334

    
335
def _avg(items, node):
336
    count = 0
337
    sum_ = 0.
338
    for name, value in conv_items(float, items):
339
        count += 1
340
        sum_ += value
341
    if count == 0: return None # input is empty
342
    else: return str(sum_/count)
343
funcs['_avg'] = _avg
344

    
345
class CvException(Exception):
346
    def __init__(self):
347
        Exception.__init__(self, 'CV (coefficient of variation) values are only'
348
            ' allowed for ratio scale data '
349
            '(see <http://en.wikipedia.org/wiki/Coefficient_of_variation>)')
350

    
351
def _noCV(items, node):
352
    items = list(conv_items(strings.ustr, items))
353
    try: name, value = items.pop() # last entry contains value
354
    except IndexError: return None # input is empty
355
    if re.match('^(?i)CV *\d+$', value): raise FormatException(CvException())
356
    return value
357
funcs['_noCV'] = _noCV
358

    
359
#### Angles
360

    
361
def _compass(items, node):
362
    '''Converts a compass direction (N, NE, NNE, etc.) into a degree heading'''
363
    items = dict(conv_items(strings.ustr, items))
364
    try: value = items['value']
365
    except KeyError: return None # input is empty
366
    
367
    if not value.isupper(): return value # pass through other coordinate formats
368
    try: return util.cast(str, angles.compass2heading(value)) # ignore None
369
    except KeyError, e: raise FormatException(e)
370
funcs['_compass'] = _compass
(44-44/47)