-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgradutil.py
242 lines (193 loc) · 8.29 KB
/
gradutil.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
import numpy as np
import pandas as pd
import os
import random
from BorealWeights import BorealWeightedProblem
from kmeans import kmeans, randomsample
from pyomo.opt import SolverFactory
def nan_to_bau(frame):
return frame.transpose().fillna(frame.iloc[:, 0]).transpose()
def ideal(dictionary=True):
if dictionary:
return {'revenue': 249966739.00009939,
'deadwood': 218153.21549812937,
'ha': 20225.257707161425,
'carbon': 4449001.4721100219}
else:
return np.array((249966739.00009939,
4449001.4721100219,
218153.21549812937,
20225.257707161425))
def nadir(dictionary=True):
if dictionary:
return {'revenue': 3.09084573e+07,
'carbon': 2.83139915e+06,
'deadwood': 8.02116726e+04,
'ha': 1.19880519e+04}
else:
return np.array((3.09084573e+07,
2.83139915e+06,
8.02116726e+04,
1.19880519e+04))
def init_boreal():
data_dir = os.path.join(os.getcwd(), '../boreal_data')
carbon = pd.read_csv(os.path.join(data_dir, 'Carbon_storage.csv'))
HA = pd.read_csv(os.path.join(data_dir, 'Combined_HA.csv'))
deadwood = pd.read_csv(os.path.join(data_dir, 'Deadwood_volume.csv'))
revenue = pd.read_csv(os.path.join(data_dir, 'Timber_revenues.csv'))
return revenue, carbon, deadwood, HA
def init_norms():
revenue, carbon, deadwood, ha = init_boreal()
n_revenue = nan_to_bau(revenue)
n_carbon = nan_to_bau(carbon)
n_deadwood = nan_to_bau(deadwood)
n_ha = nan_to_bau(ha)
norm_revenue = new_normalize(n_revenue.values)
norm_carbon = new_normalize(n_carbon.values)
norm_deadwood = new_normalize(n_deadwood.values)
norm_ha = new_normalize(n_ha.values)
x = np.concatenate((n_revenue, n_carbon, n_deadwood, n_ha), axis=1)
x_norm = np.concatenate((norm_revenue,
norm_carbon,
norm_deadwood,
norm_ha), axis=1)
x_stack = np.dstack((n_revenue, n_carbon, n_deadwood, n_ha))
x_norm_stack = np.dstack((norm_revenue,
norm_carbon,
norm_deadwood,
norm_ha))
return {'x': x,
'x_norm': x_norm,
'x_stack': x_stack,
'x_norm_stack': x_norm_stack}
def normalize(data):
norm_data = data.copy()
inds = np.where(np.isnan(norm_data))
norm_data[inds] = np.take(np.nanmin(norm_data, axis=0)
- np.nanmax(norm_data, axis=0),
inds[1])
norm_data -= np.min(norm_data, axis=0)
with np.errstate(invalid='ignore'):
normax = np.max(norm_data, axis=0)
norm_data = np.where(normax != 0., norm_data / normax, 0)
return norm_data
def new_normalize(data):
norm_data = data.copy()
norm_data -= np.min(norm_data)
with np.errstate(invalid='ignore'):
normax = np.max(norm_data)
norm_data = np.where(normax != 0., norm_data / normax, 0)
return norm_data
def optimize_all(combined_data, weights, opt):
problem1 = BorealWeightedProblem(combined_data[:, :7], weights)
res1 = opt.solve(problem1.model, False)
problem2 = BorealWeightedProblem(combined_data[:, 7:14], weights)
res2 = opt.solve(problem2.model, False)
problem3 = BorealWeightedProblem(combined_data[:, 14:21], weights)
res3 = opt.solve(problem3.model, False)
problem4 = BorealWeightedProblem(combined_data[:, 21:], weights)
res4 = opt.solve(problem4.model, False)
return (problem1, res1), (problem2, res2),\
(problem3, res3), (problem4, res4)
def res_to_list(model):
resdict = model.x.get_values()
reslist = np.zeros(model.n.value)
for i, j in resdict.keys():
if resdict[i, j] == 1.:
reslist[i] = j
return reslist
def res_value(res):
return res['Problem'][0]['Upper bound']
def cluster_to_value(cluster_data, cluster_list, weights):
''' Returns the optimization values of the cluster, based
on the data of the clusters (cluster_data), the list of
decision variables options (cluster_list) and the proportion
of each cluster (weights)'''
return sum([cluster_data[ind, int(cluster_list[ind])] * weights[ind]
for ind in range(len(cluster_list))])
def clusters_to_origin(data, xtoc, cluster_list):
return sum([sum(data[xtoc == ind][:, int(cluster_list[ind])])
for ind in range(len(cluster_list))])
def model_to_real_values(data, model, xtoc=None):
if xtoc is None:
return sum(values_to_list(model, data))
else:
return clusters_to_origin(data, xtoc, res_to_list(model))
def values_to_list(model, data):
lst = []
for i in model.I:
for j in model.J:
if model.x[i, j].value == 1:
lst.append(data[i, j])
return lst
def cluster(data, nclust, seed, delta=.0001, maxiter=100,
metric='cosine', verbose=1):
random.seed(seed)
np.random.seed(seed)
data[np.isnan(data)] = np.nanmin(data) - np.nanmax(data)
randomcenters = randomsample(data, nclust)
centers, xtoc, dist = kmeans(data,
randomcenters,
delta=delta,
maxiter=maxiter,
metric=metric,
verbose=verbose)
return centers, xtoc, dist
def cNopt(orig_data, clust_data, opt_data, opt, nclust='10', seed=2):
c, xtoc, dist = cluster(clust_data, nclust, seed, verbose=0)
nvar = len(orig_data)
weights = np.array([sum(xtoc == i) for i in range(len(c))])/nvar
opt_x = np.array([opt_data[xtoc == i].mean(axis=0)
for i in range(nclust)])
problem1, problem2, problem3, problem4 = optimize_all(opt_x,
weights,
opt)
res1 = model_to_real_values(orig_data[:, :7], problem1[0].model, xtoc)
res2 = model_to_real_values(orig_data[:, 7:14], problem2[0].model, xtoc)
res3 = model_to_real_values(orig_data[:, 14:21], problem3[0].model, xtoc)
res4 = model_to_real_values(orig_data[:, 21:], problem4[0].model, xtoc)
return res1, res2, res3, res4
def calc_ideal_n_nadir(data, xtoc=None, weights=None):
'''
Calculate ideal and nadir from the data where different
objectives are at the "last" level
'''
solver = SolverFactory('glpk')
problems = []
for i in range(np.shape(data)[-1]):
problems.append(BorealWeightedProblem(data[:, :, i], weights))
for j in range(len(problems)):
solver.solve(problems[j].model)
if xtoc is None:
payoff = [[np.sum(values_to_list(problems[j], data[:, :, i]))
for i in range(np.shape(data)[-1])]
for j in range(len(problems))]
else:
payoff = [[cluster_to_value(data[:, :, i],
res_to_list(problems[j].model),
weights)
for i in range(np.shape(data)[-1])]
for j in range(len(problems))]
ideal = np.max(payoff, axis=0)
nadir = np.min(payoff, axis=0)
return ideal, nadir
if __name__ == '__main__':
seed = 2
nclust = 50
revenue, carbon, deadwood, ha = init_boreal()
x = np.concatenate((revenue, carbon, deadwood, ha), axis=1)
norm_x = np.concatenate((normalize(revenue.values),
normalize(carbon.values),
normalize(deadwood.values),
normalize(ha.values)), axis=1)
no_nan_x = x.copy()
inds = np.where(np.isnan(no_nan_x))
no_nan_x[inds] = np.take(np.nanmin(no_nan_x, axis=0)
- np.nanmax(no_nan_x, axis=0), inds[1])
opt = SolverFactory('glpk')
res1, res2, res3, res4 = cNopt(x, norm_x, no_nan_x, opt, nclust, seed)
print('Results when surrogate mapped to real values:')
print('(i) Harvest revenues {: .0f} M€'.format(res1/1000000))
print('(ii) Carbon storage {: .0f} x 100 MgC'.format(res2/100))
print('(iii) Deadwood index {: .0f} m3'.format(res3))
print('(iv) Combined Habitat {: .0f}'.format(res4))