# Posted By

stagger on 02/24/08

# Statistics

Viewed 168 times
Favorited by 0 user(s)

# Transport Matrix Generator

/ Published in: Python
`import csvimport time reader = csv.reader(open("2007.csv", "rb"), dialect="excel", delimiter=";")opcodes = csv.reader(open("opcodes.csv", "rb"), dialect="excel", delimiter=";")writer = csv.writer(file("matrix.csv", "w"), dialect="excel", delimiter=";")  # initialise transport matrix# column 50, row 2: matrix[50][2]matrix = []heading = ['']index = {}op = {}# i is the column indexi = 0for row in opcodes:    code = row[0]    index[code] = i    op[i] = code    matrix.append([code])    heading.append(code)    i += 1for col in matrix:    for j in range(i):        col.append(0) # add OP codes from CSV filefor row in reader:    # parse current row into sequence[] with elements like: {'code':code, 'depth':depth}    sequence = []    code = ''    depth = 0    for char in row[0]:        if char in ' )' and not code == '':            def add(code, depth):                step = {'code': code, 'depth': depth}                sequence.append(step)            add(code, depth)            code = ''         if char == '(':            depth += 1        elif char == ')':            depth -= 1        elif char != ' ':            code += char    add(code, depth)     # add sequence to matrix    stack = []    quantity = int(row[1])    prev_depth = sequence[0]['depth']    prev_code = ''    for step in sequence:        depth = step['depth']        code = step['code']        #print '%s:%d nach %s:%d' % (code, depth, prev_code, prev_depth)        if (depth < prev_depth) and not (stack == []) and (depth == stack[-1]['depth']):            top = stack.pop()            matrix[index[top['code']]][index[code]+1] += quantity        elif depth > prev_depth:            stack.append({'code': prev_code, 'depth': prev_depth})        if prev_code and code and not (depth > prev_depth):            matrix[index[prev_code]][index[code]+1] += quantity        prev_depth = depth        prev_code = code writer.writerow(heading)count = 1for column in matrix:    writer.writerow(column) time.sleep(1)`