Skip to content

Commit e834e9e

Browse files
Merge pull request #48 from EcoExtreML/forcing_mat
Avoid locale issues in generating forcing .mat files
2 parents beb341f + 27fd011 commit e834e9e

3 files changed

Lines changed: 32 additions & 1 deletion

File tree

PyStemmusScope/forcing_io.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import hdf5storage
33
import numpy as np
44
import xarray as xr
5+
from . import utils
56
from . import variable_conversion as vc
67

78

@@ -159,7 +160,8 @@ def prepare_global_variables(data, input_path, config):
159160

160161
matfiledata['Dur_tot'] = float(total_duration) # Matlab expects a 'double'
161162

162-
hdf5storage.savemat(input_path / 'forcing_globals.mat', matfiledata, appendmat=False)
163+
hdf5storage.savemat(input_path / "forcing_globals.mat", matfiledata, appendmat=False)
164+
utils.remove_dates_from_header(input_path / "forcing_globals.mat")
163165

164166

165167
def prepare_forcing(config):

PyStemmusScope/soil_io.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,4 @@ def prepare_soil_data(config):
227227
hdf5storage.savemat(
228228
Path(config["InputPath"]) / "soil_parameters.mat", mdict=matfiledata, appendmat=False,
229229
)
230+
utils.remove_dates_from_header(Path(config["InputPath"]) / "soil_parameters.mat")

PyStemmusScope/utils.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,31 @@ def to_absolute_path(
6767
must_exist = os_name() == 'nt'
6868

6969
return pathlike.expanduser().resolve(strict=must_exist)
70+
71+
72+
def remove_dates_from_header(filename):
73+
"""Removes the datetime string from the .mat file header.
74+
75+
MATLAB raises an error when some characters are non-UTF-8 (?), e.g. Chinese month
76+
names. This function removes this part of the file header to avoid this problem.
77+
78+
Args:
79+
filename (Path): Valid path to the .mat file
80+
"""
81+
with open(filename, "rb") as f:
82+
data = f.read()
83+
84+
# Get locations of date string in header
85+
start_datestring = data[:128].find(b"Created on:") + 12
86+
end_datestring = data[:128].find(b"HDF5") - 1
87+
88+
# Rebuild the data, with the dates in the header removed
89+
sanitized_data = (
90+
data[:start_datestring] +
91+
b' '*len(data[start_datestring:end_datestring]) +
92+
data[end_datestring:]
93+
)
94+
95+
# Overwrite the old file
96+
with open(filename, 'wb') as file:
97+
file.write(sanitized_data)

0 commit comments

Comments
 (0)