Prechádzať zdrojové kódy

restructure method locations, improve visualization code

Martin 8 rokov pred
rodič
commit
5a8b314d06
4 zmenil súbory, kde vykonal 179 pridanie a 117 odobranie
  1. 5 117
      commute.py
  2. 27 0
      properties.py
  3. 29 0
      ranking.py
  4. 118 0
      visualize.py

+ 5 - 117
commute.py

@@ -207,91 +207,6 @@ def log_graph(graph, commutes):
 
         print('')
 
-def write_kml(commutes, properties, fname):
-    print('Writing .kml visualization file...')
-
-    with open(fname, 'w') as f:
-        f.write('''<?xml version="1.0" encoding="UTF-8"?>
-        <kml xmlns="http://www.opengis.net/kml/2.2">
-        <Document>
-        ''')
-
-        for i in range(256):
-            hexvalue = hex(255-i)[2:].lower()
-            if len(hexvalue) == 1:
-                hexvalue = '0' + hexvalue
-            f.write('<Style id="color-%i"><IconStyle><color>ff%s%sff</color></IconStyle></Style>\n' % (i, hexvalue, hexvalue))
-
-        max_duration = min(4000, max([x['duration'] for x in commutes.values()]))
-
-        f.write('''
-        <Folder>
-            <visibility>0</visibility>
-            <name>Monitored bboxes</name>\n''')
-
-        for (lat1, lon1), (lat2, lon2) in config.MONITORED_BBOXES:
-            f.write('<Placemark><LineString><coordinates>')
-            f.write('%s,%s' % (lon1, lat1))
-            f.write(' %s,%s' % (lon1, lat2))
-            f.write(' %s,%s' % (lon2, lat2))
-            f.write(' %s,%s' % (lon2, lat1))
-            f.write(' %s,%s' % (lon1, lat1))
-            f.write(' %s,%s' % (lon2, lat2))
-            f.write(' %s,%s' % (lon1, lat2))
-            f.write(' %s,%s' % (lon2, lat1))
-
-            f.write('</coordinates></LineString></Placemark>\n')
-
-            # f.write('''
-            #     <Placemark><Point><coordinates>%f,%f</coordinates></Point></Placemark>
-            #     <Placemark><Point><coordinates>%f,%f</coordinates></Point></Placemark>
-            # ''' % (lon1, lat1, lon2, lat2))
-        f.write('</Folder>')
-
-        f.write('<Folder><name>Commutes</name><visibility>0</visibility>\n')
-        for loc, commute in commutes.items():
-            duration = commute['duration']
-            color = 20 + int((duration/float(max_duration)) * 236)
-            color = min(color, 255)
-
-            f.write('''<Placemark>
-                <Point><coordinates>%f,%f</coordinates></Point>
-                <styleUrl>#color-%i</styleUrl>
-                <name>%s</name>
-                <description>%s</description>
-            </Placemark>\n''' % (loc[1], loc[0], color, int(duration / 60), loc))
-
-        f.write('</Folder>')
-
-        f.write('<Folder><name>Properties</name><visibility>0</visibility>\n')
-        max_score = max(x['score'] for x in properties.values())
-        properties = list(properties.items())
-        properties.sort(key=lambda x: x[1]['score'], reverse=True)
-        for i, (pid, data) in enumerate(properties):
-            color = 20 + int((data['score']/float(max_score)) * 236)
-            color = min(color, 255)
-
-            color = 20 + int(236*(float(i)/len(properties)))
-
-            name = '%s/%s/%s' % (data['price'], data['size'], data['bedrooms'])
-            loc = data['loc']
-            description = pid
-
-            print(color, data)
-
-            f.write('''<Placemark>
-                <Point><coordinates>%f,%f</coordinates></Point>
-                <styleUrl>#color-%i</styleUrl>
-                <name>%s</name>
-                <description>%s</description>
-            </Placemark>\n''' % (loc[1], loc[0], color, name, description))
-        f.write('</Folder>\n')
-
-        f.write('''
-        </Document>
-        </kml>
-        ''')
-
 def analyze_locations(commutes, num_locations=5):
     print('Loading new directions data for %i locations...' % num_locations)
 
@@ -330,31 +245,11 @@ def analyze_locations(commutes, num_locations=5):
             print('\tLoading %s...' % str(loc))
             directions_call(loc, config.WORKPLACE, TransitMethod.TRANSIT)
 
-def load_properties():
-    with db.connect() as conn:
-        rows = conn.select('select id, lat, lon, size, price, bedrooms from properties where price<450000')
-
-        res = {}
-        for property_id, lat, lon, size, price, bedrooms in rows:
-            if not price or not size or not lat or not lon:
-                continue
-
-            if not any(geo_util.inside((lat, lon), bbox) for bbox in config.MONITORED_BBOXES):
-                continue
-
-            price = price/1000
-
-            res[property_id] = {
-                'loc': (lat, lon),
-                'size': size,
-                'price': price,
-                'bedrooms': bedrooms,
-                'score': float(size) / int(price),
-            }
-
-            # print(res[property_id])
-    
-        return res
+def add_commute_data(properties, commutes):
+    for p in properties.values():
+        p.update({
+            'commute_duration': 1800,
+        })
 
 if __name__ == '__main__':
 
@@ -366,10 +261,3 @@ if __name__ == '__main__':
         commutes = determine_fastest_paths(graph, config.WORKPLACE)
 
         # analyze_locations(commutes)
-
-    properties = load_properties()
-
-    write_kml(commutes, properties, 'vis.kml')
-
-
-    # log_graph(graph, commutes)

+ 27 - 0
properties.py

@@ -0,0 +1,27 @@
+import db
+import geo_util
+import config
+import ranking
+
+def load_properties():
+    with db.connect() as conn:
+        rows = conn.select('select id, lat, lon, size, price, bedrooms from properties where price<450000')
+
+        res = {}
+        for property_id, lat, lon, size, price, bedrooms in rows:
+            if not price or not size or not lat or not lon:
+                continue
+
+            if not any(geo_util.inside((lat, lon), bbox) for bbox in config.MONITORED_BBOXES):
+                continue
+
+            price = price/1000
+
+            res[property_id] = {
+                'loc': (lat, lon),
+                'size': size,
+                'price': price,
+                'bedrooms': bedrooms,
+            }
+
+        return res

+ 29 - 0
ranking.py

@@ -0,0 +1,29 @@
+def _size(size):
+    if size < 30 or size > 400:
+        return 0.0
+    elif size > 200:
+        return 1.0
+    else:
+        return (size - 30) / 200.0
+
+def _price(price):
+    if price < 200 or price > 400:
+        return 0
+    else:
+        return (price-200.0)/200.0
+
+def _commute_duration(duration):
+    return max(0, 1 - (duration / float(70*60)))
+
+def _rank(price, size, commute_duration):
+    res = 1.0
+
+    res *= _size(size)
+    res *= _price(price)
+    res *= _commute_duration(commute_duration)
+
+    return res
+
+def add_scores(properties_dict):
+    for p in properties_dict.values():
+        p['score'] = _rank(p['price'], p['size'], p['commute_duration'])

+ 118 - 0
visualize.py

@@ -0,0 +1,118 @@
+import commute
+import config
+import db
+import geo_util
+import properties
+import ranking
+
+def _write_bboxes(f):
+    f.write('''
+    <Folder>
+        <visibility>0</visibility>
+        <name>Monitored bboxes</name>\n''')
+    for (lat1, lon1), (lat2, lon2) in config.MONITORED_BBOXES:
+        f.write('<Placemark><LineString><coordinates>')
+        f.write('%s,%s' % (lon1, lat1))
+        f.write(' %s,%s' % (lon1, lat2))
+        f.write(' %s,%s' % (lon2, lat2))
+        f.write(' %s,%s' % (lon2, lat1))
+        f.write(' %s,%s' % (lon1, lat1))
+        f.write(' %s,%s' % (lon2, lat2))
+        f.write(' %s,%s' % (lon1, lat2))
+        f.write(' %s,%s' % (lon2, lat1))
+        f.write('</coordinates></LineString></Placemark>\n')
+    f.write('</Folder>')
+
+def _write_styles(f):
+    for i in range(256):
+        hexvalue = hex(255-i)[2:].lower()
+        if len(hexvalue) == 1:
+            hexvalue = '0' + hexvalue
+        f.write('<Style id="color-%i"><IconStyle><color>ff%s%sff</color></IconStyle></Style>\n' % (i, hexvalue, hexvalue))
+
+def _write_commutes(f, commutes):
+    f.write('<Folder><name>Commutes</name><visibility>0</visibility>\n')
+    max_duration = min(4000, max([x['duration'] for x in commutes.values()]))
+    for loc, commute_data in commutes.items():
+        duration = commute_data['duration']
+        color = 20 + int((duration/float(max_duration)) * 236)
+        color = min(color, 255)
+        f.write('''<Placemark>
+            <Point><coordinates>%f,%f</coordinates></Point>
+            <styleUrl>#color-%i</styleUrl>
+            <name>%s</name>
+            <description>%s</description>
+        </Placemark>\n''' % (loc[1], loc[0], color, int(duration / 60), loc))
+    f.write('</Folder>')
+
+def _write_properties(f, properties_dict):
+    f.write('<Folder><name>Properties</name><visibility>0</visibility>\n')
+    max_score = max(x['score'] for x in properties_dict.values())
+    properties_list = list(properties_dict.items())
+    
+    # properties_list.sort(key=lambda x: x[1]['score'], reverse=True)
+    import random
+    random.shuffle(properties_list)
+
+    for i, (pid, data) in enumerate(properties_list[:100]):
+        color = 20 + (int((data['score']/float(max_score)) * 236) if max_score else 0)
+        color = min(color, 255)
+
+        # color = 20 + int(236*(float(i)/len(properties_list)))
+
+        title = ','.join([str(x) for x in [
+            int(data['price']),
+            data['size'],
+        ]])
+
+        description = '\n'.join([
+            'Price: %s' % data.get('price', '---'),
+            'Size: %s' % data.get('size', '---'),
+            'Bedrooms: %s' % data.get('bedrooms', '---'),
+            'Score: %.4f' % data.get('score'),
+        ])
+
+        f.write('''<Placemark>
+            <Point><coordinates>%f,%f</coordinates></Point>
+            <styleUrl>#color-%i</styleUrl>
+            <name>%s</name>
+            <description>%s</description>
+        </Placemark>\n''' % (data['loc'][1], data['loc'][0], color, title, description))
+
+    f.write('</Folder>\n')    
+
+def _write_kml(commutes, properties_dict, fname):
+    print('Writing .kml visualization file...')
+
+    with open(fname, 'w') as f:
+        f.write('''<?xml version="1.0" encoding="UTF-8"?>
+        <kml xmlns="http://www.opengis.net/kml/2.2">
+        <Document>
+        ''')
+
+        _write_styles(f)
+        # _write_bboxes(f)
+        # _write_commutes(f, commutes)
+        _write_properties(f, properties_dict)
+
+        f.write('''
+        </Document>
+        </kml>
+        ''')
+
+def run():
+    graph = commute.load_graph()
+
+    commutes = commute.determine_fastest_paths(graph, config.WORKPLACE)
+
+    print(commutes)
+
+    properties_dict = properties.load_properties()
+
+    commute.add_commute_data(properties_dict, commutes)
+    ranking.add_scores(properties_dict)
+
+    _write_kml(commutes, properties_dict, 'vis.kml')
+
+if __name__ == '__main__':
+    run()