|
| 1 | +import os |
| 2 | +import sys |
| 3 | +from django.core.management.base import BaseCommand, CommandError |
| 4 | +from dg.settings import DATABASES |
| 5 | +from loop.models import LoopUser, CombinedTransaction, Village, Crop, Mandi, Farmer, DayTransportation, Gaddidar, \ |
| 6 | + Transporter, Language, CropLanguage, GaddidarCommission, GaddidarShareOutliers, AggregatorIncentive, \ |
| 7 | + AggregatorShareOutliers, IncentiveParameter, IncentiveModel |
| 8 | +import subprocess |
| 9 | +import MySQLdb |
| 10 | +import datetime, time |
| 11 | +import pandas as pd |
| 12 | +from django.db.models import Count, Sum, Avg |
| 13 | +import inspect |
| 14 | +from loop.utils.loop_etl.get_gaddidar_share import compute_gaddidar_share |
| 15 | +from loop.utils.loop_etl.get_aggregator_share import compute_aggregator_share |
| 16 | + |
| 17 | +DIR_PATH = os.path.dirname(os.path.abspath(__file__)) |
| 18 | + |
| 19 | +class LoopStatistics(): |
| 20 | + |
| 21 | + def recompute_myisam(self): |
| 22 | + database = DATABASES['default']['NAME'] |
| 23 | + username = DATABASES['default']['USER'] |
| 24 | + password = DATABASES['default']['PASSWORD'] |
| 25 | + print 'Database : ', database |
| 26 | + print datetime.datetime.utcnow() |
| 27 | + |
| 28 | + create_schema = subprocess.call("mysql -u%s -p%s %s < %s" % (username, password, database, os.path.join(DIR_PATH,'recreate_schema.sql')), shell=True) |
| 29 | + |
| 30 | + if create_schema !=0: |
| 31 | + raise Exception("Could not create schema for loop etl") |
| 32 | + print "Schema created successfully" |
| 33 | + |
| 34 | + try: |
| 35 | + start_time = time.time() |
| 36 | + self.mysql_cn = MySQLdb.connect(host='localhost',user=DATABASES['default']['USER'], passwd=DATABASES['default']['PASSWORD'], db=DATABASES['default']['NAME'], charset='utf8', use_unicode=True) |
| 37 | + # .cursor() |
| 38 | + |
| 39 | + df_loopuser = pd.DataFrame(list(LoopUser.objects.values('id','user__id','name_en'))) |
| 40 | + df_loopuser.rename(columns={"user__id":"user_created__id","name_en":"name"},inplace=True) |
| 41 | + |
| 42 | + print "Loop User Shape",df_loopuser.shape |
| 43 | + |
| 44 | + df_ct = pd.DataFrame(list(CombinedTransaction.objects.values('date','user_created__id','mandi__id','mandi__mandi_name_en','gaddidar__id','gaddidar__gaddidar_name_en').order_by('date').annotate(Sum('quantity'),Sum('amount')))) |
| 45 | + df_ct.rename(columns={"mandi__mandi_name_en":"mandi__mandi_name","gaddidar__gaddidar_name_en":"gaddidar__gaddidar_name"},inplace=True) |
| 46 | + |
| 47 | + print "Combined Transaction Shape",df_ct.shape |
| 48 | + |
| 49 | + df_ct = pd.merge(df_ct,df_loopuser,left_on='user_created__id',right_on='user_created__id',how='left') |
| 50 | + |
| 51 | + df_dt = pd.DataFrame(list(DayTransportation.objects.values('date','user_created__id','mandi__id').order_by('date').annotate(Sum('transportation_cost'),Avg('farmer_share')))) |
| 52 | + |
| 53 | + print "Day Transportation Shape",df_dt.shape |
| 54 | + |
| 55 | + ct_merge_dt = pd.merge(df_ct,df_dt,left_on=['date','user_created__id','mandi__id'],right_on=['date','user_created__id','mandi__id'],how='left') |
| 56 | + |
| 57 | + print "Combined Transaction merged with Day Transportation ",ct_merge_dt.shape |
| 58 | + |
| 59 | + #CALCULATING GADDIDAR SHARE |
| 60 | + gaddidar_share_result = compute_gaddidar_share() |
| 61 | + |
| 62 | + gaddidar_share = pd.DataFrame(gaddidar_share_result) |
| 63 | + |
| 64 | + print "Gaddidar Share",gaddidar_share.shape |
| 65 | + |
| 66 | + # CALCULATING AGGREGATOR INCENTIVE |
| 67 | + aggregator_incentive_result = compute_aggregator_share() |
| 68 | + |
| 69 | + aggregator_incentive = pd.DataFrame(aggregator_incentive_result) |
| 70 | + |
| 71 | + print "Aggregator Incentive",aggregator_incentive.shape |
| 72 | + |
| 73 | + merged_ct_dt_gaddidar = pd.merge(ct_merge_dt,gaddidar_share,left_on=['user_created__id','mandi__id','gaddidar__id','date'],right_on=['user_created__id','mandi__id','gaddidar__id','date'],how='left') |
| 74 | + |
| 75 | + print "After merging Gaddidar Share", merged_ct_dt_gaddidar.shape |
| 76 | + |
| 77 | + result = pd.merge(merged_ct_dt_gaddidar,aggregator_incentive,left_on=['user_created__id','mandi__id','date'],right_on=['user_created__id','mandi__id','date'],how='left') |
| 78 | + |
| 79 | + print "After adding aggregator incentive", result.shape |
| 80 | + result.fillna(value=0,axis=1,inplace=True) |
| 81 | + |
| 82 | + # Getting new farmers who did any transaction on a particular date |
| 83 | + df_farmer_count = pd.read_sql("SELECT T.date, count(T.farmer_id) as distinct_farmer_count FROM ( SELECT farmer_id, min(date) as date FROM loop_combinedtransaction GROUP BY farmer_id) as T GROUP BY T.date",con=self.mysql_cn) |
| 84 | + |
| 85 | + # Cummulating sum of farmers that were unique and did any transaction till a particular date |
| 86 | + df_farmer_count['cummulative_distinct_farmer'] = df_farmer_count['distinct_farmer_count'].cumsum() |
| 87 | + df_farmer_count.drop(['distinct_farmer_count'],axis=1,inplace=True) |
| 88 | + |
| 89 | + result = pd.merge(result,df_farmer_count,left_on='date',right_on='date',how='left') |
| 90 | + result['cummulative_distinct_farmer'].fillna(method='ffill',inplace=True) |
| 91 | + |
| 92 | + # Final result DataFrame contains same value for transportation_cost, farmer share, aggregator_incentive where date,aggregator_id,mandi are same but gaddidar_id is different. |
| 93 | + # Also cummulative_distinct_farmer is same where date is same but aggregator_id,gaddidar_id,mandi_id are different |
| 94 | + print "After adding cummulative distinct farmer ", result.shape |
| 95 | + |
| 96 | + for index,row in result.iterrows(): |
| 97 | + self.mysql_cn.cursor().execute("""INSERT INTO loop_aggregated_myisam (date,aggregator_id,mandi_id,gaddidar_id,quantity,amount,transportation_cost,farmer_share,gaddidar_share,aggregator_incentive,aggregator_name,mandi_name,gaddidar_name,cum_distinct_farmer) values(""" + '"'+row['date'].strftime('%Y-%m-%d %H:%M:%S')+'"' + "," + str(row['user_created__id']) + "," |
| 98 | + + str(row['mandi__id']) + "," |
| 99 | + + str(row['gaddidar__id']) + "," |
| 100 | + + str(row['quantity__sum']) + "," |
| 101 | + + str(row['amount__sum']) + "," |
| 102 | + + str(row['transportation_cost__sum']) + "," |
| 103 | + + str(row['farmer_share__avg']) + "," |
| 104 | + + str(row['gaddidar_share_amount']) + "," |
| 105 | + + str(row['aggregator_incentive']) + "," |
| 106 | + + '"'+row['name']+'"' + "," |
| 107 | + + '"'+row['mandi__mandi_name']+'"' + "," |
| 108 | + + '"'+row['gaddidar__gaddidar_name']+'",' |
| 109 | + + str(row['cummulative_distinct_farmer']) + """)""") |
| 110 | + |
| 111 | + print "Myisam insertion complete" |
| 112 | + end_time = time.time() |
| 113 | + print "Total time taken (secs) : %f" % (end_time-start_time) |
| 114 | + |
| 115 | + ct_outer_merge_dt = pd.merge(df_ct,df_dt,left_on=['date','user_created__id','mandi__id'],right_on=['date','user_created__id','mandi__id'],how='outer') |
| 116 | + |
| 117 | + if ct_outer_merge_dt.shape == ct_merge_dt.shape: |
| 118 | + print "successfully Completed" |
| 119 | + else: |
| 120 | + print "Issue: Some aggregator has DT but no CT corresponding to date(s).", ct_outer_merge_dt.shape |
| 121 | + # print ct_outer_merge_dt[ct_outer_merge_dt.isnull().any(axis=1)] |
| 122 | + print "==================================" |
| 123 | + |
| 124 | + |
| 125 | + except Exception as e: |
| 126 | + print "Error : %s" % (e) |
| 127 | + sys.exit(1) |
| 128 | + |
| 129 | +class Command(BaseCommand): |
| 130 | + help = '''This command updates stats displayed on Loop dashboard. ''' |
| 131 | + |
| 132 | + def handle(self,*args,**options): |
| 133 | + print("Log") |
| 134 | + print("LOOP ETL LOG") |
| 135 | + print(datetime.date.today()) |
| 136 | + loop_statistics = LoopStatistics() |
| 137 | + loop_statistics.recompute_myisam() |
0 commit comments