Transport Matrix Generator


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import csv
  2. import time
  3.  
  4. reader = csv.reader(open("2007.csv", "rb"), dialect="excel", delimiter=";")
  5. opcodes = csv.reader(open("opcodes.csv", "rb"), dialect="excel", delimiter=";")
  6. writer = csv.writer(file("matrix.csv", "w"), dialect="excel", delimiter=";")
  7.  
  8. # initialise transport matrix
  9. # column 50, row 2: matrix[50][2]
  10. matrix = []
  11. heading = ['']
  12. index = {}
  13. op = {}
  14. # i is the column index
  15. i = 0
  16. for row in opcodes:
  17. code = row[0]
  18. index[code] = i
  19. op[i] = code
  20. matrix.append([code])
  21. heading.append(code)
  22. i += 1
  23. for col in matrix:
  24. for j in range(i):
  25. col.append(0)
  26.  
  27. # add OP codes from CSV file
  28. for row in reader:
  29. # parse current row into sequence[] with elements like: {'code':code, 'depth':depth}
  30. sequence = []
  31. code = ''
  32. depth = 0
  33. for char in row[0]:
  34. if char in ' )' and not code == '':
  35. def add(code, depth):
  36. step = {'code': code, 'depth': depth}
  37. sequence.append(step)
  38. add(code, depth)
  39. code = ''
  40.  
  41. if char == '(':
  42. depth += 1
  43. elif char == ')':
  44. depth -= 1
  45. elif char != ' ':
  46. code += char
  47. add(code, depth)
  48.  
  49. # add sequence to matrix
  50. stack = []
  51. quantity = int(row[1])
  52. prev_depth = sequence[0]['depth']
  53. prev_code = ''
  54. for step in sequence:
  55. depth = step['depth']
  56. code = step['code']
  57. #print '%s:%d nach %s:%d' % (code, depth, prev_code, prev_depth)
  58. if (depth < prev_depth) and not (stack == []) and (depth == stack[-1]['depth']):
  59. top = stack.pop()
  60. matrix[index[top['code']]][index[code]+1] += quantity
  61. elif depth > prev_depth:
  62. stack.append({'code': prev_code, 'depth': prev_depth})
  63. if prev_code and code and not (depth > prev_depth):
  64. matrix[index[prev_code]][index[code]+1] += quantity
  65. prev_depth = depth
  66. prev_code = code
  67.  
  68. writer.writerow(heading)
  69. count = 1
  70. for column in matrix:
  71. writer.writerow(column)
  72.  
  73. time.sleep(1)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.