-
Notifications
You must be signed in to change notification settings - Fork 8
/
forward_pass.py
1703 lines (1506 loc) · 71 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 json
import numpy as np
import logging
import os
import warnings
import copy
from datetime import datetime as dt
import psutil
from inspect import signature
from rex.utilities.fun_utils import get_fun_call_str
from rex.utilities.execution import SpawnProcessPool
import sup3r.models
import sup3r.bias.bias_transforms
from sup3r.preprocessing.data_handling import InputMixIn
from sup3r.preprocessing.exogenous_data_handling import ExogenousDataHandler
from sup3r.postprocessing.file_handling import (OutputHandlerH5,
OutputHandlerNC)
from sup3r.utilities.utilities import (get_chunk_slices,
get_source_type,
get_input_handler_class)
from sup3r.utilities import ModuleName
from concurrent.futures import as_completed
np.random.seed(42)
logger = logging.getLogger(__name__)
class ForwardPassSlicer:
"""Get slices for sending data chunks through model."""
def __init__(self, coarse_shape, time_index, 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_index : pd.Datetimeindex
Time index for full temporal domain of low res data
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 factor by which the Sup3rGan model will enhance the spatial
dimensions of low resolution data
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.
exo_s_enhancements : list
List of spatial enhancement steps specific to the exogenous_data
inputs. This differs from s_enhancements in that s_enhancements[0]
will be the spatial enhancement of the first model, but
exo_s_enhancements[0] may be 1 to signify exo data is required for
the first non-enhanced spatial input resolution.
"""
self.grid_shape = coarse_shape
self.s_enhancements = s_enhancements
self.t_enhancements = t_enhancements
self.s_enhance = np.product(self.s_enhancements)
self.t_enhance = np.product(self.t_enhancements)
self.raw_time_index = time_index
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._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 raw_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, len(self.raw_time_index), 1,
self.temporal_pad, self.temporal_slice.step)
return self._t_lr_pad_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 = []
for s in self.s_hr_crop_slices:
node_slices.append((s[0], s[1], t, slice(None)))
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.raw_time_index[self.temporal_slice])
n_chunks = n_tsteps / self.chunk_shape[2]
n_chunks = np.int(np.ceil(n_chunks))
ti_slices = np.arange(len(self.raw_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
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):
"""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,
max_workers=None,
output_workers=None,
exo_kwargs=None,
pass_workers=1,
bias_correct_method=None,
bias_correct_kwargs=None,
max_nodes=None):
"""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
kwargs for initializing the input_handler class
:class:`sup3r.preprocessing.data_handling.DataHandler`. These
kwargs include temporal_slice, target, shape used to define the
spatiotemporal domain sent through the forward passes.
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).
max_workers : int | None
Providing a value for max workers will be used to set the value of
extract_workers, compute_workers, output_workers, and load_workers.
If max_workers == 1 then all processes will be serialized. If None
extract_workers, compute_workers, load_workers, output_workers will
use their own provided values.
output_workers : int | None
max number of workers to use for writing forward pass output.
pass_workers : int | None
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.
exo_kwargs : dict | None
Dictionary of args to pass to :class:
`sup3r.preprocessing.exogeneous_data_handling.ExogenousDataHandler`
for extracting exogenous features such as topography for future
multistep foward pass
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.
"""
self._i = 0
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.max_workers = max_workers
self.output_workers = output_workers
self.pass_workers = pass_workers
self.exo_kwargs = exo_kwargs or {}
self.incremental = incremental
self._single_time_step_files = None
self._input_handler_class = None
self._input_handler_name = input_handler
self._max_nodes = max_nodes
self._input_handler_kwargs = input_handler_kwargs or {}
self._time_index = None
self._raw_time_index = None
self._out_files = None
self._file_ids = None
self._time_index_file = None
self._node_chunks = None
self.incremental = incremental
self.bias_correct_method = bias_correct_method
self.bias_correct_kwargs = bias_correct_kwargs or {}
self._target = input_handler_kwargs.get('target', None)
self._grid_shape = input_handler_kwargs.get('shape', None)
self.raster_file = input_handler_kwargs.get('raster_file', None)
self.temporal_slice = input_handler_kwargs.get('temporal_slice',
slice(None))
self.time_chunk_size = input_handler_kwargs.get('time_chunk_size',
None)
self.overwrite_cache = input_handler_kwargs.get('overwrite_cache',
False)
self.overwrite_ti_cache = input_handler_kwargs.get(
'overwrite_ti_cache', False)
self.extract_workers = input_handler_kwargs.get('extract_workers',
None)
self.compute_workers = input_handler_kwargs.get('compute_workers',
None)
self.load_workers = input_handler_kwargs.get('load_workers', None)
self.ti_workers = input_handler_kwargs.get('ti_workers', None)
self._cache_pattern = input_handler_kwargs.get('cache_pattern', None)
self.cap_worker_args(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.product(self.s_enhancements)
self.t_enhance = np.product(self.t_enhancements)
self.fwp_slicer = ForwardPassSlicer(self.grid_shape,
self.raw_time_index,
self.temporal_slice,
self.fwp_chunk_shape,
self.s_enhancements,
self.t_enhancements,
self.spatial_pad,
self.temporal_pad)
logger.info('Initializing ForwardPassStrategy for '
f'{self.input_file_info}. 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} chunks per node on average.')
logger.info(f'Using max_workers={self.max_workers}, '
f'extract_workers={self.extract_workers}, '
f'compute_workers={self.compute_workers}, '
f'pass_workers={self.pass_workers}, '
f'load_workers={self.load_workers}, '
f'output_workers={self.output_workers}, '
f'ti_workers={self.ti_workers}')
self.preflight()
@property
def worker_attrs(self):
"""Get all worker args defined in init"""
return ['ti_workers', 'compute_workers', 'pass_workers',
'load_workers', 'output_workers', 'extract_workers']
def preflight(self):
"""Prelight path name formatting and sanity checks"""
if self.cache_pattern is not None:
if '{temporal_chunk_index}' not in self.cache_pattern:
self.cache_pattern = self.cache_pattern.replace(
'.pkl', '_{temporal_chunk_index}.pkl')
if '{spatial_chunk_index}' not in self.cache_pattern:
self.cache_pattern = self.cache_pattern.replace(
'.pkl', '_{spatial_chunk_index}.pkl')
if self.raster_file is not None:
if '{spatial_chunk_index}' not in self.raster_file:
self.raster_file = self.raster_file.replace(
'.txt', '_{spatial_chunk_index}.txt')
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}) '
'larger than the full temporal domain '
f'({len(self.raw_time_index)}). Should just run without '
'temporal chunking. ')
if (self.fwp_chunk_shape[2] + 2 * self.temporal_pad
>= len(self.raw_time_index)):
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.product(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
# pylint: disable=E1102
logger.info('Getting lat/lon for entire forward pass domain.')
out = self.input_handler_class(self.file_paths[0], [],
target=self.target,
shape=self.grid_shape, ti_workers=1)
self.lr_lat_lon = out.lat_lon
self.invert_lat = out.invert_lat
self.single_time_step_files = self.is_single_ts_files()
if self.single_time_step_files:
self.handle_features = out.handle_features
else:
hf = self.input_handler_class.get_handle_features(self.file_paths)
self.handle_features = hf
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_time_index(self, file_paths, max_workers=None):
"""Get time index for source data
Parameters
----------
file_paths : list
List of file paths for source data
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)
def is_single_ts_files(self):
"""Check if there is a file for each time step, in which case we can
send a subset of files to the data handler according to ti_pad_slice"""
if self._single_time_step_files is None:
t_steps = self.input_handler_class.get_time_index(
self.file_paths[:1], max_workers=1)
check = (len(self._file_paths) == len(self.raw_time_index)
and t_steps is not None and len(t_steps) == 1)
self._single_time_step_files = check
return self._single_time_step_files
@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):
check = (self.out_pattern is not None
and '{times}' in self.out_pattern)
if check:
ti = self.raw_time_index[self.ti_slices[i]]
start = str(ti[0]).strip('+').strip('-').strip(':')
start = ''.join(start.split(' '))
end = str(ti[-1]).strip('+').strip('-').strip(':')
end = ''.join(end.split(' '))
file_id = f'{start}-{end}_{str(j).zfill(6)}'
self._file_ids.append(file_id)
else:
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:
self._input_handler_class = get_input_handler_class(
self.file_paths, self._input_handler_name)
return self._input_handler_class
def __len__(self):
"""Get the number of nodes that this strategy is distributing to"""
return self.fwp_slicer.n_chunks
@property
def max_nodes(self):
"""Get the maximum number of nodes that this strategy should distribute
work to, equal to either the specified max number of nodes or total
number of temporal chunks"""
nodes = (self._max_nodes if self._max_nodes is not None
else self.fwp_slicer.n_temporal_chunks)
nodes = np.min((nodes, self.chunks))
return nodes
@property
def nodes(self):
"""Get the number of nodes that this strategy should distribute work
to, equal to either the specified max number of nodes or total number
of temporal chunks"""
return len(self.node_chunks)
@property
def chunks(self):
"""Get the number of spatiotemporal chunks going through forward pass,
calculated as the source time index divided by the temporal part of the
fwp_chunk_shape times the number of spatial chunks"""
return self.fwp_slicer.n_chunks
@property
def node_chunks(self):
"""Get chunked list of spatiotemporal chunk indices that will be
used to distribute sets of spatiotemporal chunks across nodes. For
example, if we want to distribute 10 spatiotemporal chunks across 2
nodes this will return [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]. So the first
node will be used to run forward passes on the first 5 spatiotemporal
chunks and the second node will be used for the last 5"""
if self._node_chunks is None:
n_chunks = np.min((self.max_nodes, self.chunks))
self._node_chunks = np.array_split(np.arange(self.chunks),
n_chunks)
return self._node_chunks
@staticmethod
def get_output_file_names(out_files, file_ids):
"""Get output file names for each file chunk forward pass
Parameters
----------
out_files : str
Output file pattern. Should be of the form
/<path>/<name>_{file_id}.<ext>. e.g. /tmp/fp_out_{file_id}.h5.
Each output file will have a unique file_id filled in and the ext
determines the output type.
file_ids : list
List of file ids for each output file. e.g. date range
Returns
-------
list
List of output file paths
"""
out_file_list = []
if out_files is not None:
if '{times}' in out_files:
out_files = out_files.replace('{times}', '{file_id}')
if '{file_id}' not in out_files:
out_files = out_files.split('.')
tmp = '.'.join(out_files[:-1]) + '_{file_id}'
tmp += '.' + out_files[-1]
out_files = tmp
dirname = os.path.dirname(out_files)
if not os.path.exists(dirname):
os.makedirs(dirname, exist_ok=True)
for file_id in file_ids:
out_file = out_files.replace('{file_id}', file_id)
out_file_list.append(out_file)
else:
out_file_list = [None] * len(file_ids)
return out_file_list
class ForwardPass:
"""Class to run forward passes on all chunks provided by the given
ForwardPassStrategy. The chunks provided by the strategy are all passed
through the GAN generator to produce high resolution output.
"""
def __init__(self, strategy, chunk_index=0, node_index=0):
"""Initialize ForwardPass with ForwardPassStrategy. The stragegy
provides the data chunks to run forward passes on
Parameters