Skip to content

Commit 4a08a22

Browse files
fixed writing verdat and some test cleanup
1 parent 59a29e8 commit 4a08a22

7 files changed

Lines changed: 132 additions & 177 deletions

File tree

gridded/gridded.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,13 @@ def __getitem__(self, key):
139139
"""
140140
return self.variables[key]
141141

142+
def __str__(self):
143+
descp = (f"gridded.Dataset with:\n"
144+
f"grid: {type(self.grid)}\n"
145+
f"variables: {list(self.variables.keys())}"
146+
)
147+
return descp
148+
142149

143150
def _load_variables(self, ds):
144151
"""

gridded/io/verdat.py

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,13 @@
1212
import numpy as np
1313
import gridded
1414

15+
# verdat only supports FEET or METERS
16+
FEET = ("foot", "ft", "feet")
17+
METER = ("meter", "m", "meters", "metre")
18+
UNITS_MAP = {u: "FEET" for u in FEET}
19+
UNITS_MAP.update({u: "METERS" for u in METER})
20+
21+
1522

1623
def load_verdat(filename):
1724

@@ -34,10 +41,7 @@ def load_verdat(filename):
3441
lons.append(lon)
3542
lats.append(lat)
3643
depths.append(depth)
37-
# print(lons)
38-
# print(lats)
39-
# print(depths)
40-
#read the boundaries:
44+
# read the boundaries:
4145
line = infile.readline().strip()
4246
try:
4347
num_bounds = int(line)
@@ -88,27 +92,30 @@ def save_verdat(ds, filename, depth_var="depth"):
8892
:param filename: name (full or relative path) of the file to save
8993
9094
:param depth_var="depth": name of the variable with the depths in it.
95+
if depth is None, all depths will be set to 1
9196
92-
The dataset must:
93-
94-
* Have a UGrid grid
95-
* Have a variable for the depth
97+
The dataset must: Have a UGrid grid
9698
9799
If it has boundaries, they will be used. Otherwise,
98100
it will create them from the grid.
99101
"""
100-
101-
depth = ds[depth_var]
102102
nodes = ds.grid.nodes
103+
if depth_var is None:
104+
depth = np.ones((nodes.shape[0],), dtype=np.float32)
105+
depth_units = ""
106+
else:
107+
depth = ds[depth_var]
108+
depth_units = UNITS_MAP[depth.units.strip().lower()]
103109
f_string = "{0:4d}, {1:10.6f}, {2:10.6f}, {3:8.3f}\n"
110+
104111
with open(filename, 'w') as outfile:
105-
outfile.write("DOGS ")
106-
if depth.units:
107-
outfile.write(depth.units.upper())
108-
outfile.write("\n")
112+
outfile.write("DOGS")
113+
outfile.write(f" {depth_units}\n")
109114

110115
depth = depth.data
111116
# write out the boundaries first
117+
if ds.grid.boundaries is None:
118+
ds.grid.build_boundaries()
112119
bounds, open_bounds = order_boundary_segments(ds.grid.boundaries)
113120
points_written = []
114121
i = 1
@@ -128,15 +135,14 @@ def save_verdat(ds, filename, depth_var="depth"):
128135
for j in range(len(nodes)):
129136
if j not in points_written:
130137
outfile.write(f_string.format(i,
131-
lon,
132-
lat,
138+
nodes[j, 0],
139+
nodes[j, 1],
133140
depth[j]))
134141
i += 1
135142
outfile.write(f_string.format(0, 0, 0, 0))
136143
outfile.write("{:d}\n".format(len(bounds)))
137144
i = 0
138145
for bound in bounds:
139-
print(bound)
140146
i += len(bound)
141147
outfile.write("{:d}\n".format(i))
142148

gridded/tests/get_remote_data.py

Lines changed: 0 additions & 100 deletions
This file was deleted.

gridded/tests/test_io/__init__.py

Whitespace-only changes.

gridded/tests/test_io/test_verdat.py

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
import gridded
1414
from gridded import io
1515

16+
from ..utilities import data_file_cache
17+
1618
DATA_URL = "https://gnome.orr.noaa.gov/py_gnome_testdata/gridded_test_files/"
1719

1820
HERE = Path(__file__).parent
@@ -90,7 +92,8 @@ def test_read_tiny():
9092

9193

9294
def test_save_verdat():
93-
ds = io.load_verdat(EXAMPLES / "tiny.verdat")
95+
infilename = EXAMPLES / "tiny.verdat"
96+
ds = io.load_verdat(infilename)
9497

9598
outfilename = OUTPUT / "tiny_out.verdat"
9699

@@ -101,15 +104,16 @@ def test_save_verdat():
101104
assert outfilename.is_file()
102105

103106
# Check at least a little bit if it's a valid verdat
107+
orig_contents = open(infilename).readlines()
104108
contents = open(outfilename).readlines()
105-
print(len(contents))
106-
107-
print(contents)
108-
print(len(contents))
109+
for l1, l2 in zip(orig_contents, contents):
110+
norm1 = [s.strip() for s in l1.strip().split(",")]
111+
norm2 = [s.strip() for s in l2.strip().split(",")]
112+
print()
113+
print(norm1)
114+
print(norm2)
109115

110-
assert len(contents) == 16
111-
assert contents[15] == "9\n"
112-
assert contents[0] == "DOGS FEET\n"
116+
assert norm1 == norm2
113117

114118

115119
def test_order_boundary_segments():
@@ -164,17 +168,27 @@ def test_order_boundary_segments_none():
164168
assert len(open_bounds) == 0
165169

166170

167-
def test_general_ugrid_to_verdat():
171+
def test_general_ugrid_to_verdat_no_depth():
168172
"""
169173
Loads a regular old UGRID netCDF file, and saves it to verdat
170174
"""
171-
ugrid_file = pooch.retrieve(
172-
url=(DATA_URL + "SSCOFS.ugrid.nc"),
173-
known_hash="sha256:0dcea2a2fb6ad87c7cce3ebc475fd2f0430616a5019f54f4adf97391e075e939",
174-
)
175+
ugrid_file = data_file_cache.fetch("SSCOFS.ugrid.nc")
176+
ds = gridded.Dataset.from_netCDF(ugrid_file)
177+
178+
outfile = OUTPUT / "SSCOFS.verdat"
179+
outfile.unlink(missing_ok=True)
180+
181+
io.save_verdat(ds, outfile, depth_var=None)
182+
183+
assert outfile.is_file()
184+
185+
contents = open(outfile).readlines()
186+
187+
assert contents[0] == "DOGS \n"
175188

176-
assert False
177189

190+
assert contents[-1] == "190\n"
191+
assert contents[-2] == "1\n"
178192

179193

180194
if __name__ == "__main__":

gridded/tests/test_projected_ugrid.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -60,35 +60,40 @@
6060

6161
from gridded import VALID_UGRID_LOCATIONS
6262

63-
from .utilities import get_temp_test_file
63+
from .utilities import data_file_cache
6464

65+
# try:
66+
# data_file = get_temp_test_file("projected_coords_ugrid.nc")
67+
# if data_file is None:
68+
# # skip these tests if the data file couldn't be downloaded
69+
# pytestmark = pytest.mark.skip
70+
# except: # if anything went wrong, skip these.
71+
# pytestmark = pytest.mark.skip
6572

66-
try:
67-
data_file = get_temp_test_file("projected_coords_ugrid.nc")
68-
if data_file is None:
69-
# skip these tests if the data file couldn't be downloaded
70-
pytestmark = pytest.mark.skip
71-
except: # if anything went wrong, skip these.
72-
pytestmark = pytest.mark.skip
73-
73+
data_file = data_file_cache.fetch("projected_coords_ugrid.nc")
7474

7575
def test_load():
7676
"""
7777
The file should load without error
7878
"""
79-
ds = Dataset(data_file)
79+
ds = Dataset.from_netCDF(data_file)
8080

8181
assert isinstance(ds.grid, Grid_U)
8282

83+
print(ds.grid.nodes.max(), ds.grid.nodes.min())
84+
assert ds.grid.nodes.min() > 148_000 # definitely not lat-lon
85+
8386

8487
def test_find_variables():
8588
"""
8689
Does it find the variables?
8790
"""
88-
ds = Dataset(data_file)
91+
ds = Dataset.from_netCDF(data_file)
8992

9093
var_names = list(ds.variables.keys())
9194

95+
print(var_names)
96+
9297
all_vars = ['mesh2d_Numlimdt',
9398
'mesh2d_czs',
9499
'mesh2d_diu',

0 commit comments

Comments
 (0)