-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.py
300 lines (212 loc) · 9.16 KB
/
main.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: Esteban Alonso González - [email protected]
"""
import modules.internal_fns as ifn
import modules.spatialMuSA as spM
import config as cfg
if cfg.numerical_model == 'FSM2':
import modules.fsm_tools as model
elif cfg.numerical_model == 'dIm':
import modules.dIm_tools as model
elif cfg.numerical_model == 'snow17':
import modules.snow17_tools as model
else:
raise Exception('Model not implemented')
import numpy as np
import sys
if (cfg.parallelization == "multiprocessing" or
cfg.implementation == "open_loop"):
import multiprocessing as mp
elif cfg.parallelization == "HPC.array":
import multiprocessing as mp
else:
pass
from modules.cell_assim import cell_assimilation
from mpi4py import MPI
import logging
def MuSA():
if cfg.parallelization == "HPC.array":
pass
else:
model.model_compile()
"""
This is the main function. Here the parallelization scheme and the
implementation is selected. This function is just a wrapper of the real
assimilation process, which is encapsulated in the cell_assimilation
function.
Raises
------
'Choose an available implementation'
An available implementation should be choosen.
'Choose an available parallelization scheme'
An available parallelization scheme should be choosen.
-------
None.
"""
if cfg.implementation == "point_scale":
print("Running the assimilation in a single point")
lat_idx, lon_idx = ifn.nc_idx()
cell_assimilation(lat_idx, lon_idx)
elif (cfg.implementation == "distributed"):
grid = ifn.expand_grid()
if cfg.parallelization == "sequential":
print("Running MuSA: Sequentially")
for row in range(grid.shape[0]):
lat_idx = grid[row, 0]
lon_idx = grid[row, 1]
cell_assimilation(lat_idx, lon_idx)
elif cfg.parallelization == "multiprocessing":
print("Running MuSA: Distributed (multiprocessing)")
if cfg.MPI:
comm = MPI.COMM_WORLD
nprocess = comm.Get_size() - 1
else:
if isinstance(cfg.nprocess, int):
nprocess = cfg.nprocess
else:
nprocess = mp.cpu_count() - 1
print("Launching " + str(nprocess) + " processes in "
+ str(mp.cpu_count()) + " processors")
inputs = [grid[:, 0], grid[:, 1]]
ifn.safe_pool(cell_assimilation, inputs, nprocess)
elif cfg.parallelization == "HPC.array":
HPC_task_number = int(sys.argv[1])
nprocess = int(sys.argv[2])
HPC_task_id = int(sys.argv[3])-1
ids = np.arange(0, grid.shape[0])
ids = ids % HPC_task_number == HPC_task_id
print("Running MuSA: Distributed (HPC.array) from job: " +
str(HPC_task_id) + " in " + str(nprocess) + " cores")
# compile FSM
model.model_compile_HPC(HPC_task_id)
inputs = [grid[ids, 0], grid[ids, 1]]
ifn.safe_pool(cell_assimilation, inputs, nprocess)
else:
raise Exception("Choose an available paralelization scheme")
elif cfg.implementation == 'Spatial_propagation':
if cfg.da_algorithm not in ["ES", "IES"]:
raise Exception("Spatial_propagation needs ES/IES methods")
if cfg.parallelization == "HPC.array":
grid = ifn.expand_grid()
# Restart run
if cfg.restart_run:
prev_step, prev_j = ifn.return_step_j('spatiallogfile.txt')
else:
prev_step, prev_j = 0, 0
# Log file for restart
logging.basicConfig(filename='spatiallogfile.txt',
level=logging.INFO,
format='%(asctime)s - %(message)s')
HPC_task_number = int(sys.argv[1])
nprocess = int(sys.argv[2])
HPC_task_id = int(sys.argv[3])-1
ids = np.arange(0, grid.shape[0])
ids = ids % HPC_task_number == HPC_task_id
print("Running MuSA: Distributed (HPC.array) from job: " +
str(HPC_task_id) + " in " + str(nprocess) + " cores")
# compile FSM
model.model_compile_HPC(HPC_task_id)
# get timestep of GSC maps
ini_DA_window = spM.domain_steps()
# DA_loop
# create a pool inside each task
# this enumerate is unnecesary
for gsc_count, step in enumerate(range(len(ini_DA_window))):
if cfg.restart_run and step < prev_step:
continue
# create prior Ensembles
inputs = [list(grid[ids, 0]), list(grid[ids, 1]),
[ini_DA_window] * sum(ids),
[step] * sum(ids),
[gsc_count] * sum(ids)]
ifn.safe_pool(spM.create_ensemble_cell, inputs, nprocess)
# Wait untill all ensembles are created
spM.wait_for_ensembles(step, HPC_task_id)
for j in range(cfg.max_iterations): # Run spatial assim
if cfg.restart_run and j < prev_j:
continue
# add info to log
logging.info(f'step: {step} - j: {j}')
inputs = [list(grid[ids, 0]), list(grid[ids, 1]),
[step] * sum(ids), [j]*sum(ids)]
ifn.safe_pool(spM.spatial_assim, inputs, nprocess)
# Wait untill all ensembles are updated and remove prior
spM.wait_for_ensembles(step, HPC_task_id, j)
# collect results from HPC_task_id = 0
if HPC_task_id != 0:
return None
else:
inputs = [grid[:, 0], grid[:, 1]]
ifn.safe_pool(spM.collect_results, inputs, nprocess)
elif cfg.parallelization == "multiprocessing":
grid = ifn.expand_grid()
# Restart run
if cfg.restart_run:
prev_step, prev_j = ifn.return_step_j('spatiallogfile.txt')
else:
prev_step, prev_j = 0, 0
# Log file for restart
logging.basicConfig(filename='spatiallogfile.txt',
level=logging.INFO,
format='%(asctime)s - %(message)s')
if cfg.MPI:
comm = MPI.COMM_WORLD
nprocess = comm.Get_size() - 1
else:
if isinstance(cfg.nprocess, int):
nprocess = cfg.nprocess
else:
nprocess = mp.cpu_count() - 1
# get timestep of GSC maps
ini_DA_window = spM.domain_steps()
# DA loop
for gsc_count, step in enumerate(range(len(ini_DA_window))):
if cfg.restart_run and step < prev_step:
continue
# create prior Ensembles
inputs = [list(grid[ids, 0]), list(grid[ids, 1]),
[ini_DA_window] * sum(ids),
[step] * sum(ids),
[gsc_count] * sum(ids)]
ifn.safe_pool(spM.create_ensemble_cell, inputs, nprocess)
# Wait untill all ensembles are created
spM.wait_for_ensembles(step, 0)
for j in range(cfg.max_iterations): # Run spatial assim
if cfg.restart_run and j < prev_j:
continue
# add info to log
logging.info(f'step: {step} - j: {j}')
inputs = [list(grid[:, 0]), list(grid[:, 1]),
[step] * grid.shape[0],
[j] * grid.shape[0]]
ifn.safe_pool(spM.spatial_assim, inputs, nprocess)
# Wait untill all ensembles are updated and remove prior
spM.wait_for_ensembles(step, 0, j)
# collect results
inputs = [grid[:, 0], grid[:, 1]]
ifn.safe_pool(spM.collect_results, inputs, nprocess)
elif cfg.implementation == "open_loop":
grid = ifn.expand_grid()
print("Running FSM simulation: Distributed (multiprocessing)")
if isinstance(cfg.nprocess, int):
nprocess = cfg.nprocess
else:
nprocess = mp.cpu_count() - 1
print("Launching " + str(nprocess) + " processes in " +
str(mp.cpu_count()) + " processors")
inputs = [grid[:, 0], grid[:, 1]]
ifn.safe_pool(ifn.open_loop_simulation, inputs, nprocess)
else:
raise Exception("Choose an available implementation")
def check_platform():
# TODO: provide full suport for wind32
if (sys.platform not in ("linux", "darwin")):
raise Exception(sys.platform + " is not supported by MuSA yet")
if __name__ == "__main__":
if cfg.parallelization in ["multiprocessing", "HPC.array"]:
mp.set_start_method('spawn', force=True)
check_platform()
ifn.pre_cheks()
MuSA()