visualize.py 6.0 KB

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