-
Notifications
You must be signed in to change notification settings - Fork 5
/
liaoyang_harvest.py
290 lines (236 loc) · 11 KB
/
liaoyang_harvest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import argparse
import os
import pandas as pd
import matplotlib.cm as cm
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import warnings
import datetime
import seaborn as sns
from utils.common import mkdir, save_curve
from utils.plt_params import plt_fig_params, set_day_xtick
warnings.filterwarnings("ignore")
os.environ['NLS_LANG'] = 'AMERICAN_AMERICA.AL32UTF8'
def Figure5(args):
print("=============Figure5===============")
save_dir = args.base_tmp_folder+'/figure5/'
mkdir(save_dir)
expr_harvest, ctrl_harvest = get_harvest(args)
price = get_price(args)
# save curve
figure5a_experimental = {"xlabel": 'date', "ylabel": "kg/m2",
"x": range(len(expr_harvest['production'])),
"y": expr_harvest['production']}
figure5a_control = {"xlabel": 'date', "ylabel": "kg/m2",
"x": range(len(ctrl_harvest['production'])),
"y": ctrl_harvest['production']}
figure5b_experimental = {"xlabel": 'date', "ylabel": "euro/m2",
"x": range(len(expr_harvest['gains'])),
"y": expr_harvest['gains']}
figure5b_control = {"xlabel": 'date', "ylabel": "euro/m2",
"x": range(len(ctrl_harvest['gains'])),
"y": ctrl_harvest['gains']}
figure5c_experimental = {"xlabel": ['Growing expert', 'iGrow'], "ylabel": "euro",
"x": range(len(price['expr'])),
"y": price['expr']}
figure5c_control = {"xlabel": ['Growing expert', 'iGrow'], "ylabel": "euro",
"x": range(len(price['ctrl'])),
"y": price['ctrl']}
save_curve_dir = save_dir + '/curve/'
mkdir(save_curve_dir)
save_curve(figure5a_experimental, save_curve_dir +
'figure5a_experimental.pkl')
save_curve(figure5a_control, save_curve_dir+'figure5a_control.pkl')
save_curve(figure5b_experimental, save_curve_dir +
'figure5b_experimental.pkl')
save_curve(figure5b_control, save_curve_dir+'figure5b_control.pkl')
save_curve(figure5c_experimental, save_curve_dir +
'figure5c_experimental.pkl')
save_curve(figure5c_control, save_curve_dir+'figure5c_control.pkl')
# show
compare_harvest_plot(expr_harvest, ctrl_harvest, price,
startDate=args.startDate,
endDate=args.endDate,
save_fig_dir=args.save_fig_dir)
def get_harvest(args):
harvest_file = os.path.join(args.base_input_path, args.harvest_files)
with open(harvest_file, 'r') as f:
harvest_file_dir = f.readlines()
harvest_file_dir = harvest_file_dir[0].replace("\n", '')
expr_harvest, ctrl_harvest = harvest_analysis(args=args,
harvest_dir=harvest_file_dir)
return expr_harvest, ctrl_harvest
def compare_harvest_plot(expr_harvest, ctrl_harvest, df,
startDate, endDate,
save_fig_dir):
# fig, axes
mpl.rcParams.update(plt_fig_params)
fig = plt.figure(figsize=(13, 6))
layout = (1, 3)
for c in range(layout[1]):
plt.subplot2grid(layout, (0, c), rowspan=1, colspan=1)
props = {0: {"xlabel": "Date",
"ylabel": "Kg/m$^2$",
},
1: {"xlabel": "Date",
"ylabel": "Euro/m$^2$",
},
2: {"ylabel": "Euro/Kg",
},
}
plt_fig_style = {
'Human expert': dict(linestyle='--', lw=2, color=cm.viridis(0.7), label='the control group'),
'EGA': dict(linestyle='-', lw=2, color=cm.viridis(0.3), label='the experimental group'), }
title = ['(a) Crop yield', '(b) Gains', '(c) Fruit Prices']
key = ['production', 'gains', 'price']
yticks_list = [list(range(0, 20, 5)) + [20],
list(range(0, 10, 3))]
for idx, ax in enumerate(fig.axes):
if idx == 2:
sns.boxplot(data=df, notch=0, linewidth=1.5,
order=list(df.columns), dodge=False, width=0.6,
palette=sns.color_palette("viridis_r", 2),
saturation=0.7,
showmeans=True,
meanline=True,
meanprops={'linestyle': '-',
'color': '#393939',
'linewidth': 3},
)
ax.set_xticklabels(labels=['Planting expert', 'iGrow'])
ax.tick_params(axis='x', labelsize=22)
else:
experiment_avg = np.mean(expr_harvest[key[idx]], axis=1)
experiment_std = np.std(expr_harvest[key[idx]], axis=1)
control_avg = np.mean(ctrl_harvest[key[idx]], axis=1)
control_std = np.std(ctrl_harvest[key[idx]], axis=1)
expr_max_id = np.argmax(experiment_avg)
experiment_avg = experiment_avg[:expr_max_id+1]
experiment_std = experiment_std[:expr_max_id+1]
ctrl_max_id = np.argmax(control_avg)
control_avg = control_avg[:ctrl_max_id+1]
control_std = control_std[:ctrl_max_id+1]
expr_iter = np.arange(len(experiment_avg))
ctrl_iter = np.arange(len(control_avg))
ax.plot(expr_iter, experiment_avg, **plt_fig_style['EGA'])
r1 = list(map(lambda x: x[0] - x[1],
zip(experiment_avg, experiment_std)))
r2 = list(map(lambda x: x[0] + x[1],
zip(experiment_avg, experiment_std)))
ax.fill_between(expr_iter, r1, r2, alpha=0.3,
**plt_fig_style['EGA'])
ax.plot(ctrl_iter, control_avg, **plt_fig_style['Human expert'])
r1 = list(map(lambda x: x[0] - x[1],
zip(control_avg, control_std)))
r2 = list(map(lambda x: x[0] + x[1],
zip(control_avg, control_std)))
ax.fill_between(ctrl_iter, r1, r2, alpha=0.3, **
plt_fig_style['Human expert'])
xticks, xlabels = set_day_xtick(num=4,
var_list=list(control_avg[:]),
startDate=startDate,
endDate=endDate)
ax.set_xticks(ticks=xticks)
ax.set_xticklabels(labels=xlabels)
ax.set_yticks(ticks=yticks_list[idx])
ax.tick_params(axis='x', labelsize=20)
ax.grid(linestyle="--", alpha=0.4)
ax.set_title(title[idx], y=-0.38, fontsize=28)
ax.tick_params(axis='y', labelsize=20)
ax.set(**props[idx])
min_xlim, max_xlim = ax.get_xlim()
min_ylim, max_ylim = ax.get_ylim()
xlim_length = abs(max_xlim - min_xlim)
ylim_length = abs(max_ylim - min_ylim)
aspect = xlim_length / ylim_length
ax.set_aspect(aspect)
ax.xaxis.label.set_size(25)
ax.yaxis.label.set_size(25)
plt.tight_layout()
# legend
ax = fig.axes[1]
handles, labels = ax.get_legend_handles_labels()
plt.legend(handles[:2], labels[:2], bbox_to_anchor=(1.1, -0.33), loc='upper right',
ncol=2, framealpha=0, fancybox=False, fontsize=35)
plt.subplots_adjust(bottom=0.43)
mkdir(save_fig_dir)
plt.savefig(save_fig_dir+'liaoyang2_harvest.png', bbox_inches='tight')
plt.close()
def harvest_analysis(args, harvest_dir):
startDate = datetime.datetime.strptime(args.startDate, "%Y-%m-%d")
endDate = datetime.datetime.strptime(args.endDate, "%Y-%m-%d")
days = (endDate-startDate).days + 1
expr_prod = np.zeros((days, len(args.experiment_gh)))
ctrl_prod = np.zeros((days, len(args.control_group)))
expr_gains = np.zeros((days, len(args.experiment_gh)))
ctrl_gains = np.zeros((days, len(args.control_group)))
m2_to_Mu = 667
production = pd.read_csv(harvest_dir + 'production.csv')
production = production.values[:, 1:] / m2_to_Mu
Income = pd.read_csv(harvest_dir + 'Income.csv')
Income = Income.values[:, 1:] / m2_to_Mu * args.rmb2euro
ctrl_prod[-len(production):, :] = np.nancumsum(production[:, :2], axis=0)
expr_prod[-len(production):, :] = np.nancumsum(production[:, 2:], axis=0)
ctrl_gains[-len(Income):, :] = np.nancumsum(Income[:, :2], axis=0)
expr_gains[-len(Income):, :] = np.nancumsum(Income[:, 2:], axis=0)
expr_harvest = {"production": expr_prod,
"gains": expr_gains}
ctrl_harvest = {"production": ctrl_prod,
"gains": ctrl_gains}
return expr_harvest, ctrl_harvest
def scatter_data(df, col, pos_x):
expr = df[col].values
expr_dic = dict(zip(*np.unique(expr, return_counts=True)))
Y = []
Val = []
for k, v in expr_dic.items():
if k != 'nan':
Y.append(float(k))
Val.append(v)
X = [pos_x] * len(Y)
X = np.array(X)
Y = np.array(Y)
Val = np.array(Val)
return X, Y, Val
def get_price(args):
harvest_file = os.path.join(args.base_input_path, args.harvest_files)
with open(harvest_file, 'r') as f:
harvest_file_dir = f.readlines()
harvest_file_dir = harvest_file_dir[0].replace("\n", '')
harvest_price_dir = os.path.join(harvest_file_dir, 'price.csv')
df = pd.read_csv(harvest_price_dir)
ctrl_price = df.values[:, 1:3]
expr_price = df.values[:, 3:]
expr_price = expr_price.astype(np.float32) * args.rmb2euro
ctrl_price = ctrl_price.astype(np.float32) * args.rmb2euro
expr_price[expr_price == 0] = np.nan
ctrl_price[ctrl_price == 0] = np.nan
expr_price = expr_price.flatten()
ctrl_price = ctrl_price.flatten()
price = np.full((expr_price.shape[0], 2), np.nan)
columns = ['ctrl', 'expr']
price[:ctrl_price.shape[0], 0] = ctrl_price
price[:, 1] = expr_price
df = pd.DataFrame(price, columns=columns)
df = df.applymap("{0:.01f}".format)
return df
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--startDate', default="2020-03-15",
help='start date of planting.')
parser.add_argument('--endDate', default="2020-07-13",
help='end date of planting.')
parser.add_argument('--control_group', type=list, default=[1, 2],
help='ids of all green house.')
parser.add_argument('--experiment_gh', type=list, default=[3, 4, 5, 6, 7],
help='ids of all green house.')
parser.add_argument('--rmb2euro', type=float, default=0.1276,
help="rate of rmb to euro")
parser.add_argument("--base_input_path", default="./input", type=str)
parser.add_argument("--base_tmp_folder", default="./result", type=str)
parser.add_argument("--harvest_files", default='harvest.txt', type=str)
parser.add_argument('--save_fig_dir', type=str, default='result/figure5/',
help="save figures directory")
args = parser.parse_args()
Figure5(args)