-
Notifications
You must be signed in to change notification settings - Fork 7
/
forward_pass.py
2011 lines (1783 loc) · 80.8 KB
/
forward_pass.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Sup3r forward pass handling module.
@author: bbenton
"""
import copy
import logging
import os
import warnings
from concurrent.futures import as_completed
from datetime import datetime as dt
from inspect import signature
from typing import ClassVar
import numpy as np
import psutil
from rex.utilities.execution import SpawnProcessPool
from rex.utilities.fun_utils import get_fun_call_str
import sup3r.bias.bias_transforms
import sup3r.models
from sup3r.postprocessing.file_handling import (
OutputHandler,
OutputHandlerH5,
OutputHandlerNC,
)
from sup3r.preprocessing.data_handling.base import InputMixIn
from sup3r.preprocessing.data_handling.exogenous_data_handling import (
ExoData,
ExogenousDataHandler,
)
from sup3r.utilities import ModuleName
from sup3r.utilities.cli import BaseCLI
from sup3r.utilities.execution import DistributedProcess
from sup3r.utilities.utilities import (
get_chunk_slices,
get_input_handler_class,
get_source_type,
)
np.random.seed(42)
logger = logging.getLogger(__name__)
class ForwardPassSlicer:
"""Get slices for sending data chunks through model."""
def __init__(self,
coarse_shape,
time_steps,
temporal_slice,
chunk_shape,
s_enhancements,
t_enhancements,
spatial_pad,
temporal_pad):
"""
Parameters
----------
coarse_shape : tuple
Shape of full domain for low res data
time_steps : int
Number of time steps for full temporal domain of low res data. This
is used to construct a dummy_time_index from np.arange(time_steps)
temporal_slice : slice
Slice to use to extract range from time_index
chunk_shape : tuple
Max shape (spatial_1, spatial_2, temporal) of an unpadded coarse
chunk to use for a forward pass. The number of nodes that the
ForwardPassStrategy is set to distribute to is calculated by
dividing up the total time index from all file_paths by the
temporal part of this chunk shape. Each node will then be
parallelized accross parallel processes by the spatial chunk shape.
If temporal_pad / spatial_pad are non zero the chunk sent
to the generator can be bigger than this shape. If running in
serial set this equal to the shape of the full spatiotemporal data
volume for best performance.
s_enhancements : list
List of factors by which the Sup3rGan model will enhance the
spatial dimensions of low resolution data. If there are two 5x
spatial enhancements, this should be [5, 5] where the total
enhancement is the product of these factors.
t_enhancements : list
List of factor by which the Sup3rGan model will enhance temporal
dimension of low resolution data
spatial_pad : int
Size of spatial overlap between coarse chunks passed to forward
passes for subsequent spatial stitching. This overlap will pad both
sides of the fwp_chunk_shape. Note that the first and last chunks
in any of the spatial dimension will not be padded.
temporal_pad : int
Size of temporal overlap between coarse chunks passed to forward
passes for subsequent temporal stitching. This overlap will pad
both sides of the fwp_chunk_shape. Note that the first and last
chunks in the temporal dimension will not be padded.
"""
self.grid_shape = coarse_shape
self.time_steps = time_steps
self.s_enhancements = s_enhancements
self.t_enhancements = t_enhancements
self.s_enhance = np.prod(self.s_enhancements)
self.t_enhance = np.prod(self.t_enhancements)
self.dummy_time_index = np.arange(time_steps)
self.temporal_slice = temporal_slice
self.temporal_pad = temporal_pad
self.spatial_pad = spatial_pad
self.chunk_shape = chunk_shape
self._chunk_lookup = None
self._s1_lr_slices = None
self._s2_lr_slices = None
self._s1_lr_pad_slices = None
self._s2_lr_pad_slices = None
self._s_lr_slices = None
self._s_lr_pad_slices = None
self._s_lr_crop_slices = None
self._t_lr_pad_slices = None
self._t_lr_crop_slices = None
self._s_hr_slices = None
self._s_hr_crop_slices = None
self._t_hr_crop_slices = None
self._hr_crop_slices = None
self._gids = None
def get_spatial_slices(self):
"""Get spatial slices for small data chunks that are passed through
generator
Returns
-------
s_lr_slices: list
List of slices for low res data chunks which have not been padded.
data_handler.data[s_lr_slice] corresponds to an unpadded low res
input to the model.
s_lr_pad_slices : list
List of slices which have been padded so that high res output
can be stitched together. data_handler.data[s_lr_pad_slice]
corresponds to a padded low res input to the model.
s_hr_slices : list
List of slices for high res data corresponding to the
lr_slices regions. output_array[s_hr_slice] corresponds to the
cropped generator output.
"""
return (self.s_lr_slices, self.s_lr_pad_slices, self.s_hr_slices)
def get_temporal_slices(self):
"""Calculate the number of time chunks across the full time index
Returns
-------
t_lr_slices : list
List of low-res non-padded time index slices. e.g. If
fwp_chunk_size[2] is 5 then the size of these slices will always
be 5.
t_lr_pad_slices : list
List of low-res padded time index slices. e.g. If fwp_chunk_size[2]
is 5 the size of these slices will be 15, with exceptions at the
start and end of the full time index.
"""
return self.t_lr_slices, self.t_lr_pad_slices
@property
def s_lr_slices(self):
"""Get low res spatial slices for small data chunks that are passed
through generator
Returns
-------
_s_lr_slices : list
List of spatial slices corresponding to the unpadded spatial region
going through the generator
"""
if self._s_lr_slices is None:
self._s_lr_slices = []
for _, s1 in enumerate(self.s1_lr_slices):
for _, s2 in enumerate(self.s2_lr_slices):
s_slice = (s1, s2, slice(None), slice(None))
self._s_lr_slices.append(s_slice)
return self._s_lr_slices
@property
def s_lr_pad_slices(self):
"""Get low res padded slices for small data chunks that are passed
through generator
Returns
-------
_s_lr_pad_slices : list
List of slices which have been padded so that high res output
can be stitched together. Each entry in this list has a slice for
each spatial dimension and then slice(None) for temporal and
feature dimension. This is because the temporal dimension is only
chunked across nodes and not within a single node.
data_handler.data[s_lr_pad_slice] gives the padded data volume
passed through the generator
"""
if self._s_lr_pad_slices is None:
self._s_lr_pad_slices = []
for _, s1 in enumerate(self.s1_lr_pad_slices):
for _, s2 in enumerate(self.s2_lr_pad_slices):
pad_slice = (s1, s2, slice(None), slice(None))
self._s_lr_pad_slices.append(pad_slice)
return self._s_lr_pad_slices
@property
def t_lr_pad_slices(self):
"""Get low res temporal padded slices for distributing time chunks
across nodes. These slices correspond to the time chunks sent to each
node and are padded according to temporal_pad.
Returns
-------
_t_lr_pad_slices : list
List of low res temporal slices which have been padded so that high
res output can be stitched together
"""
if self._t_lr_pad_slices is None:
self._t_lr_pad_slices = self.get_padded_slices(
self.t_lr_slices,
self.time_steps,
1,
self.temporal_pad,
self.temporal_slice.step,
)
return self._t_lr_pad_slices
@property
def t_lr_crop_slices(self):
"""Get low res temporal cropped slices for cropping time index of
padded input data.
Returns
-------
_t_lr_crop_slices : list
List of low res temporal slices for cropping padded input data
"""
if self._t_lr_crop_slices is None:
self._t_lr_crop_slices = self.get_cropped_slices(
self.t_lr_slices, self.t_lr_pad_slices, 1)
return self._t_lr_crop_slices
@property
def t_hr_crop_slices(self):
"""Get high res temporal cropped slices for cropping forward pass
output before stitching together
Returns
-------
_t_hr_crop_slices : list
List of high res temporal slices for cropping padded generator
output
"""
hr_crop_start = None
hr_crop_stop = None
if self.temporal_pad > 0:
hr_crop_start = self.t_enhance * self.temporal_pad
hr_crop_stop = -hr_crop_start
if self._t_hr_crop_slices is None:
# don't use self.get_cropped_slices() here because temporal padding
# gets weird at beginning and end of timeseries and the temporal
# axis should always be evenly chunked.
self._t_hr_crop_slices = [
slice(hr_crop_start, hr_crop_stop)
for _ in range(len(self.t_lr_slices))
]
return self._t_hr_crop_slices
@property
def s1_hr_slices(self):
"""Get high res spatial slices for first spatial dimension"""
return self.get_hr_slices(self.s1_lr_slices, self.s_enhance)
@property
def s2_hr_slices(self):
"""Get high res spatial slices for second spatial dimension"""
return self.get_hr_slices(self.s2_lr_slices, self.s_enhance)
@property
def s_hr_slices(self):
"""Get high res slices for indexing full generator output array
Returns
-------
_s_hr_slices : list
List of high res slices. Each entry in this list has a slice for
each spatial dimension and then slice(None) for temporal and
feature dimension. This is because the temporal dimension is only
chunked across nodes and not within a single node. output[hr_slice]
gives the superresolved domain corresponding to
data_handler.data[lr_slice]
"""
if self._s_hr_slices is None:
self._s_hr_slices = []
for _, s1 in enumerate(self.s1_hr_slices):
for _, s2 in enumerate(self.s2_hr_slices):
hr_slice = (s1, s2, slice(None), slice(None))
self._s_hr_slices.append(hr_slice)
return self._s_hr_slices
@property
def s_lr_crop_slices(self):
"""Get low res cropped slices for cropping input chunk domain
Returns
-------
_s_lr_crop_slices : list
List of low res cropped slices. Each entry in this list has a
slice for each spatial dimension and then slice(None) for temporal
and feature dimension.
"""
if self._s_lr_crop_slices is None:
self._s_lr_crop_slices = []
s1_crop_slices = self.get_cropped_slices(self.s1_lr_slices,
self.s1_lr_pad_slices,
1)
s2_crop_slices = self.get_cropped_slices(self.s2_lr_slices,
self.s2_lr_pad_slices,
1)
for i, _ in enumerate(self.s1_lr_slices):
for j, _ in enumerate(self.s2_lr_slices):
lr_crop_slice = (s1_crop_slices[i],
s2_crop_slices[j],
slice(None),
slice(None),
)
self._s_lr_crop_slices.append(lr_crop_slice)
return self._s_lr_crop_slices
@property
def s_hr_crop_slices(self):
"""Get high res cropped slices for cropping generator output
Returns
-------
_s_hr_crop_slices : list
List of high res cropped slices. Each entry in this list has a
slice for each spatial dimension and then slice(None) for temporal
and feature dimension.
"""
hr_crop_start = None
hr_crop_stop = None
if self.spatial_pad > 0:
hr_crop_start = self.s_enhance * self.spatial_pad
hr_crop_stop = -hr_crop_start
if self._s_hr_crop_slices is None:
self._s_hr_crop_slices = []
s1_hr_crop_slices = [
slice(hr_crop_start, hr_crop_stop)
for _ in range(len(self.s1_lr_slices))
]
s2_hr_crop_slices = [
slice(hr_crop_start, hr_crop_stop)
for _ in range(len(self.s2_lr_slices))
]
for _, s1 in enumerate(s1_hr_crop_slices):
for _, s2 in enumerate(s2_hr_crop_slices):
hr_crop_slice = (s1, s2, slice(None), slice(None))
self._s_hr_crop_slices.append(hr_crop_slice)
return self._s_hr_crop_slices
@property
def hr_crop_slices(self):
"""Get high res spatiotemporal cropped slices for cropping generator
output
Returns
-------
_hr_crop_slices : list
List of high res spatiotemporal cropped slices. Each entry in this
list has a crop slice for each spatial dimension and temporal
dimension and then slice(None) for the feature dimension.
model.generate()[hr_crop_slice] gives the cropped generator output
corresponding to output_array[hr_slice]
"""
if self._hr_crop_slices is None:
self._hr_crop_slices = []
for t in self.t_hr_crop_slices:
node_slices = [(s[0], s[1], t, slice(None))
for s in self.s_hr_crop_slices]
self._hr_crop_slices.append(node_slices)
return self._hr_crop_slices
@property
def s1_lr_pad_slices(self):
"""List of low resolution spatial slices with padding for first
spatial dimension"""
if self._s1_lr_pad_slices is None:
self._s1_lr_pad_slices = self.get_padded_slices(
self.s1_lr_slices,
self.grid_shape[0],
1,
padding=self.spatial_pad,
)
return self._s1_lr_pad_slices
@property
def s2_lr_pad_slices(self):
"""List of low resolution spatial slices with padding for second
spatial dimension"""
if self._s2_lr_pad_slices is None:
self._s2_lr_pad_slices = self.get_padded_slices(
self.s2_lr_slices,
self.grid_shape[1],
1,
padding=self.spatial_pad,
)
return self._s2_lr_pad_slices
@property
def s1_lr_slices(self):
"""List of low resolution spatial slices for first spatial dimension
considering padding on all sides of the spatial raster."""
ind = slice(0, self.grid_shape[0])
slices = get_chunk_slices(self.grid_shape[0],
self.chunk_shape[0],
index_slice=ind)
return slices
@property
def s2_lr_slices(self):
"""List of low resolution spatial slices for second spatial dimension
considering padding on all sides of the spatial raster."""
ind = slice(0, self.grid_shape[1])
slices = get_chunk_slices(self.grid_shape[1],
self.chunk_shape[1],
index_slice=ind)
return slices
@property
def t_lr_slices(self):
"""Low resolution temporal slices"""
n_tsteps = len(self.dummy_time_index[self.temporal_slice])
n_chunks = n_tsteps / self.chunk_shape[2]
n_chunks = int(np.ceil(n_chunks))
ti_slices = self.dummy_time_index[self.temporal_slice]
ti_slices = np.array_split(ti_slices, n_chunks)
ti_slices = [
slice(c[0], c[-1] + 1, self.temporal_slice.step) for c in ti_slices
]
return ti_slices
@staticmethod
def get_hr_slices(slices, enhancement, step=None):
"""Get high resolution slices for temporal or spatial slices
Parameters
----------
slices : list
Low resolution slices to be enhanced
enhancement : int
Enhancement factor
step : int | None
Step size for slices
Returns
-------
hr_slices : list
High resolution slices
"""
hr_slices = []
if step is not None:
step = step * enhancement
for sli in slices:
start = sli.start * enhancement
stop = sli.stop * enhancement
hr_slices.append(slice(start, stop, step))
return hr_slices
@property
def chunk_lookup(self):
"""Get a 3D array with shape
(n_spatial_1_chunks, n_spatial_2_chunks, n_temporal_chunks)
where each value is the chunk index."""
if self._chunk_lookup is None:
n_s1 = len(self.s1_lr_slices)
n_s2 = len(self.s2_lr_slices)
n_t = self.n_temporal_chunks
lookup = np.arange(self.n_chunks).reshape((n_t, n_s1, n_s2))
self._chunk_lookup = np.transpose(lookup, axes=(1, 2, 0))
return self._chunk_lookup
@property
def spatial_chunk_lookup(self):
"""Get a 2D array with shape (n_spatial_1_chunks, n_spatial_2_chunks)
where each value is the spatial chunk index."""
n_s1 = len(self.s1_lr_slices)
n_s2 = len(self.s2_lr_slices)
return np.arange(self.n_spatial_chunks).reshape((n_s1, n_s2))
@property
def n_spatial_chunks(self):
"""Get the number of spatial chunks"""
return len(self.hr_crop_slices[0])
@property
def n_temporal_chunks(self):
"""Get the number of temporal chunks"""
return len(self.t_hr_crop_slices)
@property
def n_chunks(self):
"""Get total number of spatiotemporal chunks"""
return self.n_spatial_chunks * self.n_temporal_chunks
@staticmethod
def get_padded_slices(slices, shape, enhancement, padding, step=None):
"""Get padded slices with the specified padding size, max shape,
enhancement, and step size
Parameters
----------
slices : list
List of low res unpadded slice
shape : int
max possible index of a padded slice. e.g. if the slices are
indexing a dimension with size 10 then a padded slice cannot have
an index greater than 10.
enhancement : int
Enhancement factor. e.g. If these slices are indexing a spatial
dimension which will be enhanced by 2x then enhancement=2.
padding : int
Padding factor. e.g. If these slices are indexing a spatial
dimension and the spatial_pad is 10 this is 10. It will be
multiplied by the enhancement factor if the slices are to be used
to index an enhanced dimension.
step : int | None
Step size for slices. e.g. If these slices are indexing a temporal
dimension and temporal_slice.step = 3 then step=3.
Returns
-------
list
Padded slices for temporal or spatial dimensions.
"""
step = step or 1
pad = step * padding * enhancement
pad_slices = []
for _, s in enumerate(slices):
start = np.max([0, s.start * enhancement - pad])
end = np.min([enhancement * shape, s.stop * enhancement + pad])
pad_slices.append(slice(start, end, step))
return pad_slices
@staticmethod
def get_cropped_slices(unpadded_slices, padded_slices, enhancement):
"""Get cropped slices to cut off padded output
Parameters
----------
unpadded_slices : list
List of unpadded slices
padded_slices : list
List of padded slices
enhancement : int
Enhancement factor for the data to be cropped.
Returns
-------
list
Cropped slices for temporal or spatial dimensions.
"""
cropped_slices = []
for ps, us in zip(padded_slices, unpadded_slices):
start = us.start
stop = us.stop
step = us.step or 1
if start is not None:
start = enhancement * (us.start - ps.start) // step
if stop is not None:
stop = enhancement * (us.stop - ps.stop) // step
if start is not None and start <= 0:
start = None
if stop is not None and stop >= 0:
stop = None
cropped_slices.append(slice(start, stop))
return cropped_slices
class ForwardPassStrategy(InputMixIn, DistributedProcess):
"""Class to prepare data for forward passes through generator.
A full file list of contiguous times is provided. The corresponding data is
split into spatiotemporal chunks which can overlap in time and space. These
chunks are distributed across nodes according to the max nodes input or
number of temporal chunks. This strategy stores information on these
chunks, how they overlap, how they are distributed to nodes, and how to
crop generator output to stich the chunks back togerther.
"""
def __init__(self,
file_paths,
model_kwargs,
fwp_chunk_shape,
spatial_pad,
temporal_pad,
model_class='Sup3rGan',
out_pattern=None,
input_handler=None,
input_handler_kwargs=None,
incremental=True,
worker_kwargs=None,
exo_kwargs=None,
bias_correct_method=None,
bias_correct_kwargs=None,
max_nodes=None,
allowed_const=False):
"""Use these inputs to initialize data handlers on different nodes and
to define the size of the data chunks that will be passed through the
generator.
Parameters
----------
file_paths : list | str
A list of low-resolution source files to extract raster data from.
Each file must have the same number of timesteps. Can also pass a
string with a unix-style file path which will be passed through
glob.glob
model_kwargs : str | list
Keyword arguments to send to `model_class.load(**model_kwargs)` to
initialize the GAN. Typically this is just the string path to the
model directory, but can be multiple models or arguments for more
complex models.
fwp_chunk_shape : tuple
Max shape (spatial_1, spatial_2, temporal) of an unpadded coarse
chunk to use for a forward pass. The number of nodes that the
ForwardPassStrategy is set to distribute to is calculated by
dividing up the total time index from all file_paths by the
temporal part of this chunk shape. Each node will then be
parallelized accross parallel processes by the spatial chunk shape.
If temporal_pad / spatial_pad are non zero the chunk sent
to the generator can be bigger than this shape. If running in
serial set this equal to the shape of the full spatiotemporal data
volume for best performance.
spatial_pad : int
Size of spatial overlap between coarse chunks passed to forward
passes for subsequent spatial stitching. This overlap will pad both
sides of the fwp_chunk_shape. Note that the first and last chunks
in any of the spatial dimension will not be padded.
temporal_pad : int
Size of temporal overlap between coarse chunks passed to forward
passes for subsequent temporal stitching. This overlap will pad
both sides of the fwp_chunk_shape. Note that the first and last
chunks in the temporal dimension will not be padded.
model_class : str
Name of the sup3r model class for the GAN model to load. The
default is the basic spatial / spatiotemporal Sup3rGan model. This
will be loaded from sup3r.models
out_pattern : str
Output file pattern. Must be of form <path>/<name>_{file_id}.<ext>.
e.g. /tmp/sup3r_job_{file_id}.h5
Each output file will have a unique file_id filled in and the ext
determines the output type. Pattern can also include {times}. This
will be replaced with start_time-end_time. If pattern is None then
data will be returned in an array and not saved.
input_handler : str | None
data handler class to use for input data. Provide a string name to
match a class in data_handling.py. If None the correct handler will
be guessed based on file type and time series properties.
input_handler_kwargs : dict | None
Any kwargs for initializing the input_handler class
:class:`sup3r.preprocessing.data_handling.DataHandler`.
incremental : bool
Allow the forward pass iteration to skip spatiotemporal chunks that
already have an output file (True, default) or iterate through all
chunks and overwrite any pre-existing outputs (False).
worker_kwargs : dict | None
Dictionary of worker values. Can include max_workers,
pass_workers, output_workers, and ti_workers. Each argument needs
to be an integer or None.
The value of `max workers` will set the value of all other worker
args. If max_workers == 1 then all processes will be serialized. If
max_workers == None then other worker args will use their own
provided values.
`output_workers` is the max number of workers to use for writing
forward pass output. `pass_workers` is the max number of workers to
use for performing forward passes on a single node. If 1 then all
forward passes on chunks distributed to a single node will be run
in serial. pass_workers=2 is the minimum number of workers required
to run the ForwardPass initialization and ForwardPass.run_chunk()
methods concurrently. `ti_workers` is the max number of workers
used to get the full time index. Doing this is parallel can be
helpful when there are a large number of input files.
exo_kwargs : dict | None
Dictionary of args to pass to :class:`ExogenousDataHandler` for
extracting exogenous features for multistep foward pass. This
should be a nested dictionary with keys for each exogeneous
feature. The dictionaries corresponding to the feature names
should include the path to exogenous data source, the resolution
of the exogenous data, and how the exogenous data should be used
in the model. e.g. {'topography': {'file_paths': 'path to input
files', 'source_file': 'path to exo data', 'exo_resolution':
{'spatial': '1km', 'temporal': None}, 'steps': [..]}.
bias_correct_method : str | None
Optional bias correction function name that can be imported from
the :mod:`sup3r.bias.bias_transforms` module. This will transform
the source data according to some predefined bias correction
transformation along with the bias_correct_kwargs. As the first
argument, this method must receive a generic numpy array of data to
be bias corrected
bias_correct_kwargs : dict | None
Optional namespace of kwargs to provide to bias_correct_method.
If this is provided, it must be a dictionary where each key is a
feature name and each value is a dictionary of kwargs to correct
that feature. You can bias correct only certain input features by
only including those feature names in this dict.
max_nodes : int | None
Maximum number of nodes to distribute spatiotemporal chunks across.
If None then a node will be used for each temporal chunk.
allowed_const : list | bool
Tensorflow has a tensor memory limit of 2GB (result of protobuf
limitation) and when exceeded can return a tensor with a
constant output. sup3r will raise a ``MemoryError`` in response. If
your model is allowed to output a constant output, set this to True
to allow any constant output or a list of allowed possible constant
outputs. For example, a precipitation model should be allowed to
output all zeros so set this to ``[0]``. For details on this limit:
https://github.com/tensorflow/tensorflow/issues/51870
"""
self._input_handler_kwargs = input_handler_kwargs or {}
self.init_mixin()
self.file_paths = file_paths
self.model_kwargs = model_kwargs
self.fwp_chunk_shape = fwp_chunk_shape
self.spatial_pad = spatial_pad
self.temporal_pad = temporal_pad
self.model_class = model_class
self.out_pattern = out_pattern
self.worker_kwargs = worker_kwargs or {}
self.exo_kwargs = exo_kwargs or {}
self.incremental = incremental
self.bias_correct_method = bias_correct_method
self.bias_correct_kwargs = bias_correct_kwargs or {}
self._input_handler_class = None
self._input_handler_name = input_handler
self._file_ids = None
self._hr_lat_lon = None
self._lr_lat_lon = None
self._init_handler = None
self._handle_features = None
self.allowed_const = allowed_const
self._single_ts_files = self._input_handler_kwargs.get(
'single_ts_files', None)
self.cache_pattern = self._input_handler_kwargs.get(
'cache_pattern', None)
self.max_workers = self.worker_kwargs.get('max_workers', None)
self.output_workers = self.worker_kwargs.get('output_workers', None)
self.pass_workers = self.worker_kwargs.get('pass_workers', None)
self.ti_workers = self.worker_kwargs.get('ti_workers', None)
self._worker_attrs = ['pass_workers', 'output_workers', 'ti_workers']
self.cap_worker_args(self.max_workers)
model_class = getattr(sup3r.models, self.model_class, None)
if isinstance(self.model_kwargs, str):
self.model_kwargs = {'model_dir': self.model_kwargs}
if model_class is None:
msg = ('Could not load requested model class "{}" from '
'sup3r.models, Make sure you typed in the model class '
'name correctly.'.format(self.model_class))
logger.error(msg)
raise KeyError(msg)
model = model_class.load(**self.model_kwargs, verbose=True)
models = getattr(model, 'models', [model])
self.s_enhancements = [model.s_enhance for model in models]
self.t_enhancements = [model.t_enhance for model in models]
self.s_enhance = np.prod(self.s_enhancements)
self.t_enhance = np.prod(self.t_enhancements)
self.output_features = model.hr_out_features
assert len(self.output_features) > 0, 'No output features!'
self.fwp_slicer = ForwardPassSlicer(self.grid_shape,
self.raw_tsteps,
self.temporal_slice,
self.fwp_chunk_shape,
self.s_enhancements,
self.t_enhancements,
self.spatial_pad,
self.temporal_pad)
DistributedProcess.__init__(self,
max_nodes=max_nodes,
max_chunks=self.fwp_slicer.n_chunks,
incremental=self.incremental)
self.preflight()
def init_mixin(self):
"""Initialize InputMixIn class"""
target = self._input_handler_kwargs.get('target', None)
grid_shape = self._input_handler_kwargs.get('shape', None)
raster_file = self._input_handler_kwargs.get('raster_file', None)
raster_index = self._input_handler_kwargs.get('raster_index', None)
temporal_slice = self._input_handler_kwargs.get(
'temporal_slice', slice(None, None, 1))
res_kwargs = self._input_handler_kwargs.get('res_kwargs', None)
InputMixIn.__init__(self,
target=target,
shape=grid_shape,
raster_file=raster_file,
raster_index=raster_index,
temporal_slice=temporal_slice,
res_kwargs=res_kwargs)
def preflight(self):
"""Prelight path name formatting and sanity checks"""
logger.info('Initializing ForwardPassStrategy. '
f'Using n_nodes={self.nodes} with '
f'n_spatial_chunks={self.fwp_slicer.n_spatial_chunks}, '
f'n_temporal_chunks={self.fwp_slicer.n_temporal_chunks}, '
f'and n_total_chunks={self.chunks}. '
f'{self.chunks / self.nodes:.3f} chunks per node on '
'average.')
logger.info(f'Using max_workers={self.max_workers}, '
f'pass_workers={self.pass_workers}, '
f'output_workers={self.output_workers}')
out = self.fwp_slicer.get_temporal_slices()
self.ti_slices, self.ti_pad_slices = out
msg = ('Using a padded chunk size '
f'({self.fwp_chunk_shape[2] + 2 * self.temporal_pad}) '
f'larger than the full temporal domain ({self.raw_tsteps}). '
'Should just run without temporal chunking. ')
if self.fwp_chunk_shape[2] + 2 * self.temporal_pad >= self.raw_tsteps:
logger.warning(msg)
warnings.warn(msg)
hr_data_shape = (self.grid_shape[0] * self.s_enhance,
self.grid_shape[1] * self.s_enhance,
)
self.gids = np.arange(np.prod(hr_data_shape))
self.gids = self.gids.reshape(hr_data_shape)
out = self.fwp_slicer.get_spatial_slices()
self.lr_slices, self.lr_pad_slices, self.hr_slices = out
def _get_spatial_chunk_index(self, chunk_index):
"""Get the spatial index for the given chunk index"""
return chunk_index % self.fwp_slicer.n_spatial_chunks
def _get_temporal_chunk_index(self, chunk_index):
"""Get the temporal index for the given chunk index"""
return chunk_index // self.fwp_slicer.n_spatial_chunks
# pylint: disable=E1102
@property
def init_handler(self):
"""Get initial input handler used for extracting handler features and
low res grid"""
if self._init_handler is None:
out = self.input_handler_class(self.file_paths[0], [],
target=self.target,
shape=self.grid_shape,
worker_kwargs={"ti_workers": 1})
self._init_handler = out
return self._init_handler
@property
def lr_lat_lon(self):
"""Get low resolution lat lons for input entire grid"""
if self._lr_lat_lon is None:
logger.info('Getting low-resolution grid for full input domain.')
self._lr_lat_lon = self.init_handler.lat_lon
return self._lr_lat_lon
@property
def handle_features(self):
"""Get list of features available in the source data"""
if self._handle_features is None:
if self.single_ts_files:
self._handle_features = self.init_handler.handle_features
else:
hf = self.input_handler_class.get_handle_features(
self.file_paths)
self._handle_features = hf
return self._handle_features
@property
def hr_lat_lon(self):
"""Get high resolution lat lons"""
if self._hr_lat_lon is None:
logger.info('Getting high-resolution grid for full output domain.')
lr_lat_lon = self.lr_lat_lon.copy()
self._hr_lat_lon = OutputHandler.get_lat_lon(
lr_lat_lon, self.gids.shape)
return self._hr_lat_lon
def get_full_domain(self, file_paths):
"""Get target and grid_shape for largest possible domain"""
return self.input_handler_class.get_full_domain(file_paths)
def get_lat_lon(self, file_paths, raster_index, invert_lat=False):
"""Get lat/lon grid for requested target and shape"""
return self.input_handler_class.get_lat_lon(file_paths,
raster_index,
invert_lat=invert_lat)
def get_time_index(self, file_paths, max_workers=None, **kwargs):
"""Get time index for source data using DataHandler.get_time_index
method
Parameters
----------
file_paths : list
List of file paths for source data
max_workers : int | None
Number of workers to use to extract the time index from the given
files. This is used when a large number of single timestep netcdf
files is provided.
**kwargs : dict
Dictionary of kwargs passed to the resource handler opening the
given file_paths. For netcdf files this is xarray.open_mfdataset().
For h5 files this is usually rex.Resource().
Returns
-------
time_index : ndarray
Array of time indices for source data
"""
return self.input_handler_class.get_time_index(file_paths,
max_workers=max_workers,
**kwargs)
@property
def file_ids(self):
"""Get file id for each output file
Returns
-------
_file_ids : list
List of file ids for each output file. Will be used to name output
files of the form filename_{file_id}.ext
"""
if not self._file_ids:
self._file_ids = []
for i in range(self.fwp_slicer.n_temporal_chunks):
for j in range(self.fwp_slicer.n_spatial_chunks):
file_id = f'{str(i).zfill(6)}_{str(j).zfill(6)}'
self._file_ids.append(file_id)
return self._file_ids
@property
def out_files(self):
"""Get output file names for forward pass output
Returns
-------
_out_files : list
List of output files for forward pass output data
"""
if self._out_files is None:
self._out_files = self.get_output_file_names(
out_files=self.out_pattern, file_ids=self.file_ids)
return self._out_files
@property
def input_type(self):
"""Get input data type
Returns
-------
input_type
e.g. 'nc' or 'h5'
"""
return get_source_type(self.file_paths)
@property
def output_type(self):
"""Get output data type
Returns
-------
output_type
e.g. 'nc' or 'h5'
"""
return get_source_type(self.out_pattern)
@property
def input_handler_class(self):
"""Get data handler class used to handle input
Returns
-------
_handler_class
e.g. DataHandlerNC, DataHandlerH5, etc
"""
if self._input_handler_class is None: