Procházet zdrojové kódy

reworked the ranking system

Martin před 8 roky
rodič
revize
8d4444a4f8
4 změnil soubory, kde provedl 112 přidání a 38 odebrání
  1. 7 2
      commute.py
  2. 4 3
      properties.py
  3. 84 17
      ranking.py
  4. 17 16
      visualize.py

+ 7 - 2
commute.py

@@ -215,13 +215,16 @@ 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.lat, p.lon from properties p
+        rows = conn.select('''select p.lat, p.lon, price from properties p
                                 where lat is not null and lon is not null''')
 
         random.shuffle(rows)
         to_load = []
 
-        for lat, lon in rows:
+        for lat, lon, price in rows:
+            if not (250000 < price < 450000):
+                continue
+
             closest = None
             closest_dist = None
             
@@ -239,6 +242,8 @@ def analyze_locations(commutes, num_locations):
         
         print('\tRemaining to load: %i' % len(to_load))
 
+        random.shuffle(to_load)
+
         # target = (53.699593,-6.259772)
         # scores = {loc: geo_util.ggcd(target, loc) for loc in to_load}
         # to_load.sort(key=lambda loc: scores[loc])

+ 4 - 3
properties.py

@@ -1,14 +1,13 @@
 import db
 import geo_util
 import config
-import ranking
 
 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')
+        rows = conn.select('select id, lat, lon, size, price, bedrooms, ber from properties where price<450000')
 
         res = {}
-        for property_id, lat, lon, size, price, bedrooms in rows:
+        for property_id, lat, lon, size, price, bedrooms, ber in rows:
             if not price or not size or not lat or not lon:
                 continue
 
@@ -23,6 +22,7 @@ def load_properties(require_active=True):
                 'price': price,
                 'bedrooms': bedrooms,
                 'price_history': [],
+                'ber': ber,
             }
 
         rows = conn.select('select property_id, price from search_results order by time asc')
@@ -32,6 +32,7 @@ def load_properties(require_active=True):
 
             if price.isdigit():
                 price = int(price)
+                res[pid]['price'] = price/1000
             
             res[pid]['price_history'].append(price)
 

+ 84 - 17
ranking.py

@@ -1,32 +1,99 @@
+# From http://www.berratings.com/wp-content/uploads/2013/11/BER_Cert_with_explaination-e1397729848491.jpg
+_BER_RANKINGS = {
+    'A1': (25 + 25) / 2.0,
+    'A2': (25 + 50) / 2.0,
+    'A3': (50 + 75) / 2.0,
+    'B1': (75 + 100) / 2.0,
+    'B2': (100 + 125) / 2.0,
+    'B3': (125 + 150) / 2.0,
+    'C1': (150 + 175) / 2.0,
+    'C2': (175 + 200) / 2.0,
+    'C3': (200 + 225) / 2.0,
+    'D1': (225 + 260) / 2.0,
+    'D2': (260 + 300) / 2.0,
+    'E1': (300 + 340) / 2.0,
+    'E2': (340 + 380) / 2.0,
+    'F': (380 + 450) / 2.0,
+    'G': (450 + 450) / 2.0,
+    'Exempt': (500 + 500) / 2.0,
+}
+
+_BER_CONF = [
+    (25, 1),
+    (300, 0.1),
+]
+
+_SIZE_CONF = [
+    (50, 0.3),
+    (150, 1),
+    (400, 1),
+]
+
+_BEDROOMS_CONF = [
+    (2, 0.3),
+    (4, 1),
+    (10, 1),
+]
+
+_COMMUTE_CONF = [
+    (0, 1),
+    (60*70, 0),
+]
+
+_PRICE_CONF = [
+    (250, 1),
+    (450, 0.5),
+]
+
+
+def _linear(signal, configuration):
+    if signal < configuration[0][0] or signal > configuration[-1][0]:
+        return 0
+
+    for i, (limit, value) in enumerate(configuration):
+        next_limit, next_value = configuration[i+1]
+
+        if signal <= next_limit:
+            limit_diff = next_limit - limit
+            signal_ratio = (signal - limit) / float(limit_diff)
+            return value + (next_value - value) * signal_ratio
+
 def r_size(size):
-    if size < 30 or size > 400:
-        return 0.0
-    elif size > 200:
-        return 1.0
-    else:
-        return (size - 30) / 200.0
+    return _linear(size, _SIZE_CONF)
 
 def r_price(price):
-    if price < 250 or price > 450:
-        return 0
-    else:
-        return 1-((price-200.0)/200.0)
+    return _linear(price, _PRICE_CONF)
 
 def r_commute_duration(duration):
-    return max(0, 1 - (duration / float(70*60)))
+    return _linear(duration, _COMMUTE_CONF)
+
+def r_bedrooms(bedrooms):
+    return _linear(bedrooms, _BEDROOMS_CONF)
+
+def r_ber(ber):
+    ber = ber or 'Exempt'
+
+    value = None
+    if '-' in ber:
+        a, b = ber.split('-')
+        value = (_BER_RANKINGS[a] + _BER_RANKINGS[b]) / 20.
+    else:
+        value = _BER_RANKINGS[ber]
 
-def _rank(price, size, commute_duration):
+    return _linear(value, _BER_CONF)
 
-    # return commute_duration / 3600.0
+def _rank(data):
 
     res = 1.0
 
-    res *= r_size(size)
-    res *= r_price(price)
-    res *= r_commute_duration(commute_duration)
+    res *= r_size(data['size'])
+    res *= r_price(data['price'])
+    res *= r_commute_duration(data['commute_duration'])
+    res *= r_ber(data['ber'])
+    res *= r_bedrooms(data['bedrooms'])
 
     return res
 
 def add_scores(properties_dict):
     for p in properties_dict.values():
-        p['score'] = _rank(p['price'], p['size'], p['commute_duration'])
+        p['score'] = _rank(p)

+ 17 - 16
visualize.py

@@ -47,36 +47,35 @@ def _write_commutes(f, commutes):
 
 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)
+    properties_list.sort(key=lambda x: x[1]['score'], reverse=True)
+    # properties_list = properties_list[:1000]
 
-    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)
+    min_score = max(0, min(x['score'] for x in properties_dict.values()))
+    max_score = max(x['score'] for x in properties_dict.values())
+    min_max_delta = max_score - min_score
 
-        # color = 20 + int(236*(float(i)/len(properties_list)))
+    for pid, data in properties_list:
+        value = (data['score'] - min_score) / min_max_delta
+        value = min(1, value)
+        color = 20 + value * 235
 
-        title = ','.join([str(x) for x in [
-            int(data['price']),
-            data['size'],
-        ]])
+        title = '%.0f-%.0f' % (data['price'], data['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', '---'),
+            'Bedrooms: %s (%.3f)' % (data.get('bedrooms') or '---', ranking.r_bedrooms(data.get('bedrooms'))),
+            'BER: %s (%.3f)' % (data.get('ber') or '---', ranking.r_ber(data.get('ber'))),
         ])
 
         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;')))
+        description += '<br>\nCommute: %.1f (%.3f)<br>' % (total_duration/60.0, ranking.r_commute_duration(total_duration))
+        description += '<br>\n'.join([('  %.1f: %s' % (x['duration']/60.0, (x.get('desc') or x['mode']).replace('>','&gt;').replace('<', '&lt;')))
                                   for x in reversed(data.get('commute_path', []))])
 
         f.write('''<Placemark>
@@ -122,6 +121,8 @@ def run():
 
     properties_dict = {k: v for k, v in properties_dict.items() if v['score'] > 0}
 
+    print('Loaded %i locations with score>0' % len(properties_dict))
+
     _write_kml(commutes, properties_dict, 'vis.kml')
 
 if __name__ == '__main__':