Newer
Older
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Counts the number of oil particle trajectories intersecting the cells of a regular grid and computes the oil spill risk, defined as the probability of being impacted by an oil spill
Author: Thomas Anselain, Earth and Life Institute, UCLouvain, Belgium
Last modified: 4 April 2022
"""
#%% Import packages and set up
import numpy as np
from math import *
import matplotlib.pyplot as plt
from matplotlib import colors
import matplotlib
from netCDF4 import Dataset
import os
from osgeo import osr, gdal
import netCDF4 as nc
import geopandas as gpd
from shapely.geometry import Polygon
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
basedir = "/export/miro/students/tanselain/OpenOil/"
#%% Define colormap
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
from matplotlib import colors
new_cmap = colors.LinearSegmentedColormap.from_list(
'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
cmap(np.linspace(minval, maxval, n)))
return new_cmap
#%% Define main function
def plot_proba_map(list_source, list_year, list_mois, resolution, vmin, vmax, outfile, show=False) :
# Concatenate data for the month
lats = np.empty((0,481))
lons = np.empty(lats.shape)
for mois in list_mois:
print('mois is', mois)
for source in list_source :
print('source is', source)
for year in list_year :
print('year = ', year)
for date in range(1,32) :
print('date =', date )
path = basedir + f"Output_backward/{year}/{source}/{mois}/out_{mois}_{date}.nc"
if not os.path.isfile(path):
continue
with Dataset(path, "r") as ds:
lat_tmp = np.ma.filled(np.ma.array(ds.variables["lat"][:]), np.nan)
lon_tmp = np.ma.filled(np.ma.array(ds.variables["lon"][:]), np.nan)
ntraj, ntime = lat_tmp.shape
#deals with the case when ntime < 121
lon = np.full((ntraj,481), np.nan)
lat = np.full((ntraj,481), np.nan)
lon[:,:ntime] = lon_tmp[:]
lat[:,:ntime] = lat_tmp[:]
lats = np.row_stack([lats, lat])
lons = np.row_stack([lons, lon])
del lon_tmp, lat_tmp, lon, lat
# Mask corresponds to nans
masked = np.isnan(lats)
#%% Building grid and count trajectory that passed throught each mesh
# Bounding box of particles coordinates
def myfloor(x, prec, base):
return round(base * floor(float(x)/base),prec)
def myceil(x, prec, base):
return round(base * ceil(float(x)/base),prec)
minlon, maxlon = lons[~masked].min()-resolution, lons[~masked].max()+resolution
minlat, maxlat = lats[~masked].min()-resolution, lats[~masked].max()+resolution
minlon, maxlon = myfloor(minlon, prec=2, base = resolution), myceil(maxlon, prec=2, base = resolution)
minlat, maxlat = myfloor(minlat, prec=2, base = resolution), myceil(maxlat, prec=2, base = resolution) #set precision 2 to have always same pixel in the mesh with the 0.01 resolution
# Build grid to count particles
longr = np.arange(minlon, maxlon+resolution, resolution)
latgr = np.arange(minlat, maxlat+resolution, resolution)
ox, oy = longr[0], latgr[0]
dx, dy = longr[1]-longr[0], latgr[1]-latgr[0]
mlongr, mlatgr = np.meshgrid(longr, latgr)
cntr = np.zeros((mlongr.shape[0]-1, mlongr.shape[1]-1))
cntrx = []; cntry = []
for i in range(lons.shape[0]):
lon, lat = lons[i,~masked[i]], lats[i,~masked[i]]
rx, ry = lon - ox, lat - oy
ix = (rx / resolution).astype(int)
iy = (ry / resolution).astype(int)
indx = np.unique(np.column_stack([iy,ix]), axis=0)
cntry.extend(indx[:,0].tolist())
cntrx.extend(indx[:,1].tolist())
np.add.at(cntr, (cntry,cntrx), np.ones(len(cntrx)))
# Normalization by total number of trajectories
cntr /= lons.shape[0]
print(lons.shape[0])
print(lons.shape)
sumdensity = round(cntr.sum(),1)
cntr[cntr <= 0] = np.nan
#%% Plot map
# Main axis
fig = plt.figure(figsize = (12,12))
ax = fig.add_subplot(111)
# Second axis to draw cbbox
fc = colors.to_rgba('white')
ec = colors.to_rgba('gray')
fc = fc[:-1] + (0.7,)
cbbox = inset_axes(ax, '15%', '35%',loc=1, bbox_to_anchor=(0, 0, 0.98, 0.98), bbox_transform=ax.transAxes, borderpad=0)
cbbox.spines['bottom'].set_color(ec)
cbbox.spines['top'].set_color(ec)
cbbox.spines['right'].set_color(ec)
cbbox.spines['left'].set_color(ec)
cbbox.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')
cbbox.set_facecolor(fc)
# Subaxis to add colorbar to cbbox
subax = inset_axes(cbbox,
width="35%", # width = 30% of parent_bbox
height="82%", # height : 1 inch
loc = 6,
bbox_to_anchor=(0.1,0,1,0.9),
bbox_transform=cbbox.transAxes,
borderpad=0,
)
# Set and identify sensitive areas + additionnal texts
list_source2 = []
for j in range(len(list_source)) :
src = list_source[j].split("_")
for i in range(len(src)):
if src[i] == "al": continue
if src[i] == "port": continue
src[i] = src[i][0].upper() + src[i][1:]
source2 = " ".join(src)
list_source2.append(source2)
mois = mois[0].upper() + mois[1:]
#ax.text(50.05, 24.1, f'{mois}', fontsize=18, horizontalalignment = 'left', verticalalignment = 'center', zorder=6)
#ax.text(50.05, 24.25, f'Total risk: {sumdensity}' , fontsize=20, horizontalalignment = 'left', verticalalignment = 'center', zorder=6)
ax.scatter(51.55, 25.9464, s=50, c='#1f77b4' ,zorder=5)
ax.text(51.355, 25.89, list_source2[0], color = 'k', fontsize=12, fontweight='bold',horizontalalignment = 'center', verticalalignment = 'center',zorder=5)
ax.scatter(51.6269, 25.2061, s=50, c='#1f77b4' ,zorder=5)
ax.text(51.385, 25.2, list_source2[1], color = 'k', fontsize=12, fontweight='bold' , horizontalalignment = 'center', verticalalignment = 'center',zorder=5)
ax.scatter(51.633, 25.1135, s=50, c='#1f77b4' ,zorder=5)
ax.text(51.355, 25.1135, list_source2[2], color = 'k', fontsize=12, fontweight='bold', horizontalalignment = 'center', verticalalignment = 'center',zorder=5)
ax.scatter(51.6682, 25.9204, s=100, color ='limegreen', marker = '*' ,zorder=5)
# Put land, border and eez in background
bgdir = basedir + "Indicators/Background_map/"
gpd_landp = gpd.read_file(bgdir+"PG_layer_poly_new/PG_layer_poly_new.shp")
gpd_bordl = gpd.read_file(bgdir+"natural_earth/ne_10m_admin_0_boundary_lines_land.shp")
gpd_eezl = gpd.read_file(bgdir+"qatar_eez/qatar_eez_line.shp")
gpd_landp.plot(ax=ax, linewidth=0.5, edgecolors="k", color='lightgray',zorder=4)
gpd_bordl.plot(ax=ax, linewidth=0.5, linestyle='-', color="k", zorder=4)
gpd_eezl.plot(ax=ax, linewidth=2, color="darkgreen",zorder=4)
# Plot mesh
cmap = plt.get_cmap('YlOrRd')
new_cmap = truncate_colormap(cmap, 0.2, 1) #set colormap
vmax2 = np.nanmax(cntr)
print(vmax2)
vmax2 = round(vmax2,2)
bounds = np.array([0, 0.001, 0.005, 0.01, 0.02, vmax2]) #0.0001, 0.001, 0.005, 0.01, 0.02, vmax2
stretched_bounds = np.interp(np.linspace(0, 1, 257), np.linspace(0, 1, len(bounds)), bounds)
norm = matplotlib.colors.BoundaryNorm(stretched_bounds, ncolors=256)
pcm = ax.pcolormesh(longr, latgr, cntr, cmap=new_cmap, norm=norm, vmin=0.0001, vmax=vmax2,zorder=3)
# Set up axis
ax.set_xlim(50, 53.2)
ax.set_ylim(24, 27.5)
yticks = np.arange(24, 28, .5)
ax.set_yticks(yticks)
ax.set_yticklabels([f"{y}°N" for y in yticks])
ax.tick_params(labelleft=True, labelbottom = True)
xticks = np.arange(50,53.5,0.5)
ax.set_xticks(xticks)
ax.set_xticklabels([f"{x}°E" for x in xticks])
# Set colorbar
#tick_step = vmax*0.2
#cticks = np.arange(tick_step, vmax+tick_step, tick_step)
#cticks= np.insert(cticks, 0, 0) #add vmin to ticks
cticks = np.array([0, 0.001, 0.005, 0.01, 0.02, vmax2])
cbar = fig.colorbar(pcm, cax= subax, orientation='vertical', ticks=[cticks], pad=.05, aspect=30, shrink=.7, fraction=0.04)
ctickslab1 = cticks*100
ctickslab= np.round(ctickslab1,2)
cbar.ax.set_yticklabels([str(int(ctickslab1[0]))+'%', str(float(ctickslab[1]))+'%', str(float(ctickslab[2]))+'%', str(float(ctickslab[3]))+'%', str(float(ctickslab[4]))+'%', '>'+str(int(ctickslab1[5]))+'%'])
cbar.set_label(label = 'Probability', labelpad=-32, y=1.15, rotation=0, fontsize = 14)
ax.set_aspect("equal")
# Final save
plt.savefig(outfile, dpi=300, bbox_inches="tight")
if show:
plt.show()
plt.close(fig)
#%% Conversion to geodataframe and save in shp
print("Building geodataframe...")
data = []
for i in range(cntr.shape[0]):
for j in range(cntr.shape[1]):
X = longr[[j, j, j+1, j+1]]
Y = latgr[[i, i+1, i+1, i]]
data.append( (cntr[i,j], Polygon(np.column_stack([X,Y]))) )
df = gpd.GeoDataFrame(data, columns=["proba", "geometry"], crs="EPSG:4326")
name, ext = os.path.splitext(outfile)
df.to_file(name)
#%% Beginning of loops
# Give combinations station/month/year assessed
list_source = ['ras_laffan', 'abu_fontas', 'umm_al_houl', 'ras_laffan_port']
list_year = ['2016', '2017', '2018', '2019', '2020']
list_mois = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
#list_mois = ['march']
# Start loops for main function
outdir = basedir + f"Indicators/Proba_map/all_qatar/"
fname = outdir + f"proba_risk_map_all_qatar.png"
plot_proba_map(list_source, list_year, list_mois, 0.01, 0.0003, 0.03, fname, show=False)