1 |
51
|
aaronmk
|
#!/usr/bin/env python
|
2 |
|
|
# Inner-joins two map spreadsheets A->B and B->C to A->C
|
3 |
|
|
|
4 |
|
|
import csv
|
5 |
734
|
aaronmk
|
import os.path
|
6 |
51
|
aaronmk
|
import sys
|
7 |
939
|
aaronmk
|
import warnings
|
8 |
51
|
aaronmk
|
|
9 |
734
|
aaronmk
|
sys.path.append(os.path.dirname(__file__)+"/../lib")
|
10 |
732
|
aaronmk
|
|
11 |
734
|
aaronmk
|
import maps
|
12 |
|
|
|
13 |
51
|
aaronmk
|
def main():
|
14 |
67
|
aaronmk
|
try: _prog_name, map_1_path = sys.argv
|
15 |
51
|
aaronmk
|
except ValueError:
|
16 |
180
|
aaronmk
|
raise SystemExit('Usage: '+sys.argv[0]+' <map_0 map_1 [| '+sys.argv[0]
|
17 |
|
|
+' map_2]... >joined_map')
|
18 |
51
|
aaronmk
|
|
19 |
|
|
# Get map 1
|
20 |
|
|
map_1 = {}
|
21 |
|
|
stream = open(map_1_path, 'rb')
|
22 |
59
|
aaronmk
|
reader = csv.reader(stream)
|
23 |
737
|
aaronmk
|
map_1_cols = reader.next()
|
24 |
51
|
aaronmk
|
for row in reader:
|
25 |
732
|
aaronmk
|
if row[0] != '': map_1[row[0]] = row
|
26 |
51
|
aaronmk
|
stream.close()
|
27 |
|
|
|
28 |
|
|
# Join map 1 to map 0
|
29 |
59
|
aaronmk
|
reader = csv.reader(sys.stdin)
|
30 |
120
|
aaronmk
|
writer = csv.writer(sys.stdout)
|
31 |
737
|
aaronmk
|
map_0_cols = reader.next()
|
32 |
|
|
if not map_0_cols[1] == map_1_cols[0]: raise SystemExit('Map error: '
|
33 |
62
|
aaronmk
|
'Map 0 output column name doesn\'t match map 1 input column name')
|
34 |
737
|
aaronmk
|
writer.writerow(maps.merge_mappings(map_0_cols, map_1_cols))
|
35 |
51
|
aaronmk
|
for row in reader:
|
36 |
730
|
aaronmk
|
if row[1] != '':
|
37 |
1170
|
aaronmk
|
# Look for a match
|
38 |
|
|
out_row = None
|
39 |
|
|
suffix = ''
|
40 |
|
|
while True:
|
41 |
|
|
try:
|
42 |
|
|
out_row = map_1[row[1]]
|
43 |
|
|
break
|
44 |
|
|
except KeyError:
|
45 |
|
|
# Heuristically look for a match on a parent path.
|
46 |
|
|
# If this produces a syntactically invalid parent path (e.g.
|
47 |
|
|
# there is a / within []), it will be ignored since there
|
48 |
|
|
# wouldn't be a an entry in map_1.
|
49 |
|
|
row[1], sep, new_suffix = row[1].rpartition('/')
|
50 |
|
|
if sep == '': break
|
51 |
|
|
suffix = sep+new_suffix+suffix # prepend new suffix
|
52 |
|
|
|
53 |
|
|
# Write new mapping
|
54 |
|
|
if out_row != None:
|
55 |
|
|
row = maps.merge_mappings(row, out_row)
|
56 |
|
|
row[1] += suffix # don't modify out_row!
|
57 |
|
|
else:
|
58 |
939
|
aaronmk
|
msg = 'No join mapping for '+row[1]
|
59 |
|
|
warnings.warn(UserWarning(msg))
|
60 |
|
|
row[2] = '** '+msg+' ** '+row[2]
|
61 |
730
|
aaronmk
|
row[1] = ''
|
62 |
120
|
aaronmk
|
writer.writerow(row)
|
63 |
51
|
aaronmk
|
|
64 |
|
|
main()
|