-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiff.txt
363 lines (314 loc) · 18.4 KB
/
diff.txt
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
diff --git a/.vscode/launch.json b/.vscode/launch.json
new file mode 100644
index 0000000..1b2aae4
--- /dev/null
+++ b/.vscode/launch.json
@@ -0,0 +1,28 @@
+{
+ // Use IntelliSense to learn about possible attributes.
+ // Hover to view descriptions of existing attributes.
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": "Python Debugger: Current File",
+ "type": "python",
+ "request": "launch",
+ "program": "${workspaceFolder}/CellEnMon/train.py",
+ "console": "integratedTerminal",
+ "env": {
+ "ENABLE_GAN": "1",
+ "THETA": "1",
+ "LAMBDA": "1",
+ "SELECTED_GROUP_NAME": "Lahav",
+ "SELECT_JOB": "2",
+ "ENABLE_WANDB": "True",
+ "DEBUG": "0",
+ "threshold": "0.3",
+ "rec_probability_threshold": "0.5",
+ "fake_probability_threshold": "0.25"
+ },
+ "args": []
+ }
+ ]
+}
\ No newline at end of file
diff --git a/CellEnMon/data/exporter.py b/CellEnMon/data/exporter.py
index 13a2ace..230018c 100644
--- a/CellEnMon/data/exporter.py
+++ b/CellEnMon/data/exporter.py
@@ -234,13 +234,45 @@ class Extractor:
ims_matrix = {}
for index, station_file_name in enumerate(os.listdir(f'{config.ims_root_files}/raw')):
print("now processing gauge: {}".format(station_file_name))
+ col='RainAmount[mm/h]'
try:
metadata = self.get_ims_metadata(f'{station_file_name}')
if metadata:
df = pd.read_csv(f'{config.ims_root_files}/raw/{station_file_name}')
- time=df.Time.to_numpy()
- ims_vec=df["RainAmout[mm/h]"].to_numpy()
+
+ # Set 'Time' as the index
+ df.set_index('Time', inplace=True)
+
+ # Create a new DataFrame with a 10-minute interval
+ idx = pd.date_range(start=df.index.min(), end=df.index.max(), freq='15T')
+ df_resampled = df.reindex(idx)
+
+ # Interpolate: 'mean of **:10 and **:20 for **:15' logic
+ for time in df_resampled.index:
+ try:
+ minute = time.minute
+ if minute == 15 or minute == 45:
+ prev_time = time - pd.Timedelta(minutes=5)
+ next_time = time + pd.Timedelta(minutes=5)
+ if prev_time in df_resampled.index and next_time in df_resampled.index:
+ df_resampled.loc[time] = (df_resampled.loc[str(prev_time)][0] + df_resampled.loc[str(next_time)][0])/2
+ else:
+ df_resampled.loc[time]=df.loc[str(time)][0]
+ except KeyError:
+ continue
+
+
+ # Forward-fill remaining NaNs and output the result
+ df_resampled.fillna(0.0, inplace=True)
+
+ # Reset the index
+ df_resampled.reset_index(inplace=True)
+ df_resampled.columns = ['Time', 'RainAmount[mm/h]']
+
+
+ time=df_resampled.Time.dt.strftime('%Y-%m-%d %H:%M:%S').to_numpy()
+ ims_vec=df_resampled["RainAmount[mm/h]"].to_numpy()
ims_matrix[metadata["gauge_name"]] = \
@@ -264,11 +296,13 @@ class Extractor:
#Conditional dataset
validation_data["LAHAV"]=training_data["LAHAV"]
- validation_data["NEOT SMADAR"]=training_data["NEOT SMADAR"]
+ validation_data["NIZZAN"]=training_data["NIZZAN"]
+ validation_data["SHANI"]=training_data["SHANI"]
#train pop
training_data.pop("LAHAV",None)
- training_data.pop("NEOT SMADAR",None)
+ training_data.pop("NIZZAN",None)
+ training_data.pop("SHANI",None)
#validation pop
validation_data.pop("ZOMVET HANEGEV",None)
@@ -375,7 +409,11 @@ class Extractor:
#Conditional dataset
validation_data["b394-ts04"]=training_data["b394-ts04"]
+ #validation_data["b459-a690"]=training_data["b459-a690"]
+ validation_data["j033-261c"]=training_data["j033-261c"]
training_data.pop("b394-ts04",None)
+ #training_data.pop("b459-a690",None)
+ training_data.pop("j033-261c",None)
dataset = training_data if is_train else validation_data
with open(f'{temp_str}/{dataset_type_str}.pkl', 'wb') as f:
diff --git a/CellEnMon/libs/visualize/visualize.py b/CellEnMon/libs/visualize/visualize.py
index deb6e5f..994a08d 100644
--- a/CellEnMon/libs/visualize/visualize.py
+++ b/CellEnMon/libs/visualize/visualize.py
@@ -46,6 +46,7 @@ class Visualizer:
self.color_of_links = 'red'
self.color_of_gauges = 'blue'
self.color_of_produced_gauges = 'green'
+ self.color_of_validation = 'black'
self.gridlines_on = False
self.num_of_gridlines = 30
@@ -245,6 +246,8 @@ class Visualizer:
p = folium.Popup(max_width=1150)
if station_type == "link":
+ if instace_dict["ID"] in ['b394_ts04', 'j033_261c']: #'c409_d063'
+ color='black'
pl = folium.PolyLine([(instace_dict['Rx Site Longitude'], instace_dict['Rx Site Latitude']),
(instace_dict['Tx Site Longitude'], instace_dict['Tx Site Latitude'])
],
@@ -252,6 +255,8 @@ class Visualizer:
opacity=1.0
).add_to(map_1)
else:
+ if instace_dict["ID"] in ['LAHAV', 'NIZZAN']: #SHANI
+ color='black'
pl = folium.Marker(
location=[instace_dict['Rx Site Longitude'], instace_dict['Rx Site Latitude']],
popup=folium.Popup(f"ID:{instace_dict['ID']}"),
diff --git a/CellEnMon/models/cycle_gan_model.py b/CellEnMon/models/cycle_gan_model.py
index 6c4d5e8..75c169b 100644
--- a/CellEnMon/models/cycle_gan_model.py
+++ b/CellEnMon/models/cycle_gan_model.py
@@ -139,7 +139,7 @@ class CycleGANModel(BaseModel):
def weight_func(self, x, a):
return 1/(a * torch.exp(-x*a))
- def set_input(self, input, isTrain=True):
+ def set_input(self, input, epoch, isTrain=True):
"""Unpack input data from the dataloader and perform necessary pre-processing steps.
Parameters:
@@ -161,6 +161,7 @@ class CycleGANModel(BaseModel):
L=input['distance'].to(self.device)
self.L=L+self.epsilon
self.dist_func=1/(torch.log(1+(self.L/config.TRAIN_RADIUS)))
+ self.epoch=epoch
if isTrain:
@@ -265,11 +266,11 @@ class CycleGANModel(BaseModel):
L2=nn.MSELoss(reduction='none')
# Real
pred_real = netD(real)
- target = torch.full_like(pred_real, 0.9).to(pred_real.device)
+ target = torch.full_like(pred_real, 1).to(pred_real.device)
loss_D_real = torch.mean(L2(pred_real, target))
# Fake
pred_fake = netD(fake.detach())
- target = torch.full_like(pred_fake, 0.1).to(pred_fake.device)
+ target = torch.full_like(pred_fake, 0).to(pred_fake.device)
loss_D_fake = torch.mean(L2(pred_fake, target))
# Combined loss and calculate gradients
loss_D = (loss_D_real + loss_D_fake)
@@ -280,12 +281,12 @@ class CycleGANModel(BaseModel):
def backward_D_A(self):
"""Calculate GAN loss for discriminator D_A"""
#fake_B = self.fake_B_pool.query(self.fake_B)
- self.loss_D_A = 0.1 * self.backward_D_basic(self.netD_A, self.real_A, self.fake_A)
+ self.loss_D_A = self.backward_D_basic(self.netD_A, self.real_A, self.fake_A)
def backward_D_B(self):
"""Calculate GAN loss for discriminator D_B"""
#fake_A = self.fake_A_pool.query(self.fake_A)
- self.loss_D_B = 0.1 * self.backward_D_basic(self.netD_B, self.real_B, self.fake_B) # self.fake_B_dot_detection
+ self.loss_D_B = self.backward_D_basic(self.netD_B, self.real_B, self.fake_B) # self.fake_B_dot_detection
def backward_G(self):
"""Calculate the losses"""
@@ -333,8 +334,8 @@ class CycleGANModel(BaseModel):
# Backward cycle loss
- self.loss_cycle_A = torch.mean(L2(self.rec_A, self.real_A))
- self.loss_cycle_B = 1000 * torch.mean(L2(self.rec_B, self.real_B)) #
+ self.loss_cycle_A = 10 * torch.mean(L1(self.rec_A, self.real_A))
+ self.loss_cycle_B = 10 * torch.mean(L1(self.rec_B_dot_detection, self.real_B)) #
# gamma=2
# residual = torch.abs(self.rec_B - self.real_B) # L1 loss
@@ -345,12 +346,12 @@ class CycleGANModel(BaseModel):
# GAN loss D_B(G_A(A))
self.D_B=self.netD_B(self.fake_B) # self.fake_B_dot_detection
targets = torch.full_like(self.D_B, 1.0).to(self.D_B.device)
- self.loss_G_B_only = 0.1 * torch.mean(L2(self.D_B, targets))
+ self.loss_G_B_only = torch.mean(L2(self.D_B, targets))
# GAN loss D_A(G_B(B))
self.D_A=self.netD_A(self.fake_A)
targets = torch.full_like(self.D_A, 1.0).to(self.D_A.device)
- self.loss_G_A = 0.1 * torch.mean(L2(self.D_A, targets)) #weight=self.rr_norm.max(), weight=self.att_norm.mean()
+ self.loss_G_A = torch.mean(L2(self.D_A, targets)) #weight=self.rr_norm.max(), weight=self.att_norm.mean()
diff --git a/CellEnMon/models/networks.py b/CellEnMon/models/networks.py
index d850626..73966c6 100644
--- a/CellEnMon/models/networks.py
+++ b/CellEnMon/models/networks.py
@@ -443,7 +443,7 @@ class ResnetBlock(nn.Module):
p = 1
else:
raise NotImplementedError('padding [%s] is not implemented' % padding_type)
- conv_block += [nn.Conv1d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)] #
+ conv_block += [nn.Conv1d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)] #
return nn.Sequential(*conv_block)
diff --git a/CellEnMon/options/base_options.py b/CellEnMon/options/base_options.py
index 61d7605..791d334 100644
--- a/CellEnMon/options/base_options.py
+++ b/CellEnMon/options/base_options.py
@@ -45,7 +45,7 @@ class BaseOptions():
parser.add_argument('--n_layers_D', type=int, default=8, help='only used if netD==n_layers | if you want to change this make sure to adjust D so it will ouput [1,1,1]')
parser.add_argument('--norm', type=str, default='instance',
help='instance normalization or batch normalization [instance | batch | none | layer]')
- parser.add_argument('--init_type', type=str, default='normal',
+ parser.add_argument('--init_type', type=str, default='xavier',
help='network initialization [normal | xavier | kaiming | orthogonal]')
diff --git a/CellEnMon/options/train_options.py b/CellEnMon/options/train_options.py
index 91461dc..8378797 100644
--- a/CellEnMon/options/train_options.py
+++ b/CellEnMon/options/train_options.py
@@ -27,10 +27,10 @@ class TrainOptions(BaseOptions):
parser.add_argument('--epoch_count', type=int, default=1, help='the starting epoch count, we save the model by <epoch_count>, <epoch_count>+<save_latest_freq>, ...')
parser.add_argument('--phase', type=str, default='train', help='train, val, test, etc')
# training parameters
- parser.add_argument('--n_epochs', type=int, default=30, help='number of epochs with the initial learning rate')
- parser.add_argument('--n_epochs_decay', type=int, default=200, help='number of epochs to linearly decay learning rate to zero')
+ parser.add_argument('--n_epochs', type=int, default=100, help='number of epochs with the initial learning rate')
+ parser.add_argument('--n_epochs_decay', type=int, default=100, help='number of epochs to linearly decay learning rate to zero')
parser.add_argument('--beta1', type=float, default=0.1, help='momentum term of adam')
- parser.add_argument('--lr', type=float, default=0.0003, help='initial learning rate for adam') # 0.00001
+ parser.add_argument('--lr', type=float, default=0.00003, help='initial learning rate for adam') # 0.00001
parser.add_argument('--gan_mode', type=str, default='lsgan', help='the type of GAN objective. [vanilla| lsgan | wgangp]. vanilla GAN loss is the cross-entropy objective used in the original GAN paper.')
parser.add_argument('--pool_size', type=int, default=50, help='the size of image buffer that stores previously generated images')
parser.add_argument('--lr_policy', type=str, default='linear', help='learning rate policy. [linear | step | plateau | cosine]')
diff --git a/CellEnMon/train.py b/CellEnMon/train.py
index 1aa5b15..ffd9697 100644
--- a/CellEnMon/train.py
+++ b/CellEnMon/train.py
@@ -95,9 +95,10 @@ all_link_to_gauge_matching ={
validation_link_to_gauge_matching ={
# "c078-d088": [],
# "a473-b119": [],
- "b394-ts04": ["LAHAV"], #
+ "b394-ts04": [], #LAHAV
"b459-a690": [], #"NEOT SMADAR",
"c409-d063": [],
+ "j033-261c": ["NIZZAN"]
}
@@ -203,7 +204,7 @@ if __name__ == '__main__':
epoch_iter += train_opt.batch_size
#model.train()
- model.set_input(data) # unpack data from dataset and apply preprocessing
+ model.set_input(data, epoch) # unpack data from dataset and apply preprocessing
model.optimize_parameters(is_train=True) # calculate loss functions, get gradients, update network weights
# Training losses
@@ -281,7 +282,7 @@ if __name__ == '__main__':
"distance": torch.tensor([3], device='cuda:0', dtype=torch.float64), # in KM
"slice_dist": train_opt.slice_dist
}
- model.set_input(loader,isTrain=False)
+ model.set_input(loader,epoch,isTrain=False)
model.optimize_parameters(is_train=False)
visuals = model.get_current_visuals()
@@ -323,7 +324,7 @@ if __name__ == '__main__':
rec_gauge_vec=np.append(rec_gauge_vec,rec_rain_add)
fake_gauge_vec_det=np.append(fake_gauge_vec_det,fake_detection_add)
rec_gauge_vec_det=np.append(rec_gauge_vec_det, rec_detection_add)
- T=np.append(T,np.array(model.t))
+ T=np.append(T,model.t)
# rec_A=visuals['rec_A'][0].cpu().detach().numpy()
@@ -382,11 +383,11 @@ if __name__ == '__main__':
if key=="fake_B":
mask=fake_detection_add[0]
- probability_threshold=rec_probability_threshold
+ probability_threshold=fake_probability_threshold
else:
mask=rec_detection_add[0]
- probability_threshold=fake_probability_threshold
+ probability_threshold=rec_probability_threshold
mask=(mask >= probability_threshold).astype(int)
@@ -423,8 +424,8 @@ if __name__ == '__main__':
# Convert continuous values to binary class labels
real_gauge_vec_labels = (real_gauge_vec >= threshold).astype(int)
- rec_gauge_vec_det_labels = ((rec_gauge_vec_det >= probability_threshold)).astype(int)
- fake_gauge_vec_det_labels = ((fake_gauge_vec_det >= probability_threshold)).astype(int)
+ rec_gauge_vec_det_labels = ((rec_gauge_vec_det >= rec_probability_threshold)).astype(int)
+ fake_gauge_vec_det_labels = ((fake_gauge_vec_det >= fake_probability_threshold)).astype(int)
p=Preprocess(link=link,gauge=gauge,epoch=epoch, T=T,\
@@ -471,8 +472,8 @@ if __name__ == '__main__':
- preprocessed_time=np.asarray(T) #16436.00694444
- preprocessed_time_wanb=[mpl_dates.date2num(datetime.strptime(t, datetime_format)) for t in T]
+
+ preprocessed_time_wanb=np.array([mpl_dates.date2num(datetime.strptime(t, datetime_format)) for t in T])
fig_preprocessed, axs_preprocessed = plt.subplots(1, 1, figsize=(15, 15))
@@ -497,13 +498,14 @@ if __name__ == '__main__':
num_ticks = 10
# Calculate the step size between ticks
- step_size = len(preprocessed_time) // num_ticks
+ step_size = len(preprocessed_time_wanb) // num_ticks
# Set the ticks on the x-axis
- axs_preprocessed.set_xticks(preprocessed_time_wanb[::step_size]) # Setting x-ticks
- axs_preprocessed.set_xticklabels(preprocessed_time_wanb[::step_size], rotation=45) # Setting x-tick labels with rotation
+ # axs_preprocessed.set_xticks(np.array(preprocessed_time_wanb[::step_size])) # Setting x-ticks
+ # axs_preprocessed.set_xticklabels(preprocessed_time_wanb[::step_size], rotation=45) # Setting x-tick labels with rotation
axs_preprocessed.xaxis.set_major_formatter(date_format)
-
+
+
wandb.log({f"Virtual (CML) vs Real (Gauge) - {link}-{gauge}":fig_preprocessed})
#RMSSE