plan_gen.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. dict_params[key] = parse_value(value)
  29. return dict_params
  30. def get_seconds(time_str):
  31. ''' returns seconds from a time string '''
  32. h, m, s = time_str.split(':')
  33. return int(h) * 3600 + int(m) * 60 + int(s)
  34. def make_gaussian(size, radius=10, center=None):
  35. ''' make a square gaussian kernel '''
  36. x = np.arange(0, size, 1, float)
  37. y = x[:, np.newaxis]
  38. if center is None:
  39. x0 = y0 = size // 2
  40. else:
  41. x0 = center[0]
  42. y0 = center[1]
  43. return np.exp(-4*np.log(2) * ((x-x0)**2 + (y-y0)**2) / radius**2)
  44. # main functions
  45. # ------------------
  46. def make_clusters(nb_clusters, nodes):
  47. ''' make a grid of (nb_clusters*nb_clusters) from a nodes list '''
  48. xmin, xmax, ymin, ymax = get_extrem_nodes(nodes)
  49. dx = (xmax - xmin) / nb_clusters
  50. dy = (ymax - ymin) / nb_clusters
  51. clusters = np.empty((nb_clusters, nb_clusters), dtype=object)
  52. for node in nodes:
  53. x, y = (float(node.get('x')) - xmin, float(node.get('y')) - ymin)
  54. i, j = (int(x/dx), int(y/dy))
  55. if i >= nb_clusters:
  56. i -= 1
  57. if j >= nb_clusters:
  58. j -= 1
  59. if clusters[i][j] is None:
  60. clusters[i][j] = []
  61. clusters[i][j] += [node]
  62. return clusters
  63. def make_densities(nb_clusters, radius, centers):
  64. ''' make a list of gaussian probability densities '''
  65. densities = np.zeros((nb_clusters, nb_clusters))
  66. if centers is None:
  67. return densities + 1
  68. for n, c in enumerate(centers):
  69. densities += make_gaussian(nb_clusters, radius=radius[n], center=c)
  70. return densities
  71. # random generators
  72. # ------------------
  73. def rand_time(low, high):
  74. ''' returns a random time between low and high bounds '''
  75. low_s = get_seconds(low)
  76. high_s = get_seconds(high)
  77. delta = np.random.randint(high_s - low_s)
  78. return time.strftime('%H:%M:%S', time.gmtime(low_s + delta))
  79. def rand_node_xy(nodes, clusters):
  80. ''' returns a random node coordinates from a list of nodes '''
  81. used_nodes = nodes
  82. if any(clusters):
  83. cluster = np.random.randint(len(clusters))
  84. used_nodes = clusters[cluster]
  85. node = used_nodes[np.random.randint(len(used_nodes))]
  86. return (node.get('x'), node.get('y'))
  87. def rand_person(nodes, home_clusters, work_clusters):
  88. ''' returns a person as a dictionnary of random parameters '''
  89. home_xy = rand_node_xy(nodes, home_clusters)
  90. work_xy = rand_node_xy(nodes, work_clusters)
  91. home_departure = rand_time(MIN_DEPARTURE_TIME, MAX_DEPARTURE_TIME)
  92. return {'home': home_xy, 'work': work_xy, 'home_departure': home_departure}
  93. # xml builders
  94. # ------------------
  95. def make_child(parent_node, child_name, child_attrs=None):
  96. ''' creates an xml child element and set its attributes '''
  97. child = etree.SubElement(parent_node, child_name)
  98. if child_attrs is None:
  99. return child
  100. for attr, value in child_attrs.items():
  101. child.set(attr, value)
  102. return child
  103. def make_plans(persons):
  104. ''' makes xml tree of plans based on persons list '''
  105. plans = etree.Element('plans')
  106. for n, p in enumerate(persons):
  107. person = make_child(plans, 'person', {'id': str(n+1)})
  108. plan = make_child(person, 'plan')
  109. # plan
  110. make_child(plan, 'act', {'type': 'h', 'x': p['home'][0], 'y': p['home'][1], 'end_time': p['home_departure']})
  111. make_child(plan, 'leg', {'mode': 'car'})
  112. make_child(plan, 'act', {'type': 'w', 'x': p['work'][0], 'y': p['work'][1], 'dur': WORK_DURATION})
  113. make_child(plan, 'leg', {'mode': 'car'})
  114. make_child(plan, 'act', {'type': 'h', 'x': p['home'][0], 'y': p['home'][1]})
  115. return plans
  116. # xml readers
  117. # ------------------
  118. def get_nodes(input_network):
  119. ''' returns all network nodes as a list '''
  120. if not input_network:
  121. return None
  122. tree = etree.parse(input_network)
  123. return [node for node in tree.xpath("/network/nodes/node")]
  124. def get_extrem_nodes(nodes):
  125. ''' returns extremum coordinates of a nodeslist '''
  126. x = [float(node.get('x')) for node in nodes]
  127. y = [float(node.get('y')) for node in nodes]
  128. return min(x), max(x), min(y), max(y)