visualize.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import sys
  2. import commute
  3. import config
  4. import db
  5. import geo_util
  6. import properties
  7. import ranking
  8. import util
  9. import datetime
  10. import visualize_map
  11. def _write_bboxes(f):
  12. f.write('''
  13. <Folder>
  14. <visibility>0</visibility>
  15. <name>Monitored bboxes</name>\n''')
  16. for (lat1, lon1), (lat2, lon2) in config.VISUALIZED_BBOXES.values():
  17. f.write('<Placemark><LineString><coordinates>')
  18. f.write('%s,%s' % (lon1, lat1))
  19. f.write(' %s,%s' % (lon1, lat2))
  20. f.write(' %s,%s' % (lon2, lat2))
  21. f.write(' %s,%s' % (lon2, lat1))
  22. f.write(' %s,%s' % (lon1, lat1))
  23. f.write(' %s,%s' % (lon2, lat2))
  24. f.write(' %s,%s' % (lon1, lat2))
  25. f.write(' %s,%s' % (lon2, lat1))
  26. f.write('</coordinates></LineString></Placemark>\n')
  27. f.write('</Folder>')
  28. def _write_styles(f):
  29. for i in range(256):
  30. hexvalue = hex(255-i)[2:].lower()
  31. if len(hexvalue) == 1:
  32. hexvalue = '0' + hexvalue
  33. f.write('<Style id="color-%i"><IconStyle><color>ff%s%sff</color></IconStyle></Style>\n' % (i, hexvalue, hexvalue))
  34. f.write('<Style id="color-green"><IconStyle><color>ff00ff00</color></IconStyle></Style>\n')
  35. def _write_commutes(f, commutes):
  36. f.write('<Folder><name>Commutes</name><visibility>0</visibility>\n')
  37. max_duration = min(4000, max([x['duration'] for x in commutes.values()]))
  38. for loc, commute_data in commutes.items():
  39. duration = commute_data['duration']
  40. color = 20 + int((duration/float(max_duration)) * 236)
  41. color = min(color, 255)
  42. f.write('''<Placemark>
  43. <Point><coordinates>%f,%f</coordinates></Point>
  44. <styleUrl>#color-%i</styleUrl>
  45. <name>%s</name>
  46. <description>%s</description>
  47. </Placemark>\n''' % (loc[1], loc[0], color, int(duration / 60), loc))
  48. f.write('</Folder>')
  49. def _write_properties(f, properties_dict, tmp_ids):
  50. f.write('<Folder><name>Properties</name><visibility>0</visibility>\n')
  51. properties_list = list(properties_dict.items())
  52. properties_list.sort(key=lambda x: x[1]['score'], reverse=True)
  53. min_score = max(0, min(x['score'] for x in properties_dict.values()))
  54. max_score = max(x['score'] for x in properties_dict.values())
  55. min_max_delta = max_score - min_score
  56. for pid, data in properties_list:
  57. color = None
  58. if data['favourite']:
  59. color = 'green'
  60. else:
  61. value = ((data['score'] - min_score) / min_max_delta) if min_max_delta else 1
  62. value = min(1, value)
  63. color = int(20 + value * 235)
  64. title = '%.0f-%.0f-%s-%i' % (data['price'], data['size'], data.get('ber', ''), tmp_ids[pid])
  65. description = '<br>\n'.join([
  66. 'https://www.myhome.ie/_/brochure/_/%i' % pid,
  67. '',
  68. 'Price: %s (%.3f)' % (data.get('price', '---'), ranking.r_price(data.get('price'))),
  69. 'Size: %s (%.3f)' % (int(data.get('size', 0)), ranking.r_size(data.get('size'))),
  70. 'Bedrooms: %s (%.3f)' % (data.get('bedrooms') or '---', ranking.r_bedrooms(data.get('bedrooms'))),
  71. 'Bathrooms: %s (%.3f)' % (data.get('bathrooms') or '---', ranking.r_bathrooms(data.get('bathrooms'))),
  72. 'BER: %s (%.3f)' % (data.get('ber') or '---', ranking.r_ber(data.get('ber'))),
  73. 'Type: %s (%.3f)' % (data.get('type') or '---', ranking.r_type(data.get('type'))),
  74. ])
  75. total_duration = sum(x['duration'] for x in data.get('commute_path', []))
  76. description += '<br>\nCommute: %.1f (%.3f)<br>' % (total_duration/60.0, ranking.r_commute_duration(total_duration))
  77. description += '<br>\n'.join([(' %.1f: %s' % (x['duration']/60.0, (x.get('desc') or x['mode']).replace('>','&gt;').replace('<', '&lt;')))
  78. for x in reversed(data.get('commute_path', []))])
  79. f.write('''<Placemark>
  80. <Point><coordinates>%f,%f</coordinates></Point>
  81. <styleUrl>#color-%s</styleUrl>
  82. <name>%s</name>
  83. <description><![CDATA[ %s ]]></description>
  84. </Placemark>\n''' % (data['loc'][1], data['loc'][0], color, title, description))
  85. f.write('</Folder>\n')
  86. def _write_kml(commutes, properties_dict, fname, tmp_ids):
  87. print('Writing .kml visualization file...')
  88. with open(fname, 'w') as f:
  89. f.write('''<?xml version="1.0" encoding="UTF-8"?>
  90. <kml xmlns="http://www.opengis.net/kml/2.2">
  91. <Document>
  92. ''')
  93. _write_styles(f)
  94. _write_bboxes(f)
  95. if commutes:
  96. _write_commutes(f, commutes)
  97. _write_properties(f, properties_dict, tmp_ids)
  98. f.write('''
  99. </Document>
  100. </kml>
  101. ''')
  102. def _set_tmp_ids(properties_dict):
  103. print ('Setting tmp ids...')
  104. res = {}
  105. with db.connect() as conn:
  106. conn.execute('update properties set tmp_id=null')
  107. properties_list = list(properties_dict.items())
  108. properties_list.sort(key=lambda x: x[1]['score'], reverse=True)
  109. for i, (pid, _) in enumerate(properties_list):
  110. conn.execute('update properties set tmp_id=? where id=?', i, pid)
  111. res[pid] = i
  112. return res
  113. def run():
  114. days = int(sys.argv[1]) if len(sys.argv) > 1 else 31
  115. load_since = datetime.datetime.now() - datetime.timedelta(days=days)
  116. properties_dict = properties.load_properties(True, load_since)
  117. print('Loaded %i properties' % len(properties_dict))
  118. commutes = None
  119. # graph = commute.load_graph()
  120. # commutes = commute.determine_fastest_paths(graph, config.WORKPLACE)
  121. # commute.add_commute_data(properties_dict, commutes)
  122. properties_dict = ranking.add_scores(properties_dict)
  123. n1 = len(properties_dict)
  124. print('\nLoaded %i properties with score > 0' % len(properties_dict))
  125. util.print_distribution([v['score'] for v in properties_dict.values()])
  126. properties_dict = ranking.rerank(properties_dict)
  127. n2 = len(properties_dict)
  128. if n1 != n2:
  129. print('\nAfter reranking, %i properties with score > 0' % len(properties_dict))
  130. util.print_distribution([v['score'] for v in properties_dict.values()])
  131. tmp_ids = _set_tmp_ids(properties_dict)
  132. _write_kml(commutes, properties_dict, 'vis.kml', tmp_ids)
  133. visualize_map.visualize(properties_dict)
  134. if __name__ == '__main__':
  135. run()