فهرست منبع

better ranking, visualizations

Martin 8 سال پیش
والد
کامیت
87cf5c1e2f
6فایلهای تغییر یافته به همراه92 افزوده شده و 34 حذف شده
  1. 3 1
      .gitignore
  2. 43 15
      commute.py
  3. 15 1
      properties.py
  4. 11 8
      ranking.py
  5. 2 1
      todo.txt
  6. 18 8
      visualize.py

+ 3 - 1
.gitignore

@@ -63,4 +63,6 @@ docs/_build/
 target/
 
 data.db*
-*.kml
+data
+*.kml
+.vscode

+ 43 - 15
commute.py

@@ -155,6 +155,10 @@ def load_graph():
 def determine_fastest_paths(graph, source):
     print('Determining the fastest paths from transit locations to %s...' % str(source))
 
+    links = {}
+    for link_dict in graph.values():
+        links.update(link_dict)
+
     indices = {}
     for loc in graph:
         if loc not in indices:
@@ -175,7 +179,7 @@ def determine_fastest_paths(graph, source):
 
         commutes[current_source] = {
             'duration': current_duration,
-            'path': current_path,
+            'path': [links[link] for link in current_path],
         }
 
         for key, dest_data in graph[current_source].items():
@@ -207,17 +211,17 @@ def log_graph(graph, commutes):
 
         print('')
 
-def analyze_locations(commutes, num_locations=5):
+def analyze_locations(commutes, num_locations):
     print('Loading new directions data for %i locations...' % num_locations)
 
     with db.connect() as conn:
-        rows = conn.select('''select p.id, p.lat, p.lon from properties p
+        rows = conn.select('''select p.lat, p.lon from properties p
                                 where lat is not null and lon is not null''')
 
         random.shuffle(rows)
         to_load = []
 
-        for property_id, lat, lon in rows:
+        for lat, lon in rows:
             closest = None
             closest_dist = None
             
@@ -229,7 +233,7 @@ def analyze_locations(commutes, num_locations=5):
             
             target_loc = (lat, lon)
 
-            if (geo_util.ggcd(target_loc, closest) > 200
+            if (geo_util.ggcd(target_loc, closest) > 300
                 and any(geo_util.inside(target_loc, bbox) for bbox in config.MONITORED_BBOXES)):
                 to_load.append(target_loc)
         
@@ -239,25 +243,49 @@ def analyze_locations(commutes, num_locations=5):
         # scores = {loc: geo_util.ggcd(target, loc) for loc in to_load}
         # to_load.sort(key=lambda loc: scores[loc])
 
-        return
-
         for loc in to_load[:num_locations]:
             print('\tLoading %s...' % str(loc))
             directions_call(loc, config.WORKPLACE, TransitMethod.TRANSIT)
 
 def add_commute_data(properties, commutes):
+
+    cyclable = {k: v for k, v in commutes.items() 
+                if not v['path'] or (v['path'][-1].get('desc') or '').startswith('HEAVY_RAIL') 
+                    or (v['path'][-1].get('desc') or '').startswith('HEAVY_RAIL')}
+
+    transport_options = [
+        (cyclable, 5.5, TransitMethod.CYCLING),
+        (commutes, 1, TransitMethod.WALKING),
+    ]
+
     for p in properties.values():
+        best_path = None
+        best_duration = None
+
+        for data, speed, mode in transport_options:
+            for loc, commute_data in data.items():
+                if best_duration is not None and best_duration <= commute_data['duration']:
+                    continue
+                
+                duration = int(round(geo_util.ggcd(p['loc'], loc) / speed))
+                total_duration = commute_data['duration'] + duration
+
+                if best_duration is None or total_duration < best_duration:
+                    best_duration = total_duration
+                    best_path = commute_data['path'] + [{
+                        'source': p['loc'],
+                        'dest': loc,
+                        'duration': duration,
+                        'mode': mode,
+                    }]
+
         p.update({
-            'commute_duration': 1800,
+            'commute_duration': best_duration,
+            'commute_path': best_path,
         })
 
 if __name__ == '__main__':
-
-    # _record_api_response(data.x)
-    # exit()
-
-    for _ in range(1):
+    while True:
         graph = load_graph()
         commutes = determine_fastest_paths(graph, config.WORKPLACE)
-
-        # analyze_locations(commutes)
+        analyze_locations(commutes, 20)

+ 15 - 1
properties.py

@@ -3,7 +3,7 @@ import geo_util
 import config
 import ranking
 
-def load_properties():
+def load_properties(require_active=True):
     with db.connect() as conn:
         rows = conn.select('select id, lat, lon, size, price, bedrooms from properties where price<450000')
 
@@ -22,6 +22,20 @@ def load_properties():
                 'size': size,
                 'price': price,
                 'bedrooms': bedrooms,
+                'price_history': [],
             }
 
+        rows = conn.select('select property_id, price from search_results order by time asc')
+        for pid, price in rows:
+            if pid not in res:
+                continue
+
+            if price.isdigit():
+                price = int(price)
+            
+            res[pid]['price_history'].append(price)
+
+        if require_active:
+            res = {k: v for k, v in res.items() if v['price_history'] and v['price_history'][-1] != 'GONE'}
+
         return res

+ 11 - 8
ranking.py

@@ -1,4 +1,4 @@
-def _size(size):
+def r_size(size):
     if size < 30 or size > 400:
         return 0.0
     elif size > 200:
@@ -6,21 +6,24 @@ def _size(size):
     else:
         return (size - 30) / 200.0
 
-def _price(price):
-    if price < 200 or price > 400:
+def r_price(price):
+    if price < 250 or price > 450:
         return 0
     else:
-        return (price-200.0)/200.0
+        return 1-((price-200.0)/200.0)
 
-def _commute_duration(duration):
+def r_commute_duration(duration):
     return max(0, 1 - (duration / float(70*60)))
 
 def _rank(price, size, commute_duration):
+
+    # return commute_duration / 3600.0
+
     res = 1.0
 
-    res *= _size(size)
-    res *= _price(price)
-    res *= _commute_duration(commute_duration)
+    res *= r_size(size)
+    res *= r_price(price)
+    res *= r_commute_duration(commute_duration)
 
     return res
 

+ 2 - 1
todo.txt

@@ -1,2 +1,3 @@
 - drogheda walks: bad order
-- crime data
+- crime data
+- rank by BER rating

+ 18 - 8
visualize.py

@@ -54,7 +54,7 @@ def _write_properties(f, properties_dict):
     import random
     random.shuffle(properties_list)
 
-    for i, (pid, data) in enumerate(properties_list[:100]):
+    for i, (pid, data) in enumerate(properties_list[:500]):
         color = 20 + (int((data['score']/float(max_score)) * 236) if max_score else 0)
         color = min(color, 255)
 
@@ -65,18 +65,25 @@ def _write_properties(f, properties_dict):
             data['size'],
         ]])
 
-        description = '\n'.join([
-            'Price: %s' % data.get('price', '---'),
-            'Size: %s' % data.get('size', '---'),
+        description = '<br>\n'.join([
+            'https://www.myhome.ie/_/brochure/_/%i' % pid,
+            '',
+            'Price: %s (%.3f)' % (data.get('price', '---'), ranking.r_price(data.get('price'))),
+            'Size: %s (%.3f)' % (int(data.get('size', 0)), ranking.r_size(data.get('size'))),
             'Bedrooms: %s' % data.get('bedrooms', '---'),
-            'Score: %.4f' % data.get('score'),
         ])
 
+        total_duration = sum(x['duration'] for x in data.get('commute_path', []))
+
+        description += '<br>\nCommute: %i (%.3f)<br>' % (total_duration, ranking.r_commute_duration(total_duration))
+        description += '<br>\n'.join([('  %i: %s' % (x['duration'], (x.get('desc') or x['mode']).replace('>','&gt;').replace('<', '&lt;')))
+                                  for x in reversed(data.get('commute_path', []))])
+
         f.write('''<Placemark>
             <Point><coordinates>%f,%f</coordinates></Point>
             <styleUrl>#color-%i</styleUrl>
             <name>%s</name>
-            <description>%s</description>
+            <description><![CDATA[ %s ]]></description>
         </Placemark>\n''' % (data['loc'][1], data['loc'][0], color, title, description))
 
     f.write('</Folder>\n')    
@@ -91,7 +98,7 @@ def _write_kml(commutes, properties_dict, fname):
         ''')
 
         _write_styles(f)
-        # _write_bboxes(f)
+        _write_bboxes(f)
         # _write_commutes(f, commutes)
         _write_properties(f, properties_dict)
 
@@ -105,13 +112,16 @@ def run():
 
     commutes = commute.determine_fastest_paths(graph, config.WORKPLACE)
 
-    print(commutes)
+    # import json
+    # print(json.dumps({str(k): v for k, v in commutes.items()}))
 
     properties_dict = properties.load_properties()
 
     commute.add_commute_data(properties_dict, commutes)
     ranking.add_scores(properties_dict)
 
+    properties_dict = {k: v for k, v in properties_dict.items() if v['score'] > 0}
+
     _write_kml(commutes, properties_dict, 'vis.kml')
 
 if __name__ == '__main__':