-
Notifications
You must be signed in to change notification settings - Fork 86
/
topotools.py
1895 lines (1520 loc) · 73.2 KB
/
topotools.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
#!/usr/bin/env python
# encoding: utf-8
r"""
GeoClaw topotools Module `$CLAW/geoclaw/src/python/geoclaw/topotools.py`
Module provides several functions for reading, writing and manipulating
topography (bathymetry) files.
:Classes:
- Topography
:Functions:
- determine_topo_type
- create_topo_func
- topo1writer
- topo2writer
- topo3writer
- swapheader
:TODO:
- Add sub and super sampling capababilities
- Add functions for creating topography based off a topo function, incorporate
the create_topo_func into Topography class, maybe allow more broad
initialization ability to the class to handle this?
- Fix `in_poly` function
- Add remove/fill no data value
- Add more robust plotting capabilities
"""
import os
import numpy
import clawpack.geoclaw.util as util
import clawpack.clawutil.data
import clawpack.geoclaw.data
# ==============================================================================
# Topography Related Functions
# ==============================================================================
def determine_topo_type(path, default=None):
r"""Using the file suffix of path, attempt to deterimine the topo type.
:Input:
- *path* (string) - Path to the file. Can include archive extensions (they
will be stripped off).
- *default* (object) - Value returned if no suitable topo type was
determined. Default is *None*.
returns integer between 1-3 or *default* if nothing matches.
"""
extension = os.path.splitext(
clawpack.clawutil.data.strip_archive_extensions(path))[-1][1:]
topo_type = default
if extension[:2] == "tt" or extension[:8] == 'topotype':
topo_type = int(extension[-1])
elif extension == 'xyz':
topo_type = 1
elif extension == 'asc':
topo_type = 3
elif extension == 'txyz':
topo_type = 1
elif extension == 'nc':
topo_type = 4
return topo_type
def create_topo_func(loc,verbose=False):
"""
Given a 1-dimensional topography profile specfied by a set of (x,z)
values, create a lambda function that when evaluated will give the
topgraphy at the point (x,y). (The resulting function is constant in y.)
:Example:
>>> f = create_topo_func(loc)
>>> b = f(x, y)
:Input:
- *loc* (list) - Create a topography file with the profile denoted by the
tuples inside of loc. A sample set of points are shown below. Note
that the first value of the list is the x location and the second is
the height of the topography. ::
z (m)
^ o loc[5] o
|
| loc[4]
|--------------------------------------------o-----> x (m) (sea level)
|
| o loc[2] o loc[3]
|
|
| o loc[1]
|
|
|__________________o loc[0]
0.0
"""
cmd_str = "lambda x,y: (x <= %s) * %s" % (loc[0][0],loc[0][1])
for i in range(0,len(loc)-1):
loc_str = " + (%s < x) * (x <= %s)" % (loc[i][0],loc[i+1][0])
loc_str = "".join((loc_str," * ((%s - %s) " % (loc[i][1],loc[i+1][1])))
loc_str = "".join((loc_str," / (%s - %s)" % (loc[i][0],loc[i+1][0])))
loc_str = "".join((loc_str," * (x - %s) + %s)" % (loc[i][0],loc[i][1])))
cmd_str = "".join((cmd_str,loc_str))
cmd_str = "".join((cmd_str," + (%s < x) * %s" % (loc[-1][0],loc[-1][1])))
if verbose:
print(cmd_str)
return eval(cmd_str)
def topo1writer (outfile,topo,xlower,xupper,ylower,yupper,nxpoints,nypoints):
"""
Function topo1writer will write out the topofiles by evaluating the
function topo on the grid specified by the other parameters.
Assumes topo can be called on arrays X,Y produced by numpy.meshgrid.
Output file is of "topotype1," which we use to refer to a file with
(x,y,z) values on each line, progressing from upper left corner across
rows, then down.
"""
topography = Topography(topo_func=topo)
topography.x = numpy.linspace(xlower,xupper,nxpoints)
topography.y = numpy.linspace(ylower,yupper,nypoints)
topography.write(outfile, topo_type=1)
def topo2writer (outfile,topo,xlower,xupper,ylower,yupper,nxpoints,nypoints, \
nodata_value=-99999):
r"""Write out a topo type 2 file by evaluating the function *topo*.
This routine is here for backwards compatibility and simply creates a new
topography object and writes it out.
"""
topography = Topography(topo_func=topo)
topography.x = numpy.linspace(xlower,xupper,nxpoints)
topography.y = numpy.linspace(ylower,yupper,nypoints)
topography.write(outfile, topo_type=2)
def topo3writer (outfile,topo,xlower,xupper,ylower,yupper,nxpoints,nypoints, \
nodata_value=-99999):
r"""Write out a topo type 3 file by evaluating the function *topo*.
This routine is here for backwards compatibility and simply creates a new
topography object and writes it out.
"""
topography = Topography(topo_func=topo)
topography.x = numpy.linspace(xlower,xupper,nxpoints)
topography.y = numpy.linspace(ylower,yupper,nypoints)
topography.write(outfile, topo_type=3)
def fetch_topo_url(url, local_fname=None, force=None, verbose=False,
ask_user=False):
"""
DEPRECATED: Use *clawpack.clawutil.data.get_remote_file* instead (see note below).
Replaces get_topo function.
Download a topo file from the web, provided the file does not
already exist locally.
:Input:
- *url* (str) URL including file name
- *local_fname* (str) name of local file to create.
If *local_fname == None*, take file name from URL
- *force* (bool) If False, prompt user before downloading.
For GeoClaw examples, some topo files can be found in
`http://www.geoclaw.org/topo`_
See that website for a list of archived topo datasets.
If force==False then prompt the user to make sure it's ok to download,
If force==None then check for environment variable CLAW_TOPO_DOWNLOAD
and if this exists use its value. This is useful for the script
python/run_examples.py that runs all examples so it won't stop to prompt.
This routine has been deprecated in favor of
*clawpack.clawutil.data.get_remote_file*. All the functionality should be
the same but calls the other routine internally.
"""
if force is None:
CTD = os.environ.get('CLAW_TOPO_DOWNLOAD', None)
force = (CTD in [True, 'True'])
if local_fname is not None:
output_dir = os.path.dirname(local_fname)
file_name = os.path.basename(local_fname)
clawpack.clawutil.data.get_remote_file(url, output_dir=output_dir,
file_name=file_name,
force=force,
verbose=verbose,
ask_user=ask_user)
def get_topo(topo_fname, remote_directory, force=None):
"""
DEPRECATED: Use *clawpack.geoclaw.util.get_remote_file* instead
Download a topo file from the web, provided the file does not
already exist locally.
remote_directory should be a URL. For GeoClaw data it may be a
subdirectory of http://www.clawpack.org/geoclaw/topo
See that website for a list of archived topo datasets.
If force==False then prompt the user to make sure it's ok to download,
with option to first get small file of metadata.
If force==None then check for environment variable CLAW_TOPO_DOWNLOAD
and if this exists use its value. This is useful for the script
python/run_examples.py that runs all examples so it won't stop to prompt.
"""
url = remote_directory + '/' + topo_fname
clawpack.clawutil.data.get_remote_file(url, force=force)
def swapheader(inputfile, outputfile):
r"""Swap the order of key and value in header to value first.
Note that this is a wrapper around functionality in the Topography class.
"""
topo = Topography(inputfile)
topo.write(outputfile)
# ==============================================================================
# Topography class
# ==============================================================================
class Topography(object):
r"""Base topography class.
A class representing a single topography file.
:Properties:
Note: Modified to check the `grid_registration` when reading or writing
topo files and properly deal with `llcorner` registration in which case
the x,y data should be offset by dx/2, dy/2 from the lower left corner
specified in the header of a DEM file.
:Initialization:
-
:Examples:
>>> import clawpack.geoclaw.topotools as topo
>>> topo_file = topo.Topography()
>>> topo_file.read('./topo.tt3', topo_type=3)
>>> topo_file.plot()
"""
@property
def z(self):
r"""A representation of the data as an 1d array."""
if (self._z is None) and self.unstructured:
self.read(mask=False)
return self._z
@z.setter
def z(self, value):
self._z = value
@z.deleter
def z(self):
del self._z
@property
def Z(self):
r"""A representation of the data as a 2d array."""
if self._Z is None:
self.generate_2d_topo(mask=False)
return self._Z
@Z.setter
def Z(self, value):
self._Z = value
@Z.deleter
def Z(self):
del self._Z
@property
def x(self):
r"""One dimensional coorindate array in x direction."""
if self._x is None:
self.read(mask=False)
return self._x
@x.setter
def x(self, value):
self._extent = None
self._x = value
@x.deleter
def x(self):
del self._x
@property
def X(self):
r"""Two dimensional coordinate array in x direction."""
if self._X is None:
self.generate_2d_coordinates(mask=False)
return self._X
@X.setter
def X(self, value):
self._extent = None
self._X = value
self._x = numpy.nan
@X.deleter
def X(self):
del self._X
@property
def y(self):
r"""One dimensional coordinate array in y direction."""
if self._y is None:
self.read(mask=False)
return self._y
@y.setter
def y(self, value):
self._extent = None
self._y = value
@y.deleter
def y(self):
del self._y
@property
def Y(self):
r"""Two dimensional coordinate array in y direction."""
if self._Y is None:
self.generate_2d_coordinates(mask=False)
return self._Y
@Y.setter
def Y(self, value):
self._extent = None
self._Y = value
self._y = numpy.nan
@Y.deleter
def Y(self):
del self._Y
@property
def extent(self):
r"""Extent of the topography."""
if self._extent is None:
self._extent = ( numpy.min(self.x), numpy.max(self.x),
numpy.min(self.y), numpy.max(self.y) )
return self._extent
@extent.setter
def extent(self, value):
self._extent = value
@property
def delta(self):
r"""Spacing of data points."""
if self._delta is None:
if self.unstructured:
# Calculate the smallest spacing between grid points
dx = numpy.infty
dy = numpy.infty
num_comparisons = self.x.shape[0] - 1
for i in range(self.x.shape[0]):
for j in range(num_comparisons):
dx = min(dx, numpy.abs(self.x[i + j + 1] - self.x[i]))
dy = min(dy, numpy.abs(self.y[i + j + 1] - self.y[i]))
num_comparisons -= 1
self._delta = [dx, dy]
else:
# All other topography types should have equally spaced grid
# points in each direction
begin_delta = numpy.array([abs(self.x[1] - self.x[0]),
abs(self.y[1] - self.y[0])])
end_delta = numpy.array([abs(self.x[-2] - self.x[-1]),
abs(self.y[-2] - self.y[-1])])
if not numpy.allclose(begin_delta, end_delta, 1e-8):
raise ValueError("Grid spacing delta not constant, ",
"%s != %s." % (begin_delta, end_delta))
dx = numpy.round(begin_delta[0], 15)
dy = numpy.round(begin_delta[1], 15)
self._delta = (dx, dy)
return self._delta
def __init__(self, path=None, topo_type=None, topo_func=None,
unstructured=False):
r"""Topography initialization routine.
See :class:`Topography` for more info.
"""
super(Topography, self).__init__()
self.path = path
self.topo_func = topo_func
self.topo_type = topo_type
self.unstructured = unstructured
self.no_data_value = -9999
# Data storage for only calculating array shapes when needed
self._z = None
self._Z = None
self._x = None
self._X = None
self._y = None
self._Y = None
self._extent = None
self._delta = None
self.coordinate_transform = lambda x,y: (x,y)
if path:
self.read(path=path, topo_type=topo_type,
unstructured=unstructured)
def set_xyZ(self, X, Y, Z):
r"""
Set _x, _y, and _Z attributes and then generate X,Y,Z.
If X,Y are 1d arrays, then shape of Z should be (len(Y), len(X)).
Allow X,Y to be 2d arrays of shape Z.shape, in which case
first extract x,y
"""
if X.ndim == 1:
x = X
else:
x = X[0,:]
if Y.ndim == 1:
y = Y
else:
y = Y[:,0]
if Z.shape != (len(y),len(x)):
raise ValueError("shape of Z should be (len(y), len(x))")
diffx = numpy.diff(x)
diffy = numpy.diff(y)
dx = numpy.mean(diffx)
dy = numpy.mean(diffy)
if dy < 0:
Y = numpy.flipud(Y)
y = numpy.flipud(y)
diffy = numpy.diff(y)
dy = numpy.mean(diffy)
Z = numpy.flipud(Z)
if diffx.max()-diffx.min() > 1e-3*dx:
print('diffx.max()-diffx.min() = ', diffx.max()-diffx.min())
raise ValueError("x must be equally spaced for structured topo")
if diffy.max()-diffy.min() > 1e-3*dy:
print('diffy.max()-diffy.min() = ', diffy.max()-diffy.min())
raise ValueError("y must be equally spaced for structured topo")
self.unstructured = False
self._x = x
self._y = y
self._Z = Z
self._X = None
self._Y = None
self.generate_2d_coordinates()
if X.ndim == 2:
assert numpy.allclose(self.X, X), '*** X set incorrectly?'
if Y.ndim == 2:
assert numpy.allclose(self.Y, Y), '*** Y set incorrectly?'
def generate_2d_topo(self, mask=False):
r"""Generate a 2d array of the topo."""
# Check to see if we need to generate these
if self._Z is None:
if self.unstructured:
# Really no way to do this here with performing interpolation via
# extract. Note that if the interpolation is performed these
# arrays are already stored in self._X and self._Y
raise ValueError("Unstructured data does not allow for use of" \
+ " 2d arrays, first interpolate the data and" \
+ " try to perform this operation again.")
if self.path is not None:
# RJL: why do we expect 1d z?
if self._z is None:
# Try to read the data, may not have done this yet
if self.topo_type is None:
self.topo_type = determine_topo_type(self.path)
if self.topo_type is None:
raise ValueError("topo_type must be specified")
self.read(path=self.path, topo_type=self.topo_type, mask=mask)
if self._Z is not None:
# We are done, the read function did our work
return
# See if self._X and self._Y are already computed and use them if
# available, otherwise just use self._x and self._y
if self._X is not None and self._Y is not None:
new_shape = self._X.shape
else:
new_shape = (self._x.shape[0], self._y.shape[0])
# Reshape, note that the mask follows along with the new array
self._Z = numpy.reshape(self._z, new_shape)
elif self.topo_func is not None:
# Generate topo via topo_func
## self._Z = numpy.flipud(self.topo_func(self.X, self.Y))
## RJL: Don't flip -- leave so Z[i,j] has same dimensions as X,Y
## Othewise does not plot properly.
self._Z = self.topo_func(self.X, self.Y)
def generate_2d_coordinates(self, mask=False):
r"""Generate 2d coordinate arrays."""
# Check to see if we need to generate these
if self._X is None and self._Y is None:
# RJL: Added this to generate from _x and _y if available.
# Correct?
if (self._x is not None) and (self._y is not None):
self._X,self._Y = numpy.meshgrid(self._x, self._y)
if self._X is None and self._Y is None:
if self.unstructured:
# Really no way to do this here with performing interpolation via
# extract. Note that if the interpolation is performed these
# arrays are already stored in self._X and self._Y
raise ValueError("Unstructured data does not allow for use of" \
+ " 2d coordinates, first interpolate the data" \
+ " and try to perform this operation again.")
if self.path is not None:
if abs(self.topo_type) == 1:
# Reading this topo_type should produce the X and Y arrays
self.read(mask=mask)
elif abs(self.topo_type) in [2,3]:
if self._x is None or self._y is None:
# Try to read the data to get these, may not have been done yet
self.read(mask=mask)
# Generate arrays
self._X, self._Y = numpy.meshgrid(self._x, self._y)
else:
raise ValueError("Unrecognized topo_type: %s" % self.topo_type)
elif self.topo_func is not None:
if self._x is None or self._y is None:
raise ValueError("The x and y arrays must be set to ",
"create 2d coordinate arrays.")
self._X, self._Y = numpy.meshgrid(self._x, self._y)
# If masking has been requested try to get the mask first from
# self._Z and then self._z
if mask:
if self._Z is None:
# Check to see if we really need to do anything here
if isinstance(self._z, numpy.ma.MaskedArray):
# Try to create self._Z
self.generate_2d_topo(mask=mask)
if isinstance(self._Z, numpy.ma.MaskedArray):
# Use Z's mask for the X and Y coordinates
self._X = numpy.ma.MaskedArray(self._X, mask=self._Z.mask,
copy=False)
self._Y = numpy.ma.MaskedArray(self._Y, mask=self._Z.mask,
copy=False)
def read(self, path=None, topo_type=None, unstructured=False,
mask=False, filter_region=None, force=False, stride=[1, 1],
nc_params={}):
r"""Read in the data from the object's *path* attribute.
Stores the resulting data in one of the sets of *x*, *y*, and *z* or
*X*, *Y*, and *Z*.
:Input:
- *path* (str) file to read
- *topo_type* (int) - GeoClaw format topo_type
- *unstructured* (bool) - default is False for lat-long grids.
- *mask* (bool) - whether to store as masked array for missing
values (default if False)
- *filter_region* (tuple)
- *stride* (list) - List of strides for the x and y dimensions
respectively. Default is *[1, 1]*. Note that this is only
implemented for NetCDF reading currently.
- *nc_params* (dict) -
The first three might have already been set when instatiating object.
"""
if (path is None) and (self.path is None):
raise ValueError("*** Need to set path for file to read")
if path:
self.path = path # set or perhaps reset
self.topo_type = None # force resetting below
if unstructured:
self.unstructured = unstructured
# Check if the path is a URL and fetch data if needed or forced
#if "http" in self.path:
# fetch_topo_url(self.path)
# RJL: should switch to util.get_remote_file, but after fetching
# still need to read it in, which that routine does not do.
# Do we really want to support this? Seems better for user
# to fetch and store as desired filename and then read file.
if self.topo_type is None:
if topo_type is not None:
self.topo_type = topo_type
else:
# Try to look at suffix for type
self.topo_type = determine_topo_type(self.path)
if self.topo_type is None:
#self.topo_type = 3
raise ValueError("topo_type must be specified")
if self.unstructured:
# Read in the data as series of tuples
data = numpy.loadtxt(self.path)
points = []
values = []
# Filter region if requested
if filter_region is not None:
for coordinate in data:
if filter_region[0] <= coordinate[0] <= filter_region[1]:
if filter_region[2] <= coordinate[1] <= filter_region[3]:
points.append(coordinate[0:2])
values.append(coordinate[2])
if len(points) == 0:
raise Exception("No points were found inside requested " \
+ "filter region.")
# Cast lists as ndarrays
self._x = numpy.array(points[:,0])
self._y = numpy.array(points[:,1])
self._z = numpy.array(values)
else:
self._x = data[:,0]
self._y = data[:,1]
self._z = data[:,2]
else:
# Data is in one of the GeoClaw supported formats
if abs(self.topo_type) == 1:
data = numpy.loadtxt(self.path)
N = [0,0]
y0 = data[0,1]
for (n, y) in enumerate(data[1:,1]):
if y != y0:
N[1] = n + 1
break
N[0] = data.shape[0] // N[1]
self._x = data[:N[1],0]
self._y = data[::N[1],1]
self._Z = numpy.flipud(data[:,2].reshape(N))
dx = self.X[0,1] - self.X[0,0]
dy = self.Y[1,0] - self.Y[0,0]
self._delta = (dx,dy)
elif abs(self.topo_type) in [2,3]:
# Get header information
N = self.read_header() # note this also sets self._extent
# self._x, self._y, self._delta,
# and self.grid_registration
if abs(self.topo_type) == 2:
# Data is read in as a single column, reshape it
self._Z = numpy.loadtxt(self.path, skiprows=6).reshape(N[1],N[0])
self._Z = numpy.flipud(self._Z)
elif abs(self.topo_type) == 3:
# Data is read in starting at the top right corner
self._Z = numpy.flipud(numpy.loadtxt(self.path, skiprows=6))
if mask:
self._Z = numpy.ma.masked_values(self._Z, self.no_data_value, copy=False)
elif abs(self.topo_type) == 4:
import netCDF4
# NetCDF4 GEBCO topography
with netCDF4.Dataset(self.path, 'r', format="NETCDF4") as nc_file:
x_var = nc_params.get('x_var', None)
y_var = nc_params.get('y_var', None)
z_var = nc_params.get('z_var', None)
for (key, var) in nc_file.variables.items():
if 'axis' in var.ncattrs():
if var.axis.lower() == "x" and x_var is None:
x_var = key
elif var.axis.lower() == "y" and y_var is None:
y_var = key
else:
if z_var is None:
z_var = key
if x_var is None or y_var is None or z_var is None:
err_string = "".join(
("Could not automatically determine ",
"variable ids. Please check if the ",
"file has the 'axis' attribute attached",
" to the appropriate x and y variables ",
"or specify the variables directly via",
" the *nc_params* dictionary."))
raise IOError(err_string)
self._x = nc_file.variables[x_var][::stride[0]]
self._y = nc_file.variables[y_var][::stride[1]]
self._Z = nc_file.variables[z_var][::stride[0],
::stride[1]]
if mask:
self._Z = numpy.ma.masked_values(self._Z, self.no_data_value, copy=False)
elif abs(self.topo_type) == 5:
# GeoTIFF
try:
import gdal
except ImportError as e:
print("Reading GeoTIFF files requires GDAL.")
raise e
data = gdal.Open(self.path)
z = data.GetRasterBand(1).ReadAsArray()
transform = data.GetGeoTransform()
x_origin = transform[0]
y_origin = transform[3]
dx = transform[1]
dy = -transform[5]
self._Z = numpy.flipud(z)
self._x = numpy.linspace(x_origin,
x_origin + (z.shape[0] - 1) * dx, z.shape[0])
self._y = numpy.linspace(y_origin - (z.shape[1] - 1) * dy,
y_origin, z.shape[1])
else:
raise IOError("Unrecognized topo_type: %s" % self.topo_type)
if self.topo_type < 0:
# positive Z means distance below sea level for these
# topo_type's, contrary to our convention, so negate:
self._Z = -self._Z
# Make sure these are set to None to force re-generating:
self._X = None
self._Y = None
# Perform region filtering
if filter_region is not None:
# Find indices of region
region_index = [None, None, None, None]
region_index[0] = (self.x >= filter_region[0]).nonzero()[0][0]
region_index[1] = (self.x <= filter_region[1]).nonzero()[0][-1]
region_index[2] = (self.y >= filter_region[2]).nonzero()[0][0]
region_index[3] = (self.y <= filter_region[3]).nonzero()[0][-1]
self._x = self._x[region_index[0]:region_index[1]]
self._y = self._y[region_index[2]:region_index[3]]
# Force regeneration of 2d coordinate arrays and extent
if self._X is not None or self._Y is not None:
del self._X, self._Y
self._X = None
self._Y = None
self._extent = None
# Modify Z array as well
self._Z = self._Z[region_index[2]:region_index[3],
region_index[0]:region_index[1]]
def read_header(self):
r"""Read in header of topography file at path.
If a value returns numpy.nan then the value was not retrievable. Note
that this routine can read in headers whose values and labels are
swapped.
"""
if abs(self.topo_type) in [2,3]:
# Default values to track errors
num_cells = [numpy.nan,numpy.nan]
self._extent = [numpy.nan,numpy.nan,numpy.nan,numpy.nan]
self._delta = numpy.nan
with open(self.path, 'r') as topo_file:
# Check to see if we need to flip the header values
first_line = topo_file.readline()
try:
num_cells[0] = int(first_line.split()[0])
except ValueError:
# Assume the header is flipped from what we expect
num_cells[0] = int(first_line.split()[-1])
value_index = -1
label_index = 0
else:
value_index = 0
label_index = -1
num_cells[1] = int(topo_file.readline().split()[value_index])
xline = topo_file.readline().split()
xll = float(xline[value_index])
# drop 'x' character and convert remaining string to lower case:
x_registration = xline[label_index][1:].lower()
yline = topo_file.readline().split()
yll = float(yline[value_index])
# drop 'y' character and convert remaining string to lower case:
y_registration = yline[label_index][1:].lower()
if x_registration == y_registration:
self.grid_registration = x_registration
# expect registration in ['llcorner', 'llcenter', 'lower']
else:
raise IOError("x_registration and y_registration don't " \
+ "match: %s,%s" % (x_registration, y_registration))
# parse line allowing possibility of dx and dy (or just dx=dy)
line = topo_file.readline()
tokens = line.split()
values = []
for token in tokens:
try:
v = float(token)
values.append(v)
except:
pass
dx = values[0]
if len(values) == 1:
dy = dx # only dx given
elif len(values) == 2:
dy = values[1]
self._delta = (values[0], values[1]) # if dx,dy on line
else:
raise IOError("Cannot parse dx,dy line: %s" % line)
self._delta = (dx, dy)
self.no_data_value = float(topo_file.readline().split()[value_index])
x = numpy.linspace(xll, xll+(num_cells[0]-1)*dx, num_cells[0])
y = numpy.linspace(yll, yll+(num_cells[1]-1)*dy, num_cells[1])
if self.grid_registration in ['lower', 'llcenter']:
# x,y are cell center / data locations:
self._x = x
self._y = y
elif self.grid_registration == 'llcorner':
# x,y are lower left corners:
# data points are offset by dx/2, dy/2
self._x = x + dx/2.
self._y = y + dy/2.
print('*** Note: since grid registration is llcorner,')
print(' will shift x,y values by (dx/2, dy/2) to cell centers')
else:
# assume that x,y are cell center / data locations:
self._x = x
self._y = y
print('*** Warning: Unrecognized grid_registration: %s' \
% self.grid_registration)
print(' Assuming x,y at grid points')
# set extent based on data locations (not lower corner for 'llcorner')
self._extent = [self._x[0],self._x[-1],self._y[0],self._y[-1]]
elif abs(self.topo_type) == 4:
# netCDF
import netCDF4
f = netCDF4.Dataset(self.path, 'r')
self._x = f.variables['lon']
self._y = f.variables['lat']
self._extent = [self._x[0],self._x[-1],self._y[0],self._y[-1]]
dx = self._x[1] - self._x[0]
dy = self._y[1] - self._y[0]
self._delta = (dx, dy)
num_cells = (len(self._x), len(self._y))
elif abs(self.topo_type) == 5:
# GeoTIFF
try:
import gdal
except ImportError as e:
print("Reading GeoTIFF files requires GDAL.")
raise e
data = gdal.Open(self.path)
# z = data.GetRasterBand(1).ReadAsArray()
transform = data.GetGeoTransform()
x_origin = transform[0]
y_origin = transform[3]
dx = transform[1]
dy = -transform[5]
# self._Z = numpy.flipud(z)
self._x = numpy.linspace(x_origin,
x_origin + (z.shape[0] - 1) * dx, z.shape[0])
self._y = numpy.linspace(y_origin - (z.shape[0] - 1) * dy,
y_origin, z.shape[1])
else:
raise IOError("Cannot read header for topo_type %s" % self.topo_type)
return num_cells
def write(self, path, topo_type=None, no_data_value=None, fill_value=None,
header_style='geoclaw', Z_format="%15.7e", grid_registration=None):
r"""Write out a topography file to path of type *topo_type*.
Writes out a topography file of topo type specified with *topo_type* or
inferred from the output file's extension, defaulting to 3, to path
from data in Z. The rest of the arguments are used to write the header
data.
:Input:
- *path* (str) - file to write
- *topo_type* (int) - GeoClaw format topo_type
**Note:** this is second positional argument, agreeing with
the read function in this class. It was the third argument in
GeoClaw version 5.3.1 and earlier.
- *no_data_value* - values used to indicate missing data
- *fill_value* (float) - value to use if filling a masked array
- *header_style* (str) - indicates format of header lines
'geoclaw' or 'default' ==> write value then label
with grid_registration == 'lower' as default
'arcgis' or 'asc' ==> write label then value
with grid_registration == 'llcorner' as default
(needed for .asc files in ArcGIS)
- *Z_format* (str) - string format to use for Z values
The default format "%15.7e" gives at least millimeter precision
for topography with abs(Z) < 10000 and results in
smaller files than the previous default of "%22.15e" used in
GeoClaw version 5.3.1 and earlier. A shorter format can be used
if the user knows there are fewer significant digits, e.g.
etopo1 data is integers and so has a resolution of 1 meter.
In this case a cropped or coarsened version might be written
with `Z_format = "%7i"`, for example.
- *grid_registration* (str) - 'lower', 'llcorner', 'llcenter'
or None for defaults described above.
"""
# Determine topo type if not specified
if topo_type is None:
# Look at the the suffix of the path and the object's topo_type
# attribute to try to deterimine which to use, default to the path
# version unless it did not work
path_topo_type = determine_topo_type(path, default=-1)
if self.topo_type is not None and path_topo_type == -1:
topo_type = self.topo_type
elif path_topo_type != -1:
topo_type = path_topo_type