visualize.py 6.0 KB

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