plan_gen.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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, center=None, radius=10):
  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, centers=None, radius=None):
  64. ''' make a list of gaussian probability densities '''
  65. densities = np.zeros((nb_clusters, nb_clusters))
  66. if centers is None:
  67. return make_gaussian(nb_clusters, radius=nb_clusters/2)
  68. for n, c in enumerate(centers):
  69. densities += make_gaussian(nb_clusters, center=c, radius=radius[n])
  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, densities):
  80. ''' returns a random node coordinates from a random cluster '''
  81. clusters = clusters.flatten()
  82. densities = densities.flatten()
  83. cluster = np.random.choice(clusters, p=densities/sum(densities))
  84. if cluster is not None:
  85. node = cluster[np.random.randint(len(cluster))]
  86. else:
  87. node = nodes[np.random.randint(len(nodes))]
  88. return (node.get('x'), node.get('y'))
  89. def rand_person(nodes, clusters, h_dens, w_dens):
  90. ''' returns a person as a dictionnary of random parameters '''
  91. home_xy = rand_node_xy(nodes, clusters, h_dens)
  92. work_xy = rand_node_xy(nodes, clusters, w_dens)
  93. home_departure = rand_time(MIN_DEPARTURE_TIME, MAX_DEPARTURE_TIME)
  94. return {'home': home_xy, 'work': work_xy, 'home_departure': home_departure}
  95. # xml builders
  96. # ------------------
  97. def make_child(parent_node, child_name, child_attrs=None):
  98. ''' creates an xml child element and set its attributes '''
  99. child = etree.SubElement(parent_node, child_name)
  100. if child_attrs is None:
  101. return child
  102. for attr, value in child_attrs.items():
  103. child.set(attr, value)
  104. return child
  105. def make_plans(persons):
  106. ''' makes xml tree of plans based on persons list '''
  107. plans = etree.Element('plans')
  108. for n, p in enumerate(persons):
  109. person = make_child(plans, 'person', {'id': str(n+1)})
  110. plan = make_child(person, 'plan')
  111. # plan
  112. make_child(plan, 'act', {'type': 'h', 'x': p['home'][0], 'y': p['home'][1], 'end_time': p['home_departure']})
  113. make_child(plan, 'leg', {'mode': 'car'})
  114. make_child(plan, 'act', {'type': 'w', 'x': p['work'][0], 'y': p['work'][1], 'dur': WORK_DURATION})
  115. make_child(plan, 'leg', {'mode': 'car'})
  116. make_child(plan, 'act', {'type': 'h', 'x': p['home'][0], 'y': p['home'][1]})
  117. return plans
  118. # xml readers
  119. # ------------------
  120. def get_nodes(input_network):
  121. ''' returns all network nodes as a list '''
  122. if not input_network:
  123. return None
  124. tree = etree.parse(input_network)
  125. return [node for node in tree.xpath("/network/nodes/node")]
  126. def get_extrem_nodes(nodes):
  127. ''' returns extremum coordinates of a nodeslist '''
  128. x = [float(node.get('x')) for node in nodes]
  129. y = [float(node.get('y')) for node in nodes]
  130. return min(x), max(x), min(y), max(y)