plan_gen.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. #!/usr/bin/env python3
  2. ''' plan_gen main functions '''
  3. import time
  4. import numpy as np
  5. import lxml.etree as etree
  6. # constants
  7. # ------------------
  8. MIN_DEPARTURE_TIME = '08:00:00'
  9. MAX_DEPARTURE_TIME = '09:00:00'
  10. WORK_DURATION = '04:00:00'
  11. # utils
  12. # ------------------
  13. def parse_value(string):
  14. ''' convert string to int, float or string '''
  15. try:
  16. return int(string)
  17. except ValueError:
  18. try:
  19. return float(string)
  20. except ValueError:
  21. return string
  22. def parse_params(param_str):
  23. ''' parse a param string to a dict '''
  24. dict_params = {}
  25. if param_str:
  26. for key_value_str in param_str.split(','):
  27. key, value = key_value_str.split('=')
  28. if key in ['hc', 'wc']:
  29. dict_params[key] = [file for file in value.split(':')]
  30. else:
  31. dict_params[key] = parse_value(value)
  32. return dict_params
  33. def get_seconds(time_str):
  34. ''' returns seconds from a time string '''
  35. h, m, s = time_str.split(':')
  36. return int(h) * 3600 + int(m) * 60 + int(s)
  37. def make_gaussian(size, radius=10, center=None):
  38. ''' make a square gaussian kernel '''
  39. x = np.arange(0, size, 1, float)
  40. y = x[:, np.newaxis]
  41. if center is None:
  42. x0 = y0 = size // 2
  43. else:
  44. x0 = center[0]
  45. y0 = center[1]
  46. return np.exp(-4*np.log(2) * ((x-x0)**2 + (y-y0)**2) / radius**2)
  47. # main functions
  48. # ------------------
  49. def make_clusters(nb_clusters, nodes):
  50. ''' make a grid of (nb_clusters*nb_clusters) from a nodes list '''
  51. xmin, xmax, ymin, ymax = get_extrem_nodes(nodes)
  52. dx = (xmax - xmin) / nb_clusters
  53. dy = (ymax - ymin) / nb_clusters
  54. clusters = np.empty((nb_clusters, nb_clusters), dtype=object)
  55. for node in nodes:
  56. x, y = (float(node.get('x')) - xmin, float(node.get('y')) - ymin)
  57. i, j = (int(x/dx), int(y/dy))
  58. if i >= nb_clusters:
  59. i -= 1
  60. if j >= nb_clusters:
  61. j -= 1
  62. if clusters[i][j] is None:
  63. clusters[i][j] = []
  64. clusters[i][j] += [node]
  65. return clusters
  66. # random generators
  67. # ------------------
  68. def rand_time(low, high):
  69. ''' returns a random time between low and high bounds '''
  70. low_s = get_seconds(low)
  71. high_s = get_seconds(high)
  72. delta = np.random.randint(high_s - low_s)
  73. return time.strftime('%H:%M:%S', time.gmtime(low_s + delta))
  74. def rand_node_xy(nodes, clusters):
  75. ''' returns a random node coordinates from a list of nodes '''
  76. used_nodes = nodes
  77. if any(clusters):
  78. cluster = np.random.randint(len(clusters))
  79. used_nodes = clusters[cluster]
  80. node = used_nodes[np.random.randint(len(used_nodes))]
  81. return (node.get('x'), node.get('y'))
  82. def rand_person(nodes, home_clusters, work_clusters):
  83. ''' returns a person as a dictionnary of random parameters '''
  84. home_xy = rand_node_xy(nodes, home_clusters)
  85. work_xy = rand_node_xy(nodes, work_clusters)
  86. home_departure = rand_time(MIN_DEPARTURE_TIME, MAX_DEPARTURE_TIME)
  87. return {'home': home_xy, 'work': work_xy, 'home_departure': home_departure}
  88. # xml builders
  89. # ------------------
  90. def make_child(parent_node, child_name, child_attrs=None):
  91. ''' creates an xml child element and set its attributes '''
  92. child = etree.SubElement(parent_node, child_name)
  93. if child_attrs is None:
  94. return child
  95. for attr, value in child_attrs.items():
  96. child.set(attr, value)
  97. return child
  98. def make_plans(persons):
  99. ''' makes xml tree of plans based on persons list '''
  100. plans = etree.Element('plans')
  101. for n, p in enumerate(persons):
  102. person = make_child(plans, 'person', {'id': str(n+1)})
  103. plan = make_child(person, 'plan')
  104. # plan
  105. make_child(plan, 'act', {'type': 'h', 'x': p['home'][0], 'y': p['home'][1], 'end_time': p['home_departure']})
  106. make_child(plan, 'leg', {'mode': 'car'})
  107. make_child(plan, 'act', {'type': 'w', 'x': p['work'][0], 'y': p['work'][1], 'dur': WORK_DURATION})
  108. make_child(plan, 'leg', {'mode': 'car'})
  109. make_child(plan, 'act', {'type': 'h', 'x': p['home'][0], 'y': p['home'][1]})
  110. return plans
  111. # xml readers
  112. # ------------------
  113. def get_nodes(input_network):
  114. ''' returns all network nodes as a list '''
  115. if not input_network:
  116. return None
  117. tree = etree.parse(input_network)
  118. return [node for node in tree.xpath("/network/nodes/node")]
  119. def get_extrem_nodes(nodes):
  120. ''' returns extremum coordinates of a nodeslist '''
  121. x = [float(node.get('x')) for node in nodes]
  122. y = [float(node.get('y')) for node in nodes]
  123. return min(x), max(x), min(y), max(y)