Project

General

Profile

1
#!/usr/bin/env python
2
# Inner-joins two map spreadsheets A->B and B->C to A->C
3
# Multi-safe (supports an input appearing multiple times). If multiple outputs
4
# should be considered ambiguous, they can be discarded by setting only_one.
5
# Case- and punctuation-insensitive.
6

    
7
import csv
8
import operator
9
import os.path
10
import re
11
import sys
12
import warnings
13

    
14
sys.path.append(os.path.dirname(__file__)+"/../lib")
15

    
16
import maps
17
import opts
18
import util
19

    
20
def main():
21
    env_names = []
22
    def usage_err():
23
        raise SystemExit('Usage: '+opts.env_usage(env_names, True)+' '
24
            +sys.argv[0]+' <map_0 map_1 [| '+sys.argv[0]+' map_2]... >out_map')
25
    
26
    only_one = opts.env_flag('only_one', False, env_names)
27
    # Uses only columns 0 and 1 of map_1
28
    map_1_core_only = opts.env_flag('map_1_core_only', False, env_names)
29
    # Turns off "No input mapping" errors
30
    quiet = opts.env_flag('quiet', False, env_names)
31
    try: _prog_name, map_1_path = sys.argv
32
    except ValueError: usage_err()
33
    
34
    # Get map 1
35
    map_1 = {}
36
    stream = open(map_1_path, 'rb')
37
    reader = csv.reader(stream)
38
    map_1_cols = reader.next()
39
    for row in reader:
40
        if map_1_core_only: row = row[:2]
41
        if row[0] != '': map_1.setdefault(maps.simplify(row[0]), []).append(row)
42
    stream.close()
43
    
44
    # Join map 1 to map 0
45
    reader = csv.reader(sys.stdin)
46
    writer = csv.writer(sys.stdout)
47
    map_0_cols = reader.next()
48
    if not maps.join_combinable(map_0_cols, map_1_cols):
49
        raise SystemExit('Map error: Map 0 output column name "'+map_0_cols[1]
50
        +'" doesn\'t match map 1 input column name "'+map_1_cols[0]+'"')
51
    writer.writerow(maps.merge_mappings(map_0_cols, map_1_cols))
52
    for row in reader:
53
        def set_error(msg):
54
            row[1] = ''
55
            if not quiet:
56
                warnings.warn(UserWarning(msg))
57
                row[2] = '** '+msg+' ** '+util.list_setdefault(row, 2, '')
58
        
59
        row_written = False
60
        if row[1] != '':
61
            out_orig = row[1] # used in "No join mapping" error msg
62
            
63
            # Look for a match
64
            out_rows = []
65
            suffix = ''
66
            while True:
67
                try:
68
                    out_rows = map_1[maps.simplify(row[1])]
69
                    break
70
                except KeyError:
71
                    # Heuristically look for a match on a parent path.
72
                    # If this produces a syntactically invalid parent path (e.g.
73
                    # there is a / within []), it will be ignored since there
74
                    # wouldn't be a an entry in map_1.
75
                    row[1], sep, new_suffix = row[1].rpartition('/')
76
                    if sep == '': break
77
                    suffix = sep+new_suffix+suffix # prepend new suffix
78
            
79
            # Write new mapping
80
            is_empty = len(out_rows) == 1 and out_rows[0][1] == ''
81
            if only_one and len(out_rows) > 1: # multiple outputs are ambiguous
82
                set_error('Ambiguous mapping for '+row[1]) # discards mapping
83
            elif out_rows and not is_empty: # found non-empty mapping(s)
84
                for out_row in out_rows:
85
                    row_ = row[:] # don't modify row, since it will be reused
86
                    row_ = maps.merge_mappings(row_, out_row)
87
                    if row_[1] != '': row_[1] += suffix # don't modify out_row!
88
                    writer.writerow(row_)
89
                row_written = True
90
            else:
91
                msg = 'No'
92
                if is_empty: msg += ' non-empty'
93
                msg += ' join mapping for '+out_orig
94
                set_error(msg)
95
        elif row[2] == '': # also no comment explaining why no input mapping
96
            set_error('No input mapping for '+row[0])
97
        
98
        if not row_written: writer.writerow(row)
99

    
100
main()
(29-29/62)