Project

General

Profile

1 929 aaronmk
#!/usr/bin/env python
2
# Subtracts map spreadsheet A1->C from A0->B to A->B
3
4
import csv
5 1137 aaronmk
import os.path
6 929 aaronmk
import sys
7
8 1137 aaronmk
sys.path.append(os.path.dirname(__file__)+"/../lib")
9
10 1503 aaronmk
import maps
11 1137 aaronmk
import opts
12
import util
13
14 929 aaronmk
def main():
15 1137 aaronmk
    ignore = opts.env_flag('ignore')
16
    try: _prog_name, map_1_path = sys.argv[:2]
17 929 aaronmk
    except ValueError:
18 1137 aaronmk
        raise SystemExit('Usage: env [ignore=1] '+sys.argv[0]+' <from_map '
19
            'subtract_map [compare_col_num...] [| '+sys.argv[0]
20
            +' subtract_map_2]... >difference_map')
21
    compare_col_nums = map(int, sys.argv[2:]) # 0-based
22 1495 aaronmk
    if compare_col_nums == []:
23
        compare_col_nums = None # list_subset() value for all columns
24 929 aaronmk
25 1137 aaronmk
    def compare_on(row): return tuple(util.list_subset(row, compare_col_nums))
26
27 1503 aaronmk
    headers = [None]*2
28
29 929 aaronmk
    # Get map 1
30 1137 aaronmk
    compare_cols = set()
31 929 aaronmk
    stream = open(map_1_path, 'rb')
32
    reader = csv.reader(stream)
33 1503 aaronmk
    headers[1] = reader.next()
34 929 aaronmk
    for row in reader:
35 1137 aaronmk
        if row[0] != '': compare_cols.add(compare_on(row))
36 929 aaronmk
    stream.close()
37
38
    # Open map 0
39
    reader = csv.reader(sys.stdin)
40 1503 aaronmk
    headers[0] = reader.next()
41 929 aaronmk
42 1503 aaronmk
    # Check col labels
43
    if not maps.combinable(*headers) and not ignore:
44
        raise SystemExit('Map error: '
45
        'Map 0 column 0 label doesn\'t contain map 1 column 0 label')
46
47 929 aaronmk
    # Subtract map 1 from map 0
48
    writer = csv.writer(sys.stdout)
49 1503 aaronmk
    writer.writerow(headers[0])
50 929 aaronmk
    for row in reader:
51 1137 aaronmk
        if compare_on(row) not in compare_cols: writer.writerow(row)
52 929 aaronmk
53
main()