-
Notifications
You must be signed in to change notification settings - Fork 0
/
tpu_simulation_utilities.py
2822 lines (2372 loc) · 111 KB
/
tpu_simulation_utilities.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
# Floating point tolerance for timesteps.
TIMESTEP_EPS = 1e-5
# Floating point tolerance used in Saint-Venant step function.
SAINT_VENANT_EPS = 1e-1
CUTOFF_MAX = 1e15
_G = 9.8
# Manning coefficient defaults. NB: The simulation can be more accurate if a
# river mask is provided which defines th river region of the DEM. In that case,
# `MANNING_COEFF_FLOODPLAIN` is used in the non-river region (i.e., the
# floodplain region). In the Conawy example, we take a simpler approach and use
# `np.ones()` for the river mask, so `MANNING_COEFF_FLOODPLAIN` is unused.
MANNING_COEFF_FLOODPLAIN = .02
MANNING_COEFF_RIVER = .05
MANNING_COEFF = .0
# The dynamic states are:
# h: the absolute height
# q_x: The water flow in the x direction.
# q_y: The water flow in the y direction.
# t: The current simulation time.
# dt: The timestep size. Note that `dt` is held constant in this simulation.
_H = 'h'
_Q_X = 'q_x'
_U_PREV = 'u_prev'
_Q_Y = 'q_y'
_V_PREV = 'v_prev'
_T = 't'
_DT = 'dt'
INIT_STATE_KEYS = [_H, _Q_X, _Q_Y]
STATE_KEYS = INIT_STATE_KEYS + [_T, _DT]
# The static states are:
# m: The Manning coefficient matrix.
# e: The water bed elevation.
# We also specify the boundaries using {L,R,T,B}_BOUNDARIES.
_M = 'm'
_E = 'e'
_I_L_BOUNDARY = 'i_left_boundary'
_I_R_BOUNDARY = 'i_right_boundary'
_I_T_BOUNDARY = 'i_top_boundary'
_I_B_BOUNDARY = 'i_bottom_boundary'
_O_L_BOUNDARY = 'o_left_boundary'
_O_R_BOUNDARY = 'o_right_boundary'
_O_T_BOUNDARY = 'o_top_boundary'
_O_B_BOUNDARY = 'o_bottom_boundary'
_M_L_BOUNDARY = 'm_left_boundary'
_M_R_BOUNDARY = 'm_right_boundary'
_M_T_BOUNDARY = 'm_top_boundary'
_M_B_BOUNDARY = 'm_bottom_boundary'
L_BOUNDARIES = (_I_L_BOUNDARY, _M_L_BOUNDARY, _O_L_BOUNDARY)
R_BOUNDARIES = (_I_R_BOUNDARY, _M_R_BOUNDARY, _O_R_BOUNDARY)
T_BOUNDARIES = (_I_T_BOUNDARY, _M_T_BOUNDARY, _O_T_BOUNDARY)
B_BOUNDARIES = (_I_B_BOUNDARY, _M_B_BOUNDARY, _O_B_BOUNDARY)
ADDITIONAL_STATE_KEYS = [
_M, _E, *L_BOUNDARIES, *R_BOUNDARIES, *T_BOUNDARIES, *B_BOUNDARIES
]
SER_EXTENSION = 'ser'
from scipy.linalg.decomp_qr import qr_multiply
"""Runs TPU Saint-Venant Simulations."""
from user_constants import *
if PUBLIC_COLAB:
# Authenticate to access Google Cloud Storage.
from google.colab import auth # pylint: disable=g-import-not-at-top
auth.authenticate_user()
# Access DEM from Google Cloud Storage and use GCS for runtime files.
#----------------------------------------------------------------------------
# Let M be the extent in y, and let N be the extent in x for calculating FLOP
#----------------------------------------------------------------------------
import abc
import collections
import enum
import functools
import io
import sys
from matplotlib.colors import LightSource
import matplotlib.pyplot as plt
import os
from skimage import transform
import tempfile
import time
from typing import Any, Callable, Iterable, Sequence, List, Dict, Mapping, MutableMapping, MutableSequence, Optional, Text, Tuple, Union
from scipy.signal import convolve2d
import attr
import numpy as np
import scipy.interpolate
import tensorflow.compat.v1 as tf
#tf.disable_v2_behavior()
if PUBLIC_COLAB:
from google.cloud import storage # pylint: disable=g-import-not-at-top
import ipywidgets as widgets # pylint: disable=g-import-not-at-top
from osgeo import gdal # pylint: disable=g-import-not-at-top
if PUBLIC_COLAB:
from tensorflow.python.ops import gen_resource_variable_ops # pylint: disable=g-import-not-at-top
from tensorflow.python.ops import inplace_ops # pylint: disable=g-import-not-at-top
from tensorflow.python.tpu.ops import tpu_ops # pylint: disable=g-import-not-at-top
TensorMap = Mapping[Text, tf.Tensor]
TensorOrArray = Union[tf.Tensor, np.ndarray]
ThreeIntTuple = Tuple[int, int, int]
ExtractSubgridFn = Callable[[TensorOrArray,
'GridParametrization',
ThreeIntTuple], TensorOrArray]
MutableTensorMap = MutableMapping[Text, tf.Tensor]
FnOutput = Tuple[List[tf.Tensor], MutableTensorMap]
StepOutput = List[List[tf.Tensor]]
StepBuilder = Callable[[], StepOutput]
KeyedInitialValues = Mapping[Text, Union[int, float, complex, Text, bool,
np.ndarray, tf.Tensor]]
MutableKeyedInitialValues = MutableMapping[Text,
Union[int, float, complex, Text,
bool, np.ndarray, tf.Tensor]]
InputFiles = collections.namedtuple('InputFiles', ['file_name', 'dtype'])
class BoundarySide(enum.IntEnum):
"""A representation of boundary sides."""
LEFT = 0
RIGHT = 1
TOP = 2
BOTTOM = 3
class SideType(enum.Enum):
"""A class defining the type of axis side."""
LOW = 1 # The low side of an axis.
HIGH = 2 # The high side of an axis.
class BCType(enum.Enum):
"""A class defining the type of boundary conditions.
NO_TOUCH: Preserves the boundary at its current value: useful when the grid is
staggered. Namely, if certain state variables are defined and computed only
for interior grid points, their extremal values are already correct and do
not need to be re-calculated/have a boundary condition imposed outside of
the computation loop.
ADDITIVE: Similar to a Neumann condition, but adds the supplied boundary
values to the boundary plane itself, as opposed to the plane +/- 1.
"""
NO_TOUCH = 1 # Preserves the boundary at its current value.
ADDITIVE = 2 # Adds the given values at the boundary.
FREE = 3
class BoundaryCondition:
"""The base class for boundary conditions."""
def __init__(self,
boundary_side: BoundarySide,
fraction_start: float,
fraction_end: float,
left_padding: int,
top_padding: int,
unpadded_shape: Sequence[int],
slope: float):
self.boundary_side = boundary_side
self.slope = slope
self._top_bottom = boundary_side in [BoundarySide.TOP, BoundarySide.BOTTOM]
self.unpadded_side_length = unpadded_shape[int(self._top_bottom)]
self._unpadded_index_start = int(round(
fraction_start * (self.unpadded_side_length - 1)))
self._unpadded_index_end = 1 + int(round(
fraction_end * (self.unpadded_side_length - 1)))
self._unpadded_xsec_slice = self._boundary_slice()
self.padded_xsec_slice = self._boundary_slice(left_padding, top_padding)
self.padded_full_slice = self._padded_full_boundary_slice(left_padding,
top_padding)
def add_padding_fn(xsec, ones=False):
return self._add_padding(xsec, ones, left_padding, top_padding)
self.add_padding = add_padding_fn
def _add_padding(self, xsec: np.ndarray, ones: bool,
left_padding: int, top_padding: int) -> np.ndarray:
padding = left_padding if self._top_bottom else top_padding
zeros_ones = np.ones if ones else np.zeros
one_d_padded = np.concatenate([
zeros_ones(padding + self._unpadded_index_start),
np.squeeze(xsec),
zeros_ones(self.unpadded_side_length - self._unpadded_index_end)])
axis = int(not self._top_bottom)
return np.expand_dims(one_d_padded, axis).astype(np.float32)
def _boundary_slice(self, left_padding: int = 0, top_padding: int = 0):
"""Returns a 1D boundary slice."""
padding = padding = left_padding if self._top_bottom else top_padding
maybe_padded_xsec_slice = slice(padding + self._unpadded_index_start,
padding + self._unpadded_index_end)
if self.boundary_side == BoundarySide.LEFT:
return (maybe_padded_xsec_slice, left_padding)
elif self.boundary_side == BoundarySide.RIGHT:
return (maybe_padded_xsec_slice, -1)
elif self.boundary_side == BoundarySide.TOP:
return (top_padding, maybe_padded_xsec_slice)
elif self.boundary_side == BoundarySide.BOTTOM:
return (-1, maybe_padded_xsec_slice)
def _padded_full_boundary_slice(
self, left_padding: int = 0, top_padding: int = 0):
if self.boundary_side == BoundarySide.LEFT:
return (slice(None), slice(left_padding, left_padding + 1))
elif self.boundary_side == BoundarySide.RIGHT:
return (slice(None), slice(-1, None))
elif self.boundary_side == BoundarySide.TOP:
return (slice(top_padding, top_padding + 1), slice(None))
elif self.boundary_side == BoundarySide.BOTTOM:
return (slice(-1, None), slice(None))
class DirichletBoundary(BoundaryCondition):
def __init__(self,
boundary_side: BoundarySide,
fraction_start: float,
fraction_end: float,
left_padding: int,
top_padding: int,
slope: float,
value: float,
unpadded_dem: np.ndarray,
unpadded_manning_matrix: np.ndarray):
super(DirichletBoundary, self).__init__(boundary_side,
fraction_start,
fraction_end,
left_padding,
top_padding,
unpadded_dem.shape,
slope)
self.bc_type = BCType.NO_TOUCH
self.value = value
class NeumannBoundary(BoundaryCondition):
def __init__(self,
boundary_side: BoundarySide,
fraction_start: float,
fraction_end: float,
left_padding: int,
top_padding: int,
slope: float,
value: float,
unpadded_dem: np.ndarray,
unpadded_manning_matrix: np.ndarray):
super(NeumannBoundary, self).__init__(boundary_side,
fraction_start,
fraction_end,
left_padding,
top_padding,
unpadded_dem.shape,
slope)
self.bc_type = BCType.ADDITIVE
self.value = value
def _do_exchange(replicas, replica_dim, high_halo_for_predecessor,
low_halo_for_successor):
"""Does a halo exchange with predecessors/successors."""
# Special case for single replica grid width along the replica_dim.
if replicas.shape[replica_dim] == 1:
return [tf.zeros_like(high_halo_for_predecessor)] * 2
# Compute the predecessor and successor replicas in `replica_dim`.
padded_replicas = pad_in_dim(
replicas, low_pad=1, high_pad=1, value=-1, axis=replica_dim)
predecessors = np.stack(
(replicas, slice_in_dim(
padded_replicas, start=0, end=-2, axis=replica_dim)),
axis=-1)
predecessors = [(a, b) for (a, b) in predecessors.reshape((-1, 2)) if b != -1]
high_halo = tpu_ops.collective_permute(high_halo_for_predecessor,
predecessors, 'high')
successors = np.stack(
(replicas,
slice_in_dim(padded_replicas, start=2, end=None, axis=replica_dim)),
axis=-1)
successors = [(a, b) for (a, b) in successors.reshape((-1, 2)) if b != -1]
low_halo = tpu_ops.collective_permute(low_halo_for_successor, successors,
'low')
return high_halo, low_halo
def _reduce_LF_Max(replica_id, array, num_cores):
if num_cores == 1:
return array
arr = tf.ones([num_cores, 1]) * array
arr = tpu_ops.all_to_all(arr,
0,
0,
num_cores)
arr = tf.math.reduce_max(arr, axis=0)
return arr
def _replace_halo(plane, bc, dim):
"""Return a halo derived from boundary conditions.
This should only be called if all the following are true:
* `bc` is not `None`
* the replica is at the end of the dimension on the specified side in the
computational shape
Args:
plane: A 2D tensor. The plane from the subgrid relevant in applying boundary
conditions (and to get the shape for Dirichlet boundary conditions).
bc: The boundary conditions specification of the form [type, value]. See
`inplace_halo_exchange` for full details about boundary condition
specifications.
dim: The dimension (aka axis), 0, 1 or 2 for x, y or z, respectively.
Returns:
The border which is derived from the provided boundary conditions.
Raises:
ValueError if parameters have incorrect values.
"""
if not isinstance(bc, collections.Sequence):
raise ValueError('`bc` must be a sequence `(type, value)`.')
bc_type, bc_value = bc
# bc_value could be a list of tensors of shape (1, ny) or (nx, 1). If so,
# convert to a tensor of shape (nz, ny) or (nx, nz). nx, ny, nz are the number
# of points along each axis of a (sub)grid. After this line, bc_value is
# either a float or a 2D tensor.
bc_value = (
tf.concat(bc_value, dim) if isinstance(bc_value, list) else bc_value)
def additive_value():
return plane + bc_value
if bc_type == BCType.ADDITIVE:
return additive_value()
else:
raise ValueError('Unknown boundary condition type: {}.'.format(bc_type))
def _sliced_tensor_fn(tensor, slices):
return lambda: tensor[tuple(slices)]
def _halo_from_self_dim_0_1(z_list, dim, plane_to_exchange, is_first,
left_or_top_padding):
"""Returns halos from the z_list given the dimension and plane to exchange."""
if dim not in [0, 1]:
raise ValueError('dim not in [0, 1]: {}'.format(dim))
low_slices, low_slices_padded, high_slices = ([slice(None)] * 2 ,
[slice(None)] * 2,
[slice(None)] * 2 )
low_slices[dim] = slice(plane_to_exchange, plane_to_exchange + 1)
low_slices_padded[dim] = slice(plane_to_exchange + left_or_top_padding,
plane_to_exchange + left_or_top_padding + 1)
shape = z_list[0].shape.as_list()[dim]
high_slices[dim] = slice(shape - (plane_to_exchange + 1),
shape - plane_to_exchange)
low_halo_from_self, high_halo_from_self = [], []
for tensor in z_list:
low_halo = tf.cond(is_first, _sliced_tensor_fn(tensor, low_slices_padded),
_sliced_tensor_fn(tensor, low_slices))
low_halo_from_self.append(low_halo)
high_halo_from_self.append(tensor[high_slices])
# Convert to 2D tensor: a z-y or x-z plane.
low_halo_from_self = _convert_zlist_to_2d_tensor(low_halo_from_self, dim)
high_halo_from_self = _convert_zlist_to_2d_tensor(high_halo_from_self, dim)
return low_halo_from_self, high_halo_from_self
def _convert_zlist_to_2d_tensor(list_of_tensors, dim):
return tf.concat(list_of_tensors, dim)
def _convert_2d_tensor_to_zlist(tensor, dim):
nz = tensor.shape.as_list()[dim]
return tf.split(tensor, nz, dim)
def _alias_inplace_update(x, plane, low):
return lambda: inplace_ops.alias_inplace_update(x, plane, tf.squeeze(low))
def _inplace_halo_exchange_1d(z_list, dim, replica_id, replicas, replica_dim,
bc_low, bc_high, left_or_top_padding):
"""Performs halo exchange and assigns values to points in a boundary plane.
This function exchanges and sets a single plane in the boundary or halo
region. It needs to be called for each plane in the boundary or halo region,
in order, from the innermost to outermost.
Args:
z_list: A list of length nz of tensors of shape (nx, ny), where nx, ny and
nz are the number of points along the axes of a (sub)grid.
dim: The dimension of `z_list` in which halo exchange will be performed.
Must be one of 0, 1 or 2 for x, y or z, respectively.
replica_id: The replica id.
replicas: A numpy array of replicas.
replica_dim: The dimension of `replicas` along which the halo exchange is to
be performed.
bc_low: The boundary condition for the low side of the axis. This is either
`None` or of the form `(bc_type, bc_value)` where `bc_value` represents a
single 2D plane and is either a 2D tensor of shape (nx, xy) or a sequence
of length nz of tensors of shape (1, ny) or (nx, 1). See
`inplace_halo_exchange` for more details about boundary condition
specifications.
bc_high: The boundary condition for the high side of the axis. See `bc_low`.
left_or_top_padding: The amount of left or top padding, where left and top
refer to the 2d plane formed by dims 0 and 1. This is used only if `dim`
is 0 or 1.
Returns:
The `z_list` with its `plane` boundary on the low side and corresponding
plane on the high side in the `dim` dimension modified by the halos of its
neighbors and/or boundary conditions.
Raises:
ValueError if parameters are incorrect.
"""
assert dim in (0, 1, 2)
tf.logging.debug('dim: %d, replica_dim: %d, bc_low: %s, bc_high: %s', dim,
replica_dim, bc_low, bc_high)
is_first = is_first_replica(replica_id, replicas, replica_dim)
is_last = is_last_replica(replica_id, replicas, replica_dim)
def maybe_replace_halo_from_boundary_conditions(side):
"""Maybe return 2D plane from boundary conditions rather than neighbor."""
def low_from_bc():
if bc_low[0] == BCType.NO_TOUCH:
return tf.ones_like(low_plane_for_outermost_slice)*bc_low[1]
elif bc_low[0] == BCType.FREE:
return low_plane_for_outermost_slice
else: # BCType.ADDITIVE
return _replace_halo(low_plane_for_outermost_slice, bc_low, 1)
def high_from_bc():
if bc_high[0] == BCType.NO_TOUCH:
return tf.ones_like(high_plane_for_outermost_slice)*bc_high[1]
elif bc_high[0] == BCType.FREE:
return high_plane_for_outermost_slice
else: # BCType.ADDITIVE
return _replace_halo(high_plane_for_outermost_slice, bc_high, 1)
if side == SideType.LOW:
# `tf.cond` is potentially expensive as it evaluates the input of both
# branches. The `if/else` statement can optimize performance by
# eliminating an unnecessary `tf.cond` from the graph.
return tf.cond(is_first, low_from_bc, lambda: low_halo_from_neighbor)
else: # side = HIGH
return tf.cond(is_last, high_from_bc, lambda: high_halo_from_neighbor)
plane_to_exchange = 1
# dim in (0, 1).
low_halo_from_self, high_halo_from_self = _halo_from_self_dim_0_1(
z_list, dim, plane_to_exchange, is_first, left_or_top_padding)
high_halo_from_neighbor, low_halo_from_neighbor = _do_exchange(
replicas, replica_dim, low_halo_from_self, high_halo_from_self)
low_plane_for_outermost_slice, high_plane_for_outermost_slice = (
_halo_from_self_dim_0_1(z_list, dim, plane_to_exchange - 1, is_first,
left_or_top_padding))
low_edge = maybe_replace_halo_from_boundary_conditions(SideType.LOW)
high_edge = maybe_replace_halo_from_boundary_conditions(SideType.HIGH)
high_edges = _convert_2d_tensor_to_zlist(high_edge, dim)
low_edges = _convert_2d_tensor_to_zlist(low_edge, dim)
result_list = []
plane_padded = left_or_top_padding
for x, high, low in zip(z_list, high_edges, low_edges):
if dim == 0:
x = inplace_ops.alias_inplace_update(
tf.cond(is_first, _alias_inplace_update(x, plane_padded, low),
_alias_inplace_update(x, 0, low)),
x.shape.as_list()[0] - 1, tf.squeeze(high))
else:
x = tf.transpose(
inplace_ops.alias_inplace_update(
tf.cond(
is_first,
_alias_inplace_update(
tf.transpose(x, [1, 0]), plane_padded, low),
_alias_inplace_update(tf.transpose(x, [1, 0]), 0, low)),
x.shape.as_list()[1] - 1, tf.squeeze(high)), [1, 0])
result_list.append(x)
return result_list
def inplace_halo_exchange(z_list: List[tf.Tensor],
dims: Sequence[int],
replica_id: tf.Tensor,
replicas: np.ndarray,
replica_dims: Sequence[int],
boundary_conditions=None,
left_padding: int = 0,
top_padding: int = 0) -> List[tf.Tensor]:
"""Performs a N-dimensional halo exchange.
Args:
z_list: A list of length nz of tensors of shape `(nx, ny)`, where `nx`,
`ny` and `nz` are the number of points along the axes of a (sub)grid.
dims: The dimensions or axes along which halo exchange will be performed.
This is a sequence containing some or all of 0, 1, 2 (corresponding to
`x`, `y`, `z`).
replica_id: The replica id.
replicas: A numpy array of replicas.
replica_dims: The dimensions of `replicas` along which halo exchange will be
performed.
boundary_conditions: The boundary conditions to apply. If `None`, the
boundary will be set to 0. See more info about boundary conditions below.
left_padding: The amount of left padding, referring the 2d plane formed by
dims 0 and 1 (left is dim 1).
top_padding: The amount of top padding, referring to the 2d plane formed by
dims 0 and 1 (top is dim 0). If boundary_conditions is not `None` it must
have the form [ [(`BCType` for dim 0 lower bound, value for dim 0 lower
bound), (`BCType` for dim 0 upper bound, value for dim 0 upper bound)],
[(`BCType` for dim1 lower bound, value for dim 1 lower bound), (`BCType`
for dim1 upper bound, value for dim 1 upper bound)], ... ]. Note that the
innermost sequence can be `None`, in which case the corresponding boundary
will be set to zero. The value can be a float, or can be a sequence of
planes of length 1. An element of this sequence is a tensor if
dim = 2 (z-axis) and a sequence if dim is 0 or 1. A z-axis boundary plane
is specified by a 2D tensor of shape `(nx, ny)`. A 2D x- or y-axis
boundary plane is specified by a list of length nz of tensors of shape
(1, `ny`) or (`nx`, 1), respectively. The order of planes in the sequence
is from low to high along the dimension `dim`. This means for a low
boundary the innermost plane is the last element in the
sequence. For a high boundary the innermost plane is the 0th element.
Halo exchange and applying boundary conditions is done one plane at a time
for performance reasons.
Returns:
The incoming `z_list` modified to include the result of halo exchange and
taking boundary conditions into account.
"""
boundary_conditions = boundary_conditions or [[None, None]] * len(dims)
assert len(dims) == len(replica_dims)
assert len(dims) == len(boundary_conditions)
for (dim, replica_dim, bc) in zip(dims, replica_dims, boundary_conditions):
bc_low, bc_high = bc if bc else (None, None)
left_or_top_padding = (top_padding, left_padding, 0)[dim]
# Select the relevant planes from the sequence of bc planes.
# Create a mutable copy of the bc passed in.
bc_low_plane = list(bc_low)
# If the boundary condition is a list of planes select the relevant one.
bc_low_plane[1] = (
bc_low_plane[1]
if isinstance(bc_low_plane[1], float) else bc_low_plane[1][0])
# Create a mutable copy of the bc passed in.
bc_high_plane = list(bc_high)
# If the boundary condition is a list of planes select the relevant one.
bc_high_plane[1] = (
bc_high_plane[1]
if isinstance(bc_high_plane[1], float) else bc_high_plane[1][0])
z_list = _inplace_halo_exchange_1d(z_list, dim, replica_id, replicas,
replica_dim, bc_low_plane, bc_high_plane,
left_or_top_padding)
return z_list
def _get_core_n(n: int) -> Optional[int]:
"""Returns dimension of grid per core not used for halo exchange."""
core_n = n - 2
return core_n if core_n > 0 else None
def _get_full_grid(n: Optional[int], l: float) -> tf.Tensor:
"""The full grid without halos.
Args:
n: The total number of grid points without halos.
l: The total length of the domain.
Returns:
A equidistant grid for the entire computational domain. The first grid point
is 0.
"""
n_effective = n if n is not None else 1
return tf.linspace(0.0, l, n_effective)
def _get_full_grid_size(
n: int,
num_cores: int,
num_boundary_points: int = 1,
) -> int:
"""The full grid size (includes padding, if any)."""
core_n = _get_core_n(n)
if not core_n:
return 1
return num_cores * core_n + num_boundary_points * 2
# An object to hold Grid Parametrization data.
GridParametrizationData = collections.namedtuple(
'GridParametrizationData',
[
# Computation shape.
'cx',
'cy',
'cz',
# Length dims.
'lx',
'ly',
'lz',
# Grid size.
'nx',
'ny',
'nz',
# Physical grid size.
'fx_physical',
'fy_physical',
'fz_physical',
# Time delta.
'dt',
])
class GridParametrization:
"""An object to hold configuration parameters.
For computing dx, dy, dz below, we assume the 'box' boundaries coincide with
the outer most grid points on each end -- the 'halo' grid. This means there
are in total `core * c + 2` points, or `core * c + 1` spacings.
"""
def __init__(self, params: GridParametrizationData = None):
"""Creates an object from `GridParametrizationData`."""
self.cx = params.cx
self.cy = params.cy
self.cz = params.cz
self.lx = params.lx
self.ly = params.ly
self.lz = params.lz
self.nx = params.nx
self.ny = params.ny
self.nz = params.nz
self.fx_physical = params.fx_physical
self.fy_physical = params.fy_physical
self.fz_physical = params.fz_physical
self.dt = params.dt
self.num_boundary_points = 1
def __str__(self):
return ('fx_physical: {}, fy_physical: {}, fz_physical: {}, fx: {}, fy: {},'
'fz: {}, nx: {}, ny: {}, nz: {}, core_nx: {}, core_ny: {}, '
'core_nz: {}, lx: {}, ly: {}, lz: {}, dt: {}, dx: {}, dy: {}, '
'dz: {}, computation_shape: {}'.format(
self.fx_physical, self.fy_physical, self.fz_physical, self.fx,
self.fy, self.fz, self.nx, self.ny, self.nz, self.core_nx,
self.core_ny, self.core_nz, self.lx, self.ly, self.lz, self.dt,
self.dx, self.dy, self.dz, self.computation_shape))
@property
def computation_shape(self) -> np.ndarray:
return np.array([self.cx, self.cy, self.cz])
@property
def core_nx(self) -> Optional[int]:
return _get_core_n(self.nx)
@property
def core_ny(self) -> Optional[int]:
return _get_core_n(self.ny)
@property
def core_nz(self) -> Optional[int]:
return _get_core_n(self.nz)
def _get_grid_spacing(self, full_grid_size, length) -> Optional[float]:
"""Get the grid spacing between nodes in a equidistant mesh.
Args:
full_grid_size: The total number of nodes in the mesh grid.
length: The size of the domain in a particular dimension.
Returns:
The distance between two adjacent nodes.
"""
full_grid_size -= 2 * self.num_boundary_points
return length / (full_grid_size - 1) if full_grid_size > 1 else None
@property
def dx(self) -> Optional[float]:
return self._get_grid_spacing(self.fx, self.lx)
@property
def dy(self) -> Optional[float]:
return self._get_grid_spacing(self.fy, self.ly)
@property
def dz(self) -> Optional[float]:
return self._get_grid_spacing(self.fz, self.lz)
@property
def fx(self):
"""The full grid size in dim 0."""
return _get_full_grid_size(self.nx, self.cx, self.num_boundary_points)
@property
def fy(self):
"""The full grid size in dim 1."""
return _get_full_grid_size(self.ny, self.cy, self.num_boundary_points)
@property
def fz(self):
"""The full grid size in dim 2."""
return _get_full_grid_size(self.nz, self.cz, self.num_boundary_points)
@property
def x(self) -> tf.Tensor:
"""The full grid in dim 0."""
return _get_full_grid(self.fx, self.lx)
@property
def y(self) -> tf.Tensor:
"""The full grid in dim 0."""
return _get_full_grid(self.fy, self.ly)
@property
def z(self) -> tf.Tensor:
"""The full grid in dim 0."""
return _get_full_grid(self.fz, self.lz)
@property
def num_replicas(self):
return self.cx * self.cy * self.cz
def _get_padding(num_cores, divisor, full_physical_size):
"""Returns amount of padding across all cores."""
nc_div = num_cores * divisor
return int(
(nc_div - (full_physical_size + 2 * (num_cores - 1)) % nc_div) % nc_div)
class SaintVenantParams(GridParametrization):
"""A configuration object for Saint-Venant simulation."""
def __init__(self, grid_parametrization_data, grid_size_dim_0_divisor,
grid_size_dim_1_divisor, difference_method, num_secs,
num_secs_per_cycle):
super(SaintVenantParams, self).__init__(grid_parametrization_data)
self.manning_coeff_floodplain = MANNING_COEFF_FLOODPLAIN
self.manning_coeff_river = MANNING_COEFF_RIVER
self.nx_divisor = grid_size_dim_0_divisor
self.ny_divisor = grid_size_dim_1_divisor
self.difference_method = difference_method
self.num_secs = num_secs
self.num_secs_per_cycle = num_secs_per_cycle
self.warmup_seconds = 3600
@property
def left_padding(self):
return self.fy - self.fy_physical
@property
def top_padding(self):
return self.fx - self.fx_physical
def _get_grid_spacing(self, core_spacing, num_cores,
length) -> Optional[float]:
return (None if core_spacing is None
else length / (core_spacing * num_cores + 1))
@property
def dx(self) -> Optional[float]:
return self._get_grid_spacing(self.core_nx, self.cx, self.lx)
@property
def dy(self) -> Optional[float]:
return self._get_grid_spacing(self.core_ny, self.cy, self.ly)
@property
def dz(self) -> None:
return None
@property
def num_steps_per_cycle(self) -> int:
return int(round(self.num_secs_per_cycle / self.dt)) if self.dt else 1
@property
def num_cycles(self) -> int:
return int(round(self.num_secs / self.num_secs_per_cycle))
@property
def num_steps(self) -> int:
return self.num_cycles * self.num_steps_per_cycle
def get_tile_name(base_name: Text, tile_id: int) -> Text:
"""Returns TensorMap key used to store a given tile."""
return '%s_tile_%d' % (base_name, tile_id)
def gen_field(field_name: Text, nx: int, ny: int, nz: int,
dtype: tf.dtypes.DType = tf.float32) -> TensorMap:
"""Returns a dict of zero initial values."""
return {field_name: tf.zeros([nz, nx, ny], dtype=dtype)}
def constant_height_zeros(y, x, Ly, nx, ny, dem):
z = tf.ones_like(y,dtype=tf.float32)*0.0
#if height > 1e-5:
# z = tf.where(y < 1, tf.ones_like(z)*0.673, z)
z = tf.expand_dims(z,axis=0)
z = tf.repeat(z, nx,axis = 0)
return z
def water_initial_condition(field_name: Text,
coords: ThreeIntTuple,
params,
unpadded_dem,
initial_condition_function,
dtype: tf.dtypes.DType = tf.float32) -> TensorMap:
Ly = (params.fy-2)*params.dy
min_y = tf.cast((coords[1] * (params.ny-2) - 1) * params.dy, tf.float32)
max_y = tf.cast(((coords[1]+1) * (params.ny-2)) * params.dy, tf.float32)
min_x = 0.0
max_x = params.lx#tf.cast(((coords[0]+1) * (params.nx)) * params.dx, tf.float32)
dem = tf.pad(unpadded_dem,[[params.top_padding,0],[params.left_padding,0]],'SYMMETRIC')
y = tf.linspace(min_y, max_y, params.ny)
x = tf.linspace(min_x, max_x, params.nx)
min_index = (coords[1] * (params.ny-2))
max_index = (coords[1]+1) * (params.ny-2)+2
partial_dem = dem[:,min_index:max_index]
z = initial_condition_function(y,x,Ly,params.nx,params.ny,partial_dem)
return {field_name: tf.expand_dims(z,axis=0)}
def flux_initial_condition(field_name: Text,
coords: ThreeIntTuple,
params,
unpadded_dem,
initial_condition_function,
dtype: tf.dtypes.DType = tf.float32) -> TensorMap:
Ly = (params.fy-2)*params.dy
min_y = tf.cast((coords[1] * (params.ny-2) - 1) * params.dy, tf.float32)
max_y = tf.cast(((coords[1]+1) * (params.ny-2)) * params.dy, tf.float32)
min_x = 0.0
max_x = params.lx#tf.cast(((coords[0]+1) * (params.nx)) * params.dx, tf.float32)
dem = tf.pad(unpadded_dem,[[params.top_padding,0],[params.left_padding,0]],'SYMMETRIC')
y = tf.linspace(min_y, max_y, params.ny)
x = tf.linspace(min_x, max_x, params.nx)
min_index = (coords[1] * (params.ny-2))
max_index = (coords[1]+1) * (params.ny-2)+2
partial_dem = dem[:,min_index:max_index]
z = initial_condition_function(y,x,Ly,params.nx,params.ny,partial_dem)
return {field_name: tf.expand_dims(z,axis=0)}
def get_field(state: TensorMap, field_name: Text,
nz: int) -> List[tf.Tensor]:
"""Returns list of tiles from `state`."""
return [state[get_tile_name(field_name, i)] for i in range(nz)]
def split_state_in_z(state: TensorMap,
state_keys: Iterable[Text],
nz: int) -> MutableTensorMap:
"""Splits state in z, assuming that z is in the first dimension.
Args:
state: A dictionary of keyed tuples.
state_keys: A list of string keys (must be present in state dictionary).
nz: Z-dimension length/size.
Returns:
State split in the z dimension.
"""
out_dict = {}
for state_key in state_keys:
out_dict.update({
get_tile_name(state_key, i): state[state_key][i, :, :]
for i in range(nz)
})
return out_dict
def merge_state_in_z(state: TensorMap,
state_keys: Iterable[Text],
nz: int) -> MutableTensorMap:
"""Merges state in z, assuming that z is in the first dimension.
Args:
state: A dictionary of keyed tuples.
state_keys: A list of string keys (must be present in state dictionary).
nz: Z-dimension length/size.
Returns:
State stacked in the z dimension.
"""
out_dict = {}
for state_key in state_keys:
out_dict.update({
state_key:
tf.stack(
[state[get_tile_name(state_key, i)] for i in range(nz)],
axis=0)
})
return out_dict
def get_haloless_slice(replica_idx: int, num_replicas: int) -> slice:
"""Returns a slice to be used on a tensor tile.
In particular, the slice will conditionally remove the outermost indices
of a given tensor in a given dimension.
Args:
replica_idx: The replica index in the dimension for which the slice is
being determined.
num_replicas: The number of replicas in given dimension for which the
slice is being determined.
Returns:
A slice corresponding to the given input parameters.
"""
def _is_first_replica():
return replica_idx == 0
def _is_last_replica():
return replica_idx == num_replicas - 1
if num_replicas == 1:
return slice(None, None)
elif _is_first_replica():
return slice(0, -1)
elif _is_last_replica():
return slice(1, None)
else: # Interior replica.
return slice(1, -1)
def flatten_weights(
weights: Mapping[Text, Any]) -> 'collections.OrderedDict[Text, Any]':
"""Flattens a nested weight dictionary a dictionary keyed on a/b/c paths."""
flat = collections.OrderedDict()
for key, value in weights.items():
if isinstance(value, dict):
for subkey, subvalue in flatten_weights(value).items():
flat['{}/{}'.format(key, subkey)] = subvalue
else:
flat[key] = value
return flat
def unflatten_weights(
flattened_weights: Mapping[Text,
Any]) -> 'collections.OrderedDict[Text, Any]':
"""Unflattens a dictionary keyed on a/b/c paths to nested dictionaries."""
weights = collections.OrderedDict()
for flat_key, value in flattened_weights.items():
w = weights
flat_keys = flat_key.split('/')
for key in flat_keys[:-1]:
if key not in w:
w[key] = collections.OrderedDict()
w = w[key]
w[flat_keys[-1]] = value
return weights
def grid_coordinates(computation_shape: np.ndarray) -> np.ndarray:
"""Returns a numpy array containing all grid coordinates.
Args:
computation_shape: A sequence of integers giving the shape of the grid.
Returns:
A numpy array with shape
(np.prod(computation_shape), len(computation_shape)) and type np.int32.
"""
rank = len(computation_shape)
assert rank > 0