-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyawOptimizerAfricaOffshore.py
320 lines (266 loc) · 11.6 KB
/
yawOptimizerAfricaOffshore.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 2 09:58:56 2023
@author: Arnav
"""
# Copyright 2022 NREL
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
# See https://floris.readthedocs.io for documentation
# Code modified from FLORIS example #12
from time import perf_counter as timerpc
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from floris.tools import FlorisInterface
from floris.tools.optimization.yaw_optimization.yaw_optimizer_sr import (
YawOptimizationSR,
)
from floris.tools.visualization import visualize_cut_plane
from floris.tools.visualization import plot_rotor_values
def load_floris():
# Load the default example floris object
fi = FlorisInterface("inputs/gch.yaml") # GCH model matched to the default "legacy_gauss" of V2
# Specify wind farm layout and update in the floris object
fi.reinitialize(layout_x=[0, 202.4, 360.11, -858.49, -394.61, -188.66, -1236.23, -665.77, -1576.97, -2392.91, -902.16, 475.38, -2092.11, -459.9, 81.53, -1128.74, 746.44],
layout_y=[0, 1074.93, 206.34, 298.37, 1192.82, 169.0, 1260.54, 1203.08, 1211.56, 1426.76, 1202.12, 1057.17, 1480.97, 135.98, 159.98, 304.9, 1002.35])
fi.reinitialize(wind_directions=[270.0], wind_speeds=[8.0])
horizontal_plane = fi.calculate_horizontal_plane(x_resolution=200, y_resolution=100, height=90.0)
# Create the plots
fig, ax_list = plt.subplots(1, 1, figsize=(10, 8))
visualize_cut_plane(horizontal_plane, ax=None, title="Africa Offshore Wind Turbine Locations")
plt.savefig("outputs/offshoreAfrica/windFarm.pdf")
plt.show()
return fi
def load_windrose():
fn = "inputs/offshoreAfrica/windRose.csv"
df = pd.read_csv(fn)
df = df[(df["ws"] < 22)].reset_index(drop=True) # Reduce size
df["freq_val"] = df["freq_val"] / df["freq_val"].sum() # Normalize wind rose frequencies
return df
def calculate_aep(fi, df_windrose, column_name="farm_power"):
from scipy.interpolate import NearestNDInterpolator
# Define columns
nturbs = len(fi.layout_x)
yaw_cols = ["yaw_{:03d}".format(ti) for ti in range(nturbs)]
if not "yaw_000" in df_windrose.columns:
df_windrose[yaw_cols] = 0.0 # Add zeros
# Derive the wind directions and speeds we need to evaluate in FLORIS
wd_array = np.array(df_windrose["wd"].unique(), dtype=float)
ws_array = np.array(df_windrose["ws"].unique(), dtype=float)
yaw_angles = np.array(df_windrose[yaw_cols], dtype=float)
fi.reinitialize(wind_directions=wd_array, wind_speeds=ws_array)
# Map angles from dataframe onto floris wind direction/speed grid
X, Y = np.meshgrid(wd_array, ws_array, indexing='ij')
interpolant = NearestNDInterpolator(df_windrose[["wd", "ws"]], yaw_angles)
yaw_angles_floris = interpolant(X, Y)
# Calculate FLORIS for every WD and WS combination and get the farm power
fi.calculate_wake(yaw_angles_floris)
farm_power_array = fi.get_farm_power()
# Now map FLORIS solutions to dataframe
interpolant = NearestNDInterpolator(
np.vstack([X.flatten(), Y.flatten()]).T,
farm_power_array.flatten()
)
df_windrose[column_name] = interpolant(df_windrose[["wd", "ws"]]) # Save to dataframe
df_windrose[column_name] = df_windrose[column_name].fillna(0.0) # Replace NaNs with 0.0
# Calculate AEP in GWh
aep = np.dot(df_windrose["freq_val"], df_windrose[column_name]) * 365 * 24 / 1e9
return aep
if __name__ == "__main__":
# Load a dataframe containing the wind rose information
df_windrose = load_windrose()
# Load FLORIS
fi = load_floris()
fi.reinitialize(wind_speeds=6.0)
nturbs = len(fi.layout_x)
# First, get baseline AEP, without wake steering
start_time = timerpc()
print(" ")
print("===========================================================")
print("Calculating baseline annual energy production (AEP)...")
aep_bl = calculate_aep(fi, df_windrose, "farm_power_baseline")
t = timerpc() - start_time
print("Baseline AEP: {:.3f} GWh. Time spent: {:.1f} s.".format(aep_bl, t))
print("===========================================================")
print(" ")
# Now optimize the yaw angles using the Serial Refine method
print("Now starting yaw optimization for the entire wind rose...")
start_time = timerpc()
fi.reinitialize(
wind_directions=np.arange(0.0, 361.0, 1.0),
wind_speeds=[6.0]
)
yaw_opt = YawOptimizationSR(
fi=fi,
minimum_yaw_angle=-30.0, # Allowable yaw angles lower bound
maximum_yaw_angle=30.0, # Allowable yaw angles upper bound
Ny_passes=[5, 4],
exclude_downstream_turbines=True,
exploit_layout_symmetry=True,
)
df_opt = yaw_opt.optimize()
end_time = timerpc()
t_tot = end_time - start_time
t_fi = yaw_opt.time_spent_in_floris
print("Optimization finished in {:.2f} seconds.".format(t_tot))
print(" ")
print(df_opt)
print(" ")
# Now define how the optimal yaw angles for 8 m/s are applied over the other wind speeds
yaw_angles_opt = np.vstack(df_opt["yaw_angles_opt"])
yaw_angles_wind_rose = np.zeros((df_windrose.shape[0], nturbs))
for ii, idx in enumerate(df_windrose.index):
wind_speed = df_windrose.loc[idx, "ws"]
wind_direction = df_windrose.loc[idx, "wd"]
# Interpolate the optimal yaw angles for this wind direction from df_opt
id_opt = df_opt["wind_direction"] == wind_direction
yaw_opt_full = np.array(df_opt.loc[id_opt, "yaw_angles_opt"])[0]
# Now decide what to do for different wind speeds
if wind_speed >= 11.0 or wind_speed <= 3.0:
yaw_opt = np.zeros(nturbs) # do nothing for very low/high speeds
elif wind_speed < 4.0:
yaw_opt = yaw_opt_full * (6.0 - wind_speed) / 2.0 # Linear ramp up
elif wind_speed > 10.0:
yaw_opt = yaw_opt_full * (14.0 - wind_speed) / 2.0 # Linear ramp down
else:
yaw_opt = yaw_opt_full # Apply full offsets between 2.0 and 10.0 m/s
#yaw_opt = yaw_opt_full
# Save to collective array
yaw_angles_wind_rose[ii, :] = yaw_opt
# Add optimal and interpolated angles to the wind rose dataframe
yaw_cols = ["yaw_{:03d}".format(ti) for ti in range(nturbs)]
df_windrose[yaw_cols] = yaw_angles_wind_rose
# Now get AEP with optimized yaw angles
start_time = timerpc()
print("==================================================================")
print("Calculating annual energy production (AEP) with wake steering...")
aep_opt = calculate_aep(fi, df_windrose, "farm_power_opt")
aep_uplift = 100.0 * (aep_opt / aep_bl - 1)
t = timerpc() - start_time
print("Optimal AEP: {:.3f} GWh. Time spent: {:.1f} s.".format(aep_opt, t))
print("Relative AEP uplift by wake steering: {:.3f} %.".format(aep_uplift))
print("==================================================================")
print(" ")
# Now calculate helpful variables and then plot wind rose information
df = df_windrose.copy()
df["farm_power_relative"] = (
df["farm_power_opt"] / df["farm_power_baseline"]
)
df["farm_energy_baseline"] = df["freq_val"] * df["farm_power_baseline"]
df["farm_energy_opt"] = df["freq_val"] * df["farm_power_opt"]
df["energy_uplift"] = df["farm_energy_opt"] - df["farm_energy_baseline"]
df["rel_energy_uplift"] = df["energy_uplift"] / df["energy_uplift"].sum()
# Plot power and AEP uplift across wind direction
fig, ax = plt.subplots(nrows=3, sharex=True)
df_5ms = df[df["ws"] == 5.0].reset_index(drop=True)
pow_uplift = 100 * (
df_5ms["farm_power_opt"] / df_5ms["farm_power_baseline"] - 1
)
ax[0].bar(
x=df_5ms["wd"],
height=pow_uplift,
color="darkgray",
edgecolor="black",
width=4.5,
)
ax[0].set_ylabel("Power uplift \n at 5 m/s (%)", fontsize="medium")
ax[0].grid(True)
dist = df.groupby("wd").sum().reset_index()
ax[1].bar(
x=dist["wd"],
height=100 * dist["rel_energy_uplift"],
color="darkgray",
edgecolor="black",
width=4.5,
)
ax[1].set_ylabel("Contribution to \n AEP uplift (%)", fontsize="medium")
ax[1].grid(True)
ax[2].bar(
x=dist["wd"],
height=dist["freq_val"],
color="darkgray",
edgecolor="black",
width=4.5,
)
ax[2].set_xlabel("Wind direction (deg)")
ax[2].set_ylabel("Frequency", fontsize="medium")
ax[2].grid(True)
plt.tight_layout()
plt.savefig("outputs/offshoreAfrica/windDirectionAEPuplift.pdf")
# Plot power and AEP uplift across wind direction
fig, ax = plt.subplots(nrows=3, sharex=True)
df_avg = df.groupby("ws").mean().reset_index(drop=False)
mean_power_uplift = 100.0 * (df_avg["farm_power_relative"] - 1.0)
ax[0].bar(
x=df_avg["ws"],
height=mean_power_uplift,
color="darkgray",
edgecolor="black",
width=0.95,
)
ax[0].set_ylabel("Mean power \n uplift (%)", fontsize="medium")
ax[0].grid(True)
dist = df.groupby("ws").sum().reset_index()
ax[1].bar(
x=dist["ws"],
height=100 * dist["rel_energy_uplift"],
color="darkgray",
edgecolor="black",
width=0.95,
)
ax[1].set_ylabel("Contribution to \n AEP uplift (%)", fontsize="medium")
ax[1].grid(True)
ax[2].bar(
x=dist["ws"],
height=dist["freq_val"],
color="darkgray",
edgecolor="black",
width=0.95,
)
ax[2].set_xlabel("Wind speed (m/s)")
ax[2].set_ylabel("Frequency", fontsize="medium")
ax[2].grid(True)
plt.tight_layout()
plt.savefig("outputs/offshoreAfrica/windSpeedAEPuplift.pdf")
# Now plot yaw angle distributions over wind direction up to first three turbines
for ti in range(nturbs):
fig, ax = plt.subplots(figsize=(6, 3.5))
ax.plot(
df_opt["wind_direction"],
yaw_angles_opt[:, ti],
"-o",
color="maroon",
markersize=3,
label="4 m/s < Wind Speed < 10 m/s",
)
ax.plot(
df_opt["wind_direction"],
0.5 * yaw_angles_opt[:, ti],
"-v",
color="dodgerblue",
markersize=3,
label="3 m/s < Wind Speed < 4 m/s $\\bf{and}$ 10 m/s < Wind Speed < 11 m/s",
)
ax.plot(
df_opt["wind_direction"],
0.0 * yaw_angles_opt[:, ti],
"-o",
color="grey",
markersize=3,
label="Wind Speed < 3 m/s $\\bf{and}$ Wind Speed > 11 m/s",
)
ax.set_ylabel("Assigned yaw offsets (deg)")
ax.set_xlabel("Wind direction (deg)")
ax.set_title("Turbine {:d}".format(ti))
ax.grid(True)
ax.legend(fontsize="x-small")
plt.tight_layout()
plt.savefig("outputs/offshoreAfrica/turbine{:d}.pdf".format(ti))
plt.show()