forked from earthdaily/GeosysPy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotebook_utils.py
209 lines (188 loc) · 8.65 KB
/
notebook_utils.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
import boto3
import os
from urllib.parse import urlparse
from io import StringIO
import glob
import json
import pandas as pd
import matplotlib.pyplot as plt
def read_mrts_data(str_path):
""" Read MRTS outputs dowloaded from AWS
return dict containing path on files and dict containing data
Args:
str_path (_string_): path containing MRTS files
Returns:
data_files: data_files = {
"metadata": metadata_file path,
"raw_df" : raw data path,
"df" : df denoised path,
"timeserie" : ts path
}
data_files: dict_data = {
"metadata" : metadata in json,
"raw_df" : dataframe containing raw data,
"df" : dataframe containing data denoised if no smmother,
"ts" : dataframe containing timeserie denoised if smmother
}
"""
path_data = os.path.join(str_path.split('/')[-3],str_path.split('/')[-2],str_path.split('/')[-1])
metadata_file = glob.glob(os.path.join(path_data,"*.json"))[0]
with open(metadata_file, 'r') as f:
metadata = json.load(f)
str_index = metadata['parameters']['index']
str_func = metadata['parameters']['aggregation']
str_smoother = metadata['parameters']['smoother']
raw_data = metadata['parameters']['raw_data']
data_files = {
"metadata": metadata_file,
"raw_df" : glob.glob(os.path.join(path_data,"MRTS-" + str_index + str_func + "-Raw-2*.csv"))[0] if raw_data else None,
"df" : glob.glob(os.path.join(path_data,"MRTS-" + str_index + str_func + "-2*.csv"))[0] if str_smoother == "false" else None,
"timeserie" : glob.glob(os.path.join(path_data,"MRTS-" + str_index + str_func + "-2*.csv"))[0] if str_smoother != "false" else None
}
dict_data = {
"metadata" : metadata,
"raw_df" : pd.read_csv(data_files['raw_df'], sep=",") if raw_data else None,
"df" : pd.read_csv(data_files['df'], sep=",") if str_smoother == "false" else None,
"ts" : pd.read_csv(data_files['timeserie'], sep=",") if str_smoother != "false" else None
}
return data_files, dict_data
def plot_mrts_dict(dict_data):
""" Plot MRTS outputs from the dict generated by the function read_mrts_data_from_awsS3
or the function read_mrts_data
Args:
dict_data (_dictionnaire_): dict_data = {
"metadata" : metadata in json,
"raw_df" : dataframe containing raw data,
"df" : dataframe containing data denoised if no smmother,
"ts" : dataframe containing timeserie denoised if smmother
}
"""
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10,6))
metadata = dict_data['metadata']
index = metadata['parameters']['index']
if index != 'reflectances':
if dict_data['raw_df'] is not None:
raw_df = dict_data['raw_df']
raw_df['date'] = pd.to_datetime(raw_df['date'], format='%Y-%m-%d')
raw_df = raw_df.set_index('date')
plt.plot(raw_df[index] ,'.', markersize=12, label=index)
plt.plot(raw_df[index].loc[raw_df['denoised'] == True] ,'x', color='r', markersize=12, label='Denoised')
if dict_data['df'] is not None:
df = dict_data['df']
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
df = df.set_index('date')
plt.plot(df['vegetation_index'] ,'.', markersize=12, label=index)
if dict_data['ts'] is not None:
df_smooth = dict_data['ts']
df_smooth['date'] = pd.to_datetime(df_smooth['date'], format='%Y-%m-%d')
df_smooth = df_smooth.set_index('date')
plt.plot(df_smooth, linewidth=2, label='Smooth ' + index)
else:
if dict_data['raw_df'] is not None:
raw_df = dict_data['raw_df']
raw_df['date'] = pd.to_datetime(raw_df['date'], format='%Y-%m-%d')
raw_df = raw_df.set_index('date')
plt.plot(raw_df['nir'] ,'.', markersize=12, label='nir')
plt.plot(raw_df['nir'].loc[raw_df['denoised'] == True] ,'x', color='r', markersize=12, label='Denoised')
plt.plot(raw_df['red'] ,'.', markersize=12, label='red')
plt.plot(raw_df['red'].loc[raw_df['denoised'] == True] ,'x', color='r', markersize=12)
plt.plot(raw_df['green'] ,'.', markersize=12, label='green')
plt.plot(raw_df['green'].loc[raw_df['denoised'] == True] ,'x', color='r', markersize=12)
plt.plot(raw_df['blue'] ,'.', markersize=12, label='blue')
plt.plot(raw_df['blue'].loc[raw_df['denoised'] == True] ,'x', color='r', markersize=12)
if dict_data['df'] is not None:
df = dict_data['df']
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
df = df.set_index('date')
plt.plot(df['nir'] ,'.', markersize=12, label=index)
plt.plot(df['red'] ,'.', markersize=12, label=index)
plt.plot(df['green'] ,'.', markersize=12, label=index)
plt.plot(df['blue'] ,'.', markersize=12, label=index)
if dict_data['ts'] is not None:
df_smooth = dict_data['ts']
df_smooth['date'] = pd.to_datetime(df_smooth['date'], format='%Y-%m-%d')
df_smooth = df_smooth.set_index('date')
plt.plot(df_smooth['nir'], linewidth=2, label='Smooth ' + 'nir')
plt.plot(df_smooth['red'], linewidth=2, label='Smooth ' + 'red')
plt.plot(df_smooth['green'], linewidth=2, label='Smooth ' + 'green')
plt.plot(df_smooth['blue'], linewidth=2, label='Smooth ' + 'blue')
if index == 'ndvi':
plt.ylim((0,1))
elif index == 'evi':
plt.ylim((0,1))
elif index == 'cvin':
plt.ylim((0,1))
elif index == 'gndvi':
plt.ylim((0,1))
elif index == 'ndwi':
plt.ylim((0,1))
elif index == 'reflectances':
plt.ylim((0,1))
elif index == 's2rep':
plt.ylim((710,730))
ax.set_ylabel(index)
plt.legend()
plt.grid(True)
plt.show()
def read_mrts_from_awsS3(str_s3_path):
""" Read MRTS outputs direclty from S3 AWS
return dict containing path on files and dict containing data
Args:
str_s3_path (_string_): URI S3 (aws)
Returns:
data_files: dict_data = {
"metadata" : metadata in json,
"raw_df" : dataframe containing raw data,
"df" : dataframe containing data denoised if no smmother,
"ts" : dataframe containing timeserie denoised if smmother
}
"""
s3 = boto3.resource('s3')
parsed_url = urlparse(str_s3_path)
bucket_name = parsed_url.netloc
directory_name = parsed_url.path.lstrip('/')
bucket = s3.Bucket(bucket_name)
s3 = boto3.client('s3')
for obj in bucket.objects.filter(Prefix=directory_name):
response = s3.get_object(Bucket=bucket_name, Key=obj.key)
file_content = response['Body'].read().decode('utf-8')
if obj.key.split('/')[-1].split('.')[-1] == 'json' :
# Utilisez la méthode `get_object` pour récupérer l'objet du fichier
metadata = json.load(StringIO(file_content))
elif obj.key.split('/')[-1].split('.')[-1] == 'csv' :
if 'Raw' in obj.key.split('/')[-1] :
csv_data = StringIO(file_content)
raw_df = pd.read_csv(csv_data, sep=",")
else :
csv_data = StringIO(file_content)
df = pd.read_csv(csv_data, sep=",")
str_smoother = metadata['parameters']['smoother']
raw_data = metadata['parameters']['raw_data']
dict_data = {
"metadata" : metadata,
"raw_df" : raw_df if raw_data else None,
"df" : df if str_smoother == "false" else None,
"ts" : df if str_smoother != "false" else None
}
return dict_data
def plot_mrts_from_aws(str_s3_path):
""" Plot MRTS outputs stored on S3 AWS
Args:
str_s3_path (_string_): URI S3 (aws)
"""
dict_data = read_mrts_from_awsS3(str_s3_path)
plot_mrts_dict(dict_data)
def download_s3_files(str_s3_path):
"""download files stored on aws S3 bucket
Args:
str_s3_path (_string_): URI S3 (aws)
"""
s3 = boto3.resource('s3')
parsed_url = urlparse(str_s3_path)
bucket_name = parsed_url.netloc
directory_name = parsed_url.path.lstrip('/')
bucket = s3.Bucket(bucket_name)
for obj in bucket.objects.filter(Prefix=directory_name):
if not os.path.exists(os.path.dirname(obj.key)):
os.makedirs(os.path.dirname(obj.key))
bucket.download_file(obj.key, obj.key)