Project

General

Profile

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

    
3
import datetime
4
import re
5
import sre_constants
6
import warnings
7

    
8
import angles
9
import dates
10
import exc
11
import format
12
import maps
13
import sql_io
14
import strings
15
import term
16
import units
17
import util
18
import xml_dom
19
import xpath
20

    
21
##### Exceptions
22

    
23
class SyntaxError(exc.ExceptionWithCause):
24
    def __init__(self, cause):
25
        exc.ExceptionWithCause.__init__(self, 'Invalid XML function syntax',
26
            cause)
27

    
28
class FormatException(exc.ExceptionWithCause):
29
    def __init__(self, cause):
30
        exc.ExceptionWithCause.__init__(self, 'Invalid input value', cause)
31

    
32
##### Helper functions
33

    
34
def map_items(func, items):
35
    return [(name, func(value)) for name, value in items]
36

    
37
def cast(type_, val):
38
    '''Throws FormatException if can't cast'''
39
    try: return type_(val)
40
    except ValueError, e: raise FormatException(e)
41

    
42
def conv_items(type_, items):
43
    return map_items(lambda val: cast(type_, val),
44
        xml_dom.TextEntryOnlyIter(items))
45

    
46
def pop_value(items, name='value'):
47
    '''@param name Name of value param, or None to accept any name'''
48
    try: last = items.pop() # last entry contains value
49
    except IndexError: return None # input is empty and no actions
50
    if name != None and last[0] != name: return None # input is empty
51
    return last[1]
52

    
53
funcs = {}
54

    
55
structural_funcs = set()
56

    
57
##### Public functions
58

    
59
def is_func_name(name):
60
    return name.startswith('_') and name != '_' # '_' is default root node name
61

    
62
def is_func(node): return is_func_name(node.tagName)
63

    
64
def is_xml_func_name(name): return is_func_name(name) and name in funcs
65

    
66
def is_xml_func(node): return is_xml_func_name(node.tagName)
67

    
68
def process(node, on_error=exc.raise_, rel_funcs=None, db=None):
69
    '''Evaluates the XML functions in an XML tree.
70
    @param rel_funcs None|set(str...) Relational functions
71
        * container can be any iterable type
72
        * If != None: Non-relational functions are removed, or relational
73
          functions are treated specially, depending on the db param (below).
74
    @param db
75
        * If None: Non-relational functions other than structural functions are
76
          replaced with their last parameter (usually the value), not evaluated.
77
          This is used in column-based mode to remove XML-only functions.
78
        * If != None: Relational functions are evaluated directly. This is used
79
          in row-based mode to combine relational and XML functions.
80
    @return The new node
81
    '''
82
    has_rel_funcs = rel_funcs != None
83
    assert db == None or has_rel_funcs # rel_funcs required if db set
84
    
85
    changed = []
86
    for child in xml_dom.NodeElemIter(node):
87
        new = process(child, on_error, rel_funcs, db)
88
        if new is not child: changed.append(new)
89
    # Do after iterating over the children to avoid invalidating the iterator
90
    for child in changed: xml_dom.merge_adjacent(child)
91
    
92
    name = node.tagName
93
    if not is_func_name(name): return node # not any kind of function
94
    
95
    # Change rel_funcs *after* processing child nodes, which needs orig value
96
    if not has_rel_funcs: rel_funcs = set()
97
    rel_funcs = set(rel_funcs)
98
    
99
    row_mode = has_rel_funcs and db != None
100
    column_mode = has_rel_funcs and db == None
101
    items = list(xml_dom.NodeTextEntryIter(node))
102
    
103
    # Parse function
104
    if len(items) == 1 and items[0][0].isdigit(): # has single numeric param
105
        # pass-through optimization for aggregating functions with one arg
106
        value = items[0][1] # pass through first arg
107
    elif row_mode and name in rel_funcs: # row-based mode: evaluate using DB
108
        value = sql_io.put(db, name, dict(items))
109
    elif column_mode and not name in structural_funcs: # column-based mode
110
        if name in rel_funcs: return # preserve relational functions
111
        # otherwise XML-only, so just replace with last param
112
        value = pop_value(items, None)
113
    else: # local XML function
114
        try: value = funcs[name](items, node)
115
        except Exception, e: # also catch non-wrapped exceptions (XML func bugs)
116
            # Save in case another exception raised, overwriting sys.exc_info()
117
            exc.add_traceback(e)
118
            str_ = strings.ustr(node)
119
            exc.add_msg(e, 'function:\n'+str_)
120
            xml_dom.replace(node, xml_dom.mk_comment(node.ownerDocument,
121
                '\n'+term.emph_multiline(str_)))
122
                
123
            on_error(e)
124
            return # in case on_error() returns
125
    
126
    return xml_dom.replace_with_text(node, value)
127

    
128
##### XML functions
129

    
130
# Function names must start with _ to avoid collisions with real tags
131
# Functions take arguments (items)
132

    
133
#### Structural
134

    
135
def _ignore(items, node):
136
    '''Used to "comment out" an XML subtree'''
137
    return None
138
funcs['_ignore'] = _ignore
139
structural_funcs.add('_ignore')
140

    
141
def _ref(items, node):
142
    '''Used to retrieve a value from another XML node
143
    @param items
144
        addr=<path> XPath to value, relative to the XML func's parent node
145
    '''
146
    items = dict(items)
147
    try: addr = items['addr']
148
    except KeyError, e: raise SyntaxError(e)
149
    
150
    value = xpath.get_value(node.parentNode, addr)
151
    if value == None:
152
        warnings.warn(UserWarning('_ref: XPath reference target missing: '
153
            +str(addr)))
154
    return value
155
funcs['_ref'] = _ref
156
structural_funcs.add('_ref')
157

    
158
#### Conditionals
159

    
160
def _eq(items, node):
161
    items = dict(items)
162
    try:
163
        left = items['left']
164
        right = items['right']
165
    except KeyError: return '' # a value was None
166
    return util.bool2str(left == right)
167
funcs['_eq'] = _eq
168

    
169
def _if(items, node):
170
    items = dict(items)
171
    try:
172
        cond = items['cond']
173
        then = items['then']
174
    except KeyError, e: raise SyntaxError(e)
175
    else_ = items.get('else', None)
176
    cond = bool(cast(strings.ustr, cond))
177
    if cond: return then
178
    else: return else_
179
funcs['_if'] = _if
180

    
181
#### Combining values
182

    
183
def _alt(items, node):
184
    items = list(items)
185
    items.sort()
186
    try: return items[0][1] # value of lowest-numbered item
187
    except IndexError: return None # input got removed by e.g. FormatException
188
funcs['_alt'] = _alt
189

    
190
def _merge(items, node):
191
    items = list(conv_items(strings.ustr, items))
192
        # get *once* from iter, check types
193
    items.sort()
194
    return maps.merge_values(*[v for k, v in items])
195
funcs['_merge'] = _merge
196

    
197
def _label(items, node):
198
    items = dict(conv_items(strings.ustr, items))
199
        # get *once* from iter, check types
200
    value = items.get('value', None)
201
    if value == None: return None # input is empty
202
    try: label = items['label']
203
    except KeyError, e: raise SyntaxError(e)
204
    return label+': '+value
205
funcs['_label'] = _label
206

    
207
#### Transforming values
208

    
209
def _collapse(items, node):
210
    '''Collapses a subtree if the "value" element in it is NULL'''
211
    items = dict(items)
212
    try: require = cast(strings.ustr, items['require'])
213
    except KeyError, e: raise SyntaxError(e)
214
    value = items.get('value', None)
215
    
216
    if xpath.get_value(value, require, allow_rooted=False) == None: return None
217
    else: return value
218
funcs['_collapse'] = _collapse
219

    
220
types_by_name = {None: strings.ustr, 'str': strings.ustr, 'float': float}
221

    
222
def _nullIf(items, node):
223
    items = dict(conv_items(strings.ustr, items))
224
    try: null = items['null']
225
    except KeyError, e: raise SyntaxError(e)
226
    value = items.get('value', None)
227
    type_str = items.get('type', None)
228
    
229
    try: type_ = types_by_name[type_str]
230
    except KeyError, e: raise SyntaxError(e)
231
    null = type_(null)
232
    
233
    try: return util.none_if(value, null)
234
    except ValueError: return value # value not convertible, so can't equal null
235
funcs['_nullIf'] = _nullIf
236

    
237
def repl(repls, value):
238
    '''Raises error if value not in map and no special '*' entry
239
    @param repls dict repl:with
240
        repl "*" means all other input values
241
        with "*" means keep input value the same
242
        with "" means ignore input value
243
    '''
244
    try: new_value = repls[value]
245
    except KeyError, e:
246
        # Save traceback right away in case another exception raised
247
        fe = FormatException(e)
248
        try: new_value = repls['*']
249
        except KeyError: raise fe
250
    if new_value == '*': new_value = value # '*' means keep input value the same
251
    return new_value
252

    
253
def _map(items, node):
254
    '''See repl()
255
    @param items
256
        <last_entry> Value
257
        <other_entries> name=value Mappings. Special values: See repl() repls.
258
    '''
259
    items = conv_items(strings.ustr, items) # get *once* from iter, check types
260
    value = pop_value(items)
261
    if value == None: return None # input is empty
262
    return util.none_if(repl(dict(items), value), u'') # empty value means None
263
funcs['_map'] = _map
264

    
265
def _replace(items, node):
266
    items = conv_items(strings.ustr, items) # get *once* from iter, check types
267
    value = pop_value(items)
268
    if value == None: return None # input is empty
269
    try:
270
        for repl, with_ in items:
271
            if re.match(r'^\w+$', repl):
272
                repl = r'(?<![^\W_])'+repl+r'(?![^\W_])' # match whole word
273
            value = re.sub(repl, with_, value)
274
    except sre_constants.error, e: raise SyntaxError(e)
275
    return util.none_if(value.strip(), u'') # empty strings always mean None
276
funcs['_replace'] = _replace
277

    
278
#### Quantities
279

    
280
def _units(items, node):
281
    items = conv_items(strings.ustr, items) # get *once* from iter, check types
282
    value = pop_value(items)
283
    if value == None: return None # input is empty
284
    
285
    quantity = units.str2quantity(value)
286
    try:
287
        for action, units_ in items:
288
            units_ = util.none_if(units_, u'')
289
            if action == 'default': units.set_default_units(quantity, units_)
290
            elif action == 'to':
291
                try: quantity = units.convert(quantity, units_)
292
                except ValueError, e: raise FormatException(e)
293
            else: raise SyntaxError(ValueError('Invalid action: '+action))
294
    except units.MissingUnitsException, e: raise FormatException(e)
295
    return units.quantity2str(quantity)
296
funcs['_units'] = _units
297

    
298
def parse_range(str_, range_sep='-'):
299
    default = (str_, None)
300
    start, sep, end = str_.partition(range_sep)
301
    if sep == '': return default # not a range
302
    if start == '' and range_sep == '-': return default # negative number
303
    return tuple(d.strip() for d in (start, end))
304

    
305
def _rangeStart(items, node):
306
    items = dict(conv_items(strings.ustr, items))
307
    try: value = items['value']
308
    except KeyError: return None # input is empty
309
    return parse_range(value)[0]
310
funcs['_rangeStart'] = _rangeStart
311

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

    
319
def _range(items, node):
320
    items = dict(conv_items(float, items))
321
    from_ = items.get('from', None)
322
    to = items.get('to', None)
323
    if from_ == None or to == None: return None
324
    return str(to - from_)
325
funcs['_range'] = _range
326

    
327
def _avg(items, node):
328
    count = 0
329
    sum_ = 0.
330
    for name, value in conv_items(float, items):
331
        count += 1
332
        sum_ += value
333
    if count == 0: return None # input is empty
334
    else: return str(sum_/count)
335
funcs['_avg'] = _avg
336

    
337
class CvException(Exception):
338
    def __init__(self):
339
        Exception.__init__(self, 'CV (coefficient of variation) values are only'
340
            ' allowed for ratio scale data '
341
            '(see <http://en.wikipedia.org/wiki/Coefficient_of_variation>)')
342

    
343
def _noCV(items, node):
344
    try: name, value = items.pop() # last entry contains value
345
    except IndexError: return None # input is empty
346
    if re.match('^(?i)CV *\d+$', value): raise FormatException(CvException())
347
    return value
348
funcs['_noCV'] = _noCV
349

    
350
#### Dates
351

    
352
def _date(items, node):
353
    items = dict(conv_items(strings.ustr, items))
354
        # get *once* from iter, check types
355
    try: str_ = items['date']
356
    except KeyError:
357
        # Year is required
358
        try: items['year']
359
        except KeyError, e:
360
            if items == {}: return None # entire date is empty
361
            else: raise FormatException(e)
362
        
363
        # Convert month name to number
364
        try: month = items['month']
365
        except KeyError: pass
366
        else:
367
            if not month.isdigit(): # month is name
368
                try: items['month'] = str(dates.strtotime(month).month)
369
                except ValueError, e: raise FormatException(e)
370
        
371
        items = dict(conv_items(format.str2int, items.iteritems()))
372
        items.setdefault('month', 1)
373
        items.setdefault('day', 1)
374
        
375
        for try_num in xrange(2):
376
            try:
377
                date = datetime.date(**items)
378
                break
379
            except ValueError, e:
380
                if try_num > 0: raise FormatException(e)
381
                    # exception still raised after retry
382
                msg = strings.ustr(e)
383
                if msg == 'month must be in 1..12': # try swapping month and day
384
                    items['month'], items['day'] = items['day'], items['month']
385
                else: raise FormatException(e)
386
    else:
387
        try: year = float(str_)
388
        except ValueError:
389
            try: date = dates.strtotime(str_)
390
            except ImportError: return str_
391
            except ValueError, e: raise FormatException(e)
392
        else: date = (datetime.date(int(year), 1, 1) +
393
            datetime.timedelta(round((year % 1.)*365)))
394
    try: return dates.strftime('%Y-%m-%d', date)
395
    except ValueError, e: raise FormatException(e)
396
funcs['_date'] = _date
397

    
398
def _dateRangeStart(items, node):
399
    items = dict(conv_items(strings.ustr, items))
400
    try: value = items['value']
401
    except KeyError: return None # input is empty
402
    return dates.parse_date_range(value)[0]
403
funcs['_dateRangeStart'] = _dateRangeStart
404

    
405
def _dateRangeEnd(items, node):
406
    items = dict(conv_items(strings.ustr, items))
407
    try: value = items['value']
408
    except KeyError: return None # input is empty
409
    return dates.parse_date_range(value)[1]
410
funcs['_dateRangeEnd'] = _dateRangeEnd
411

    
412
#### Names
413

    
414
_name_parts_slices_items = [
415
    ('first', slice(None, 1)),
416
    ('middle', slice(1, -1)),
417
    ('last', slice(-1, None)),
418
]
419
name_parts_slices = dict(_name_parts_slices_items)
420
name_parts = [name for name, slice_ in _name_parts_slices_items]
421

    
422
def _name(items, node):
423
    items = dict(items)
424
    parts = []
425
    for part in name_parts:
426
        if part in items: parts.append(items[part])
427
    return ' '.join(parts)
428
funcs['_name'] = _name
429

    
430
def _namePart(items, node):
431
    out_items = []
432
    for part, value in items:
433
        try: slice_ = name_parts_slices[part]
434
        except KeyError, e: raise SyntaxError(e)
435
        out_items.append((part, ' '.join(value.split(' ')[slice_])))
436
    return _name(out_items, node)
437
funcs['_namePart'] = _namePart
438

    
439
#### Angles
440

    
441
def _compass(items, node):
442
    '''Converts a compass direction (N, NE, NNE, etc.) into a degree heading'''
443
    items = dict(conv_items(strings.ustr, items))
444
    try: value = items['value']
445
    except KeyError: return None # input is empty
446
    
447
    if not value.isupper(): return value # pass through other coordinate formats
448
    try: return util.cast(str, angles.compass2heading(value)) # ignore None
449
    except KeyError, e: raise FormatException(e)
450
funcs['_compass'] = _compass
451

    
452
#### Paths
453

    
454
def _simplifyPath(items, node):
455
    items = dict(items)
456
    try:
457
        next = cast(strings.ustr, items['next'])
458
        require = cast(strings.ustr, items['require'])
459
        root = items['path']
460
    except KeyError, e: raise SyntaxError(e)
461
    
462
    node = root
463
    while node != None:
464
        new_node = xpath.get_1(node, next, allow_rooted=False)
465
        if xpath.get_value(node, require, allow_rooted=False) == None: # empty
466
            xml_dom.replace(node, new_node) # remove current elem
467
            if node is root: root = new_node # also update root
468
        node = new_node
469
    return root
470
funcs['_simplifyPath'] = _simplifyPath
(34-34/37)