/
eopatch_visualization.py
348 lines (300 loc) · 13.9 KB
/
eopatch_visualization.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
"""
This module implements visualizations for EOPatch
Credits:
Copyright (c) 2017-2019 Matej Aleksandrov, Matej Batič, Andrej Burja, Eva Erzin (Sinergise)
Copyright (c) 2017-2019 Grega Milčinski, Matic Lubej, Devis Peresutti, Jernej Puc, Tomislav Slijepčević (Sinergise)
Copyright (c) 2017-2019 Blaž Sovdat, Jovan Višnjić, Anže Zupanc, Lojze Žust (Sinergise)
This source code is licensed under the MIT license found in the LICENSE
file in the root directory of this source tree.
"""
import numpy as np
import pandas as pd
import geopandas as gpd
import xarray as xr
import holoviews as hv
import geoviews as gv
import hvplot # pylint: disable=unused-import
import hvplot.xarray # pylint: disable=unused-import
import hvplot.pandas # pylint: disable=unused-import
from cartopy import crs as ccrs
from shapely.geometry import Polygon
from sentinelhub import CRS
from eolearn.core import FeatureType, FeatureTypeSet, FeatureParser
from .xarray_utils import array_to_dataframe, new_coordinates, string_to_variable
PLOT_WIDTH = 800
PLOT_HEIGHT = 500
class EOPatchVisualization:
"""
Plot class for making visulizations.
:param eopatch: eopatch
:type eopatch: EOPatch
:param feature: feature of eopatch
:type feature: (FeatureType, str)
:param rgb: bands for creating RGB image
:type rgb: [int, int, int]
:param rgb_factor: multiplication factor for constructing rgb image
:type rgb_factor: float
:param vdims: value dimensions for plotting geopandas.GeoDataFrame
:type vdims: str
:param timestamp_column: geopandas.GeoDataFrame columns with timestamps
:type timestamp_column: str
:param geometry_column: geopandas.GeoDataFrame columns with geometry
:type geometry_column: geometry
:param pixel: wheather plot data for each pixel (line), for FeatureType.DATA and FeatureType.MASK
:type pixel: bool
:param mask: name of the FeatureType.MASK to apply to data
:type mask: str
"""
def __init__(self, eopatch, feature, rgb=None, rgb_factor=3.5, vdims=None,
timestamp_column='TIMESTAMP', geometry_column='geometry', pixel=False, mask=None):
self.eopatch = eopatch
self.feature = feature
self.rgb = rgb
self.rgb_factor = rgb_factor
self.vdims = vdims
self.timestamp_column = timestamp_column
self.geometry_column = geometry_column
self.pixel = pixel
self.mask = mask
def plot(self):
""" Plots eopatch
:return: plot
:rtype: holovies/bokeh
"""
features = list(FeatureParser(self.feature))
feature_type, feature_name = features[0]
if self.pixel and feature_type in FeatureTypeSet.RASTER_TYPES_4D:
vis = self.plot_pixel(feature_type, feature_name)
elif feature_type in (FeatureType.MASK, *FeatureTypeSet.RASTER_TYPES_3D):
vis = self.plot_raster(feature_type, feature_name)
elif feature_type is FeatureType.DATA:
vis = self.plot_data(feature_name)
elif feature_type is FeatureType.VECTOR:
vis = self.plot_vector(feature_name)
elif feature_type is FeatureType.VECTOR_TIMELESS:
vis = self.plot_vector_timeless(feature_name)
else: # elif feature_type in (FeatureType.SCALAR, FeatureType.LABEL):
vis = self.plot_scalar_label(feature_type, feature_name)
return vis.opts(plot=dict(width=PLOT_WIDTH, height=PLOT_HEIGHT))
def plot_data(self, feature_name):
""" Plots the FeatureType.DATA of eopatch.
:param feature_name: name of the eopatch feature
:type feature_name: str
:return: visualization
:rtype: holoview/geoviews/bokeh
"""
crs = self.eopatch.bbox.crs
crs = CRS.POP_WEB if crs is CRS.WGS84 else crs
data_da = array_to_dataframe(self.eopatch, (FeatureType.DATA, feature_name), crs=crs)
if self.mask:
data_da = self.mask_data(data_da)
timestamps = self.eopatch.timestamp
crs = self.eopatch.bbox.crs
if not self.rgb:
return data_da.hvplot(x='x', y='y', crs=ccrs.epsg(int(crs.value)))
data_rgb = self.eopatch_da_to_rgb(data_da, feature_name, crs)
rgb_dict = {timestamp_: self.plot_rgb_one(data_rgb, timestamp_) for timestamp_ in timestamps}
return hv.HoloMap(rgb_dict, kdims=['time'])
@staticmethod
def plot_rgb_one(eopatch_da, timestamp): # OK
""" Returns visualization for one timestamp for FeatureType.DATA
:param eopatch_da: eopatch converted to xarray DataArray
:type eopatch_da: xarray DataArray
:param timestamp: timestamp to make plot for
:type timestamp: datetime
:return: visualization
:rtype: holoviews/geoviews/bokeh
"""
return eopatch_da.sel(time=timestamp).drop('time').hvplot(x='x', y='y')
def plot_raster(self, feature_type, feature_name):
""" Makes visualization for raster data (except for FeatureType.DATA)
:param feature_type: type of eopatch feature
:type feature_type: FeatureType
:param feature_name: name of eopatch feature
:type feature_name: str
:return: visualization
:rtype: holoviews/geoviews/bokeh
"""
crs = self.eopatch.bbox.crs
crs = CRS.POP_WEB if crs is CRS.WGS84 else crs
data_da = array_to_dataframe(self.eopatch, (feature_type, feature_name), crs=crs)
data_min = data_da.values.min()
data_max = data_da.values.max()
data_levels = len(np.unique(data_da))
data_levels = 11 if data_levels > 11 else data_levels
data_da = data_da.where(data_da > 0).fillna(-1)
vis = data_da.hvplot(x='x', y='y',
crs=ccrs.epsg(int(crs.value))).opts(clim=(data_min, data_max),
clipping_colors={'min': 'transparent'},
color_levels=data_levels)
return vis
def plot_vector(self, feature_name):
""" Visualizaton for vector (FeatureType.VECTOR) data
:param feature_name: name of eopatch feature
:type feature_name: str
:return: visualization
:rtype: holoviews/geoviews/bokeh
"""
crs = self.eopatch.bbox.crs
timestamps = self.eopatch.timestamp
data_gpd = self.fill_vector(FeatureType.VECTOR, feature_name)
if crs is CRS.WGS84:
crs = CRS.POP_WEB
data_gpd = data_gpd.to_crs({'init': 'epsg:{}'.format(crs.value)})
shapes_dict = {timestamp_: self.plot_shapes_one(data_gpd, timestamp_, crs)
for timestamp_ in timestamps}
return hv.HoloMap(shapes_dict, kdims=['time'])
def fill_vector(self, feature_type, feature_name):
""" Adds timestamps from eopatch to GeoDataFrame.
:param feature_type: type of eopatch feature
:type feature_type: FeatureType
:param feature_name: name of eopatch feature
:type feature_name: str
:return: GeoDataFrame with added data
:rtype: geopandas.GeoDataFrame
"""
vector = self.eopatch[feature_type][feature_name].copy()
vector['valid'] = True
eopatch_timestamps = self.eopatch.timestamp
vector_timestamps = set(vector[self.timestamp_column])
blank_timestamps = [timestamp for timestamp in eopatch_timestamps if timestamp not in vector_timestamps]
dummy_geometry = self.create_dummy_polygon(0.0000001)
temp_df = self.create_dummy_dataframe(vector,
blank_timestamps=blank_timestamps,
dummy_geometry=dummy_geometry)
final_vector = gpd.GeoDataFrame(pd.concat((vector, temp_df), ignore_index=True),
crs=vector.crs)
return final_vector
def create_dummy_dataframe(self, geodataframe, blank_timestamps, dummy_geometry,
fill_str='', fill_numeric=1):
""" Creates geopadnas GeoDataFrame to fill with dummy data (for visualization)
:param geodataframe: dataframe to append rows to
:type geodataframe: geopandas.GeoDataFrame
:param blank_timestamps: timestamps for constructing dataframe
:type blank_timestamps: list of timestamps
:param dummy_geometry: geometry to plot when there is no data
:type dummy_geometry: shapely.geometry.Polygon
:param fill_str: insert when there is no value in str column
:type fill_str: str
:param fill_numeric: insert when
:type fill_numeric: float
:return: dataframe with dummy data
:rtype: geopandas.GeoDataFrame
"""
dataframe = pd.DataFrame(data=blank_timestamps, columns=[self.timestamp_column])
for column in geodataframe.columns:
if column == self.timestamp_column:
continue
elif column == self.geometry_column:
dataframe[column] = dummy_geometry
elif column == 'valid':
dataframe[column] = False
elif geodataframe[column].dtype in (int, float):
dataframe[column] = fill_numeric
else:
dataframe[column] = fill_str
return dataframe
def create_dummy_polygon(self, addition_factor):
""" Creates geometry/polygon to plot if there is no data (at timestamp)
:param addition_factor: size of the 'blank polygon'
:type addition_factor: float
:return: polygon
:rtype: shapely.geometry.Polygon
"""
x_blank, y_blank = self.eopatch.bbox.lower_left
dummy_geometry = Polygon([[x_blank, y_blank],
[x_blank + addition_factor, y_blank],
[x_blank + addition_factor, y_blank + addition_factor],
[x_blank, y_blank + addition_factor]])
return dummy_geometry
def plot_scalar_label(self, feature_type, feature_name):
""" Line plot for FeatureType.SCALAR, FeatureType.LABEL
:param feature_type: type of eopatch feature
:type feature_type: FeatureType
:param feature_name: name of eopatch feature
:type feature_name: str
:return: visualization
:rtype: holoviews/geoviews/bokeh
"""
data_da = array_to_dataframe(self.eopatch, (feature_type, feature_name))
if data_da.dtype == np.bool:
data_da = data_da.astype(np.int8)
return data_da.hvplot()
def plot_shapes_one(self, data_gpd, timestamp, crs):
""" Plots shapes for one timestamp from geopandas GeoDataFrame
:param data_gpd: data to plot
:type data_gpd: geopandas.GeoDataFrame
:param timestamp: timestamp to plot data for
:type timestamp: datetime
:param crs: in which crs is the data to plot
:type crs: sentinelhub.crs
:return: visualization
:rtype: geoviews
"""
out = data_gpd.loc[data_gpd[self.timestamp_column] == timestamp]
return gv.Polygons(out, crs=ccrs.epsg(int(crs.value)))
def plot_vector_timeless(self, feature_name):
""" Plot FeatureType.VECTOR_TIMELESS data
:param feature_name: name of the eopatch featrue
:type feature_name: str
:return: visalization
:rtype: geoviews
"""
crs = self.eopatch.bbox.crs
if crs is CRS.WGS84:
crs = CRS.POP_WEB
data_gpd = self.eopatch[FeatureType.VECTOR_TIMELESS][feature_name].to_crs(
{'init': 'epsg:{}'.format(crs.value)})
else:
data_gpd = self.eopatch[FeatureType.VECTOR_TIMELESS][feature_name]
return gv.Polygons(data_gpd, crs=ccrs.epsg(int(crs.value)), vdims=self.vdims)
def eopatch_da_to_rgb(self, eopatch_da, feature_name, crs):
""" Creates new xarray DataArray (from old one) to plot rgb image with hv.Holomap
:param eopatch_da: eopatch DataArray
:type eopatch_da: DataArray
:param feature_name: name of the feature to plot
:type feature_name: str
:param crs: in which crs are the data
:type crs: sentinelhub.constants.crs
:return: eopatch DataArray with proper coordinates, dimensions, crs
:rtype: xarray.DataArray
"""
timestamps = eopatch_da.coords['time'].values
bands = eopatch_da[..., self.rgb] * self.rgb_factor
bands = bands.rename({string_to_variable(feature_name, '_dim'): 'band'}).transpose('time', 'band', 'y', 'x')
x_values, y_values = new_coordinates(eopatch_da, crs, CRS.POP_WEB)
eopatch_rgb = xr.DataArray(data=np.clip(bands.data, 0, 1),
coords={'time': timestamps,
'band': self.rgb,
'y': np.flip(y_values),
'x': x_values},
dims=('time', 'band', 'y', 'x'))
return eopatch_rgb
def plot_pixel(self, feature_type, feature_name):
"""
Plots one pixel through time
:return: visualization
:rtype: holoviews
"""
data_da = array_to_dataframe(self.eopatch, (feature_type, feature_name))
if self.mask:
data_da = self.mask_data(data_da)
if data_da.dtype == np.bool:
data_da = data_da.astype(np.int8)
return data_da.hvplot(x='time')
def mask_data(self, data_da):
"""
Creates a copy of array and insert 0 where data is masked.
:param data_da: dataarray
:type data_da: xarray.DataArray
:return: dataaray
:rtype: xarray.DataArray
"""
mask = self.eopatch[FeatureType.MASK][self.mask]
if len(data_da.values.shape) == 4:
mask = np.repeat(mask, data_da.values.shape[-1], -1)
else:
mask = np.squeeze(mask, axis=-1)
data_da = data_da.copy()
data_da.values[~mask] = 0
return data_da