Skip to content

Commit d0d58d3

Browse files
authored
Fix error logging when csv file is missing (#86)
* Fix error logging when csv file is missing * Change BasicGrid to CellGrid Fix #85
1 parent 21d3990 commit d0d58d3

File tree

4 files changed

+70
-13
lines changed

4 files changed

+70
-13
lines changed

src/ismn/components.py

+12-6
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@
1919
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121
# SOFTWARE.
22+
2223
import os.path
2324
import sys
24-
from pygeogrids import BasicGrid
25+
from pygeogrids import CellGrid
2526
from typing import Union
2627

2728
import numpy as np
@@ -571,11 +572,13 @@ def coords(self) -> (list, list):
571572
return lons, lats
572573

573574
@property
574-
def grid(self) -> BasicGrid:
575+
def grid(self) -> CellGrid:
575576
"""
576577
Get grid for all Stations in Network
577578
"""
578-
return BasicGrid(*self.coords)
579+
# CellGrid is intentional
580+
lons, lats = self.coords
581+
return CellGrid(lons, lats, cells=np.full(len(lons), 0))
579582

580583
@property
581584
def n_stations(self) -> int:
@@ -694,7 +697,7 @@ class NetworkCollection(IsmnComponent):
694697
----------
695698
networks : OrderedDict
696699
Collection of network names and Networks
697-
grid : BasicGrid
700+
grid : CellGrid
698701
Grid that contains one point for each station in all networks.
699702
"""
700703

@@ -718,8 +721,11 @@ def __init__(self, networks):
718721
lons += net_lons
719722
lats += net_lats
720723

721-
self.grid = BasicGrid(lons, lats) if (len(lons) > 0 and
722-
len(lats) > 0) else None
724+
if (len(lons) > 0) and (len(lats) > 0):
725+
# Should be CellGrid
726+
self.grid: CellGrid = CellGrid(lons, lats, cells=np.full(len(lons), 0))
727+
else:
728+
self.grid = None
723729

724730
def __repr__(self, indent: str = ""):
725731
return ",\n".join([

src/ismn/filecollection.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -78,13 +78,14 @@ def _read_station_dir(
7878
root, csv[0], load_metadata=True, temp_root=temp_root)
7979
station_meta = static_meta_file.metadata
8080
except const.IsmnFileError as e:
81-
logger.warning(f"Error loading static meta file: {stat_dir}/{csv[0]}. "
81+
_csv = "*missing*" if len(csv) == 0 else csv[0]
82+
logger.warning(f"Error loading static meta file for {stat_dir}/{_csv}. "
8283
f"We will use the placeholder metadata here. "
8384
f"Error traceback: {traceback.format_exc()}")
8485
station_meta = MetaData(
8586
[MetaVar(k, v) for k, v in const.CSV_META_TEMPLATE.items()]
8687
)
87-
erroneous_files.append(os.path.join(str(root), str(csv[0])))
88+
erroneous_files.append(os.path.join(str(root.path), str(stat_dir), str(_csv)))
8889

8990
data_files = root.find_files(stat_dir, "*.stm")
9091

@@ -309,7 +310,8 @@ def build_from_scratch(
309310

310311
with open(os.path.join(log_path, log_filename), mode='a') as f:
311312
f.write("\n----- Summary: Erroneous Files -----\n")
312-
f.writelines(errors)
313+
for e in errors:
314+
f.write(f"{e}\n")
313315
f.write("\n-------------------------------------\n")
314316

315317
ismnlog.info(info)

src/ismn/interface.py

+51-2
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,6 @@ class ISMN_Interface:
127127
root : IsmnRoot
128128
ISMN data folder or .zip access
129129
130-
131130
Properties
132131
----------
133132
networks : OrderedDict
@@ -1021,4 +1020,54 @@ def print_climate_dict(self) -> None:
10211020

10221021
def close_files(self):
10231022
# close all open filehandlers
1024-
self.__file_collection.close()
1023+
self.__file_collection.close()
1024+
1025+
if __name__ == '__main__':
1026+
ds = ISMN_Interface("/home/wpreimes/shares/climers/Datapool/ISMN/01_raw/FullArchive_20240314")
1027+
1028+
idx_good = ds.metadata[
1029+
np.isin(ds.metadata[('frm_class', 'val')].values, ['representative', 'very representative'])].index
1030+
1031+
frm = ds.subset_from_ids(idx_good)
1032+
1033+
fig, ax = plt.subplots(figsize=(6, 4), subplot_kw={'projection': ccrs.PlateCarree()})
1034+
frm.plot_station_locations('soil_moisture', 0, 0.1,
1035+
check_only_sensor_depth_from=False,
1036+
borders=False, ax=ax, text_scalefactor=1.6)
1037+
1038+
fig.savefig("/tmp/frm.png", dpi=300)
1039+
1040+
fig, ax = plt.subplots(figsize=(12, 8), subplot_kw={'projection': ccrs.PlateCarree()})
1041+
1042+
frm.plot_station_locations('soil_moisture', 0, 0.1,
1043+
check_only_sensor_depth_from=False,
1044+
extent=[-179, 189, -60, 90],
1045+
borders=False, ax=ax, markersize=15,
1046+
text_scalefactor=2, stats_text=False)
1047+
1048+
fig.savefig("/tmp/frms.png", dpi=300)
1049+
plt.close(fig)
1050+
1051+
1052+
fig, ax = plt.subplots(figsize=(6, 4), subplot_kw={'projection': ccrs.PlateCarree()})
1053+
1054+
frm.plot_station_locations('soil_moisture', 0, 0.1,
1055+
check_only_sensor_depth_from=False,
1056+
extent=[-128, -64, 25, 50],
1057+
borders=True, ax=ax, stats_text=False,
1058+
markersize=11, text_scalefactor=0.7)
1059+
1060+
fig.savefig("/tmp/frms_usa.png", dpi=300)
1061+
1062+
1063+
plt.close(fig)
1064+
1065+
fig, ax = plt.subplots(figsize=(6, 4), subplot_kw={'projection': ccrs.PlateCarree()})
1066+
1067+
frm.plot_station_locations('soil_moisture', 0, 0.1,
1068+
check_only_sensor_depth_from=False,
1069+
extent=[-10, 33, 35, 70],
1070+
borders=True, ax=ax, stats_text=False,
1071+
markersize=11, text_scalefactor=0.7)
1072+
1073+
fig.savefig("/tmp/frms_eu.png", dpi=300)

tests/test_components.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
from datetime import datetime, timedelta
3333

3434
from ismn.components import NetworkCollection, Network, Station, Sensor, Depth
35-
from pygeogrids.grids import BasicGrid
35+
from pygeogrids.grids import CellGrid
3636
from tempfile import TemporaryDirectory
3737
import json
3838

@@ -119,7 +119,7 @@ def test_add_station(self):
119119
assert self.network.stations[name].lat == 0
120120
assert self.network.stations[name].elev == 0
121121

122-
assert self.network.grid == BasicGrid([0], [0])
122+
assert self.network.grid == CellGrid([0], [0], [0])
123123

124124
def test_remove_station(self):
125125
"""

0 commit comments

Comments
 (0)