Kaggle competition: Hash Code Archive - Drone Delivery
<SOS> metric: PostProcessorKernelDesc Kaggle data source: hash-code-archive-drone-delivery<concatenate>
import pandas as pd
import numpy as np
from tqdm import tqdm
tr = train[['Age', 'Title']]
ts = test[['Age', 'Title']]
tr_ts = pd.concat([tr, ts])
 print(tr_ts.groupby('Title' ).mean() )<categorify>
print('Extracting data')
 with open('/kaggle/input/hashcode-drone-delivery/busy_day.in')as file:
line_list = file.read().splitlines()
ROWS, COLS, DRONES, TURNS, MAXLOAD = map(int, line_list[0].split())
 weights = line_list[2].split()
products_df = pd.DataFrame({'weight': weights})
 wh_count = int(line_list[3])
 wh_endline =(wh_count*2)+4
wh_invs = line_list[5:wh_endline+1:2]
for i, wh_inv in enumerate(wh_invs):
products_df[f'wh{i}_inv'] = wh_inv.split()
products_df = products_df.astype(int)
 wh_locs = line_list[4:wh_endline:2]
wh_rows = [wl.split() [0] for wl in wh_locs]
wh_cols = [wl.split() [1] for wl in wh_locs]
warehouse_df = pd.DataFrame(
 {'wh_row': wh_rows, 'wh_col': wh_cols} ).astype(np.uint16)
 order_locs = line_list[wh_endline+1::3]
o_rows = [ol.split() [0] for ol in order_locs]
o_cols = [ol.split() [1] for ol in order_locs]
orders_df = pd.DataFrame({'row': o_rows, 'col': o_cols})
 orders_df[orders_df.duplicated(keep=False)].sort_values('row')
 orders_df['product_count'] = line_list[wh_endline+2::3]
order_array = np.zeros(( len(orders_df), len(products_df)) , dtype=np.uint16)
 orders = line_list[wh_endline+3::3]
for i,order in enumerate(orders):
products = [int(prod)for prod in order.split() ]
for p in products:
order_array[i, p] += 1
df = pd.DataFrame(data=order_array,
columns=['p_'+ str(i)for i in range(400)],
index=orders_df.index)
 orders_df = orders_df.astype(int ).join(df)
 print('...success' )
c_train_type = train['Cabin'].str[0]
train['c_type'] = c_train_type
train['c_type'] = train['c_type'].fillna('unknown')
 c_test_type = test['Cabin'].str[0]
test['c_type'] = c_test_type
test['c_type'] = test['c_type'].fillna('unknown' )<categorify>
submission = pd.read_csv('/kaggle/input/2020hcdd-sample-submission/submission.csv')
 allcommands = submission[submission.columns[0]].values
order_completion_times = np.full(( len(orders_df)) , -1)
 missing_items = orders_df.copy()
inventory_ops = pd.DataFrame(columns=['action', 'wh', 'item', 'count', 'turn'])
 for ddd in tqdm(range(DRONES)) :
dronecommands = [iii for iii in allcommands if iii.split() [0] == str(ddd)]
currentloc = warehouse_df.loc[0].values
currenttime = 0
currentweight = 0
for cmd in dronecommands:
_, action, locidx, prod, count = cmd.split(' ')
 if action == 'W':
currenttime += locidx
continue
if action == 'L' or action == 'U':
newloc = warehouse_df.loc[int(locidx)].values
elif action == 'D':
newloc = orders_df.loc[int(locidx), ['row', 'col']].values
dist = int(np.ceil(np.sqrt(np.sum(( currentloc-newloc)**2))))
currenttime += dist
currenttime += 1
if currenttime > TURNS:
raise Exception('Maximum simulation time exceeded')
 currentloc = np.copy(newloc)
 if action == 'L':
currentweight += int(count)* products_df.loc[int(prod),'weight']
elif action == 'D' or action == 'U':
currentweight -= int(count)* products_df.loc[int(prod),'weight']
if currentweight > MAXLOAD:
raise Exception('Maximum drone load exceeded')
 if action == 'D':
if missing_items.at[int(locidx), 'p_{}'.format(prod)] >= int(count):
missing_items.at[int(locidx), 'p_{}'.format(prod)] -= int(count)
 if currenttime > order_completion_times[int(locidx)]:
order_completion_times[int(locidx)] = currenttime
else:
raise Exception('Too many items delivered')
 if action == 'L' or action == 'U':
inventory_ops = inventory_ops.append({
'action': action,
'wh': int(locidx),
'item': int(prod),
'count': int(count),
'turn': currenttime
}, ignore_index=True )
train['fam_count'] = train['SibSp']+train['Parch']
test['fam_count'] = test['SibSp']+test['Parch']
size = {
0:'alone',
1:'small',
2:'small',
3:'small',
4:'large',
5:'large',
6:'large',
7:'large',
10:'large'
}
train['fam_size'] = train['fam_count'].map(size)
 test['fam_size'] = test['fam_count'].map(size)
 train['is_alone'] = train['fam_size']=='alone'
test['is_alone'] = test['fam_size']=='alone'<normalization>
for wh in range(len(warehouse_df)) :
for item in tqdm(range(len(products_df))):
tmp = inventory_ops[ 
(inventory_ops['wh'] == wh)& 
(inventory_ops['item'] == item)
 ]
if not len(tmp):
continue
tmp = tmp.sort_values(by='turn')
 inv = products_df.loc[item, f'wh{wh}_inv']
if len(tmp[tmp['action'] == 'L'])<= inv:
continue
for iii in tmp.index:
if tmp.loc[iii, 'action'] == 'L':
inv -= tmp.loc[iii, 'count']
else:
inv += tmp.loc[iii, 'count']
if inv < 0:
raise Exception('Removal of unstocked product attempted' )
mm = MinMaxScaler()
for i in ['Age', 'Fare']:
train[i] = mm.fit_transform(train[i].values.reshape(-1,1))
test[i] = mm.fit_transform(test[i].values.reshape(-1,1))<categorify>
completed = np.max(missing_items.iloc[:,3:].values > 0, axis=1)<= 0
print('Orders completed:', len(np.where(completed)[0]))
print('Orders not completed:', len(np.where(completed == False)[0]))
order_scores = np.ceil(100 *(TURNS - order_completion_times[np.where(completed)[0]])/ TURNS)
 print('Score:', int(np.sum(order_scores)) )
<categorify><EOS> 
shutil.copyfile('/kaggle/input/2020hcdd-sample-submission/submission.csv', 'submission.csv' )