Project

General

Profile

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