Skip to content

Commit

Permalink
Update(s) include f-strings.
Browse files Browse the repository at this point in the history
  • Loading branch information
vrettasm committed Mar 18, 2021
1 parent a4990db commit 832cc0e
Show file tree
Hide file tree
Showing 7 changed files with 163 additions and 140 deletions.
65 changes: 35 additions & 30 deletions code/src/hydraulic_conductivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,25 +36,25 @@ def __init__(self, sat_soil: float = 8.5, sat_saprolite: float = 3.2,
if sat_soil > 0.0:
self.param_sat_soil = sat_soil
else:
raise ValueError(" {0}: The saturated value of the Soil layer:"
" {1}, should be strictly positive.".format(self.__class__.__name__,
sat_soil))
raise ValueError(f" {self.__class__.__name__}:"
f" The saturated value of the Soil layer: "
f" {sat_soil} should be strictly positive.")
# _end_if_

if sat_saprolite > 0.0:
self.param_sat_saprolite = sat_saprolite
else:
raise ValueError(" {0}: The saturated value of the Saprolite layer:"
" {1}, should be strictly positive.".format(self.__class__.__name__,
sat_saprolite))
raise ValueError(f" {self.__class__.__name__}:"
f" The saturated value of the Saprolite layer: "
f" {sat_saprolite} should be strictly positive.")
# _end_if_

if sat_fresh_bedrock > 0.0:
self.param_sat_fresh_bedrock = sat_fresh_bedrock
else:
raise ValueError(" {0}: The saturated value of the Fresh Bedrock layer:"
" {1}, should be strictly positive.".format(self.__class__.__name__,
sat_fresh_bedrock))
raise ValueError(f" {self.__class__.__name__}:"
f" The saturated value of the Fresh Bedrock layer: "
f" {sat_fresh_bedrock} should be strictly positive.")
# _end_if_

# Noise related variables.
Expand Down Expand Up @@ -87,9 +87,9 @@ def sat_soil(self, new_value):
self.param_sat_soil = new_value
else:
# Raise an error with a message.
raise ValueError(" {0}: The saturated value of the Soil layer:"
" {1}, should be strictly positive.".format(self.__class__.__name__,
new_value))
raise ValueError(f" {self.__class__.__name__}:"
f" The saturated value of the Soil layer: "
f" {new_value} should be strictly positive.")
# _end_if_
# _end_def_

Expand Down Expand Up @@ -118,9 +118,9 @@ def sat_saprolite(self, new_value):
self.param_sat_saprolite = new_value
else:
# Raise an error with a message.
raise ValueError(" {0}: The saturated value of the Saprolite layer:"
" {1}, should be strictly positive.".format(self.__class__.__name__,
new_value))
raise ValueError(f" {self.__class__.__name__}:"
f" The saturated value of the Saprolite layer:"
f" {new_value} should be strictly positive.")
# _end_if_
# _end_def_

Expand Down Expand Up @@ -149,9 +149,9 @@ def sat_fresh_bedrock(self, new_value):
self.param_sat_fresh_bedrock = new_value
else:
# Raise an error with a message.
raise ValueError(" {0}: The saturated value of the Fresh Bedrock layer:"
" {1}, should be strictly positive.".format(self.__class__.__name__,
new_value))
raise ValueError(f" {self.__class__.__name__}:"
f" The saturated value of the Fresh Bedrock layer:"
f" {new_value} should be strictly positive.")
# _end_if_
# _end_def_

Expand Down Expand Up @@ -180,9 +180,9 @@ def sigma_noise(self, new_value):
self.param_sigma_noise = new_value
else:
# Raise an error with a message.
raise ValueError(" {0}: The sigma amplitude value of the noise model:"
" {1}, should be non-negative.".format(self.__class__.__name__,
new_value))
raise ValueError(f" {self.__class__.__name__}:"
f" The sigma amplitude value of the noise model:"
f" {new_value} should be non-negative.")
# _end_if_
# _end_def_

Expand Down Expand Up @@ -211,9 +211,9 @@ def lambda_exponent(self, new_value):
self.param_lambda_exponent = new_value
else:
# Raise an error with a message.
raise ValueError(" {0}: The lambda exponent value of the noise model:"
" {1}, should be non-negative.".format(self.__class__.__name__,
new_value))
raise ValueError(f" {self.__class__.__name__}:"
f" The lambda exponent value of the noise model:"
f" {new_value} should be non-negative.")
# _end_if_
# _end_def_

Expand All @@ -223,13 +223,18 @@ def __str__(self):
Override to print a readable string presentation of the object.
This will include its id(), along with its fields values.
:return: a string representation of a HydraulicConductivity object.
:return: a string representation of a HydraulicConductivity.
"""
return " HydraulicConductivity Id({0}):"\
" Sat-Soil={1}, Sat-Saprolite={2}, Sat-Fresh-Bedrock={3},"\
" Sigma={4}, Lambda={5}".format(id(self), self.sat_soil, self.sat_saprolite,
self.sat_fresh_bedrock, self.sigma_noise,
self.lambda_exponent)
# New line character.
new_line = '\n'

# Return the string.
return f" HydraulicConductivity Id({id(self)}): {new_line}"\
f" Sat-Soil={self.sat_soil} {new_line}"\
f" Sat-Saprolite={self.sat_saprolite} {new_line}"\
f" Sat-Fresh-Bedrock={self.sat_fresh_bedrock} {new_line}"\
f" Sigma={self.sigma_noise} {new_line}"\
f" Lambda={self.lambda_exponent}"
# _end_def_

# _end_class_
13 changes: 7 additions & 6 deletions code/src/porosity.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,14 @@ def __init__(self, z_grid, layers, theta, soil, p_model):

# Make sure the z-grid domain is not empty.
if not z_grid.size:
raise ValueError(" {0}: Input array z_grid is empty.".format(self.__class__.__name__))
raise ValueError(f" {self.__class__.__name__}:"
f" Input array z_grid is empty.")
# _end_if_

# Make sure the z-grid domain is increasing.
if np.any(np.diff(z_grid) <= 0.0):
raise RuntimeError(" {0}: Space domain z_grid is not"
" increasing.".format(self.__class__.__name__))
raise RuntimeError(f" {self.__class__.__name__}:"
f" Space domain z_grid is not increasing.")
# _end_if_

# Store the type of profile.
Expand Down Expand Up @@ -157,8 +158,8 @@ def __init__(self, z_grid, layers, theta, soil, p_model):
# _end_if_

else:
raise ValueError(" {0}: Wrong porosity profile type:"
" {1}".format(self.__class__.__name__, p_model))
raise ValueError(f" {self.__class__.__name__}:"
f" Wrong porosity profile type: {p_model}")
# _end_if_

# Safeguard: make sure this profile is [MIN <= q_sat <= MAX]
Expand Down Expand Up @@ -223,7 +224,7 @@ def __str__(self):
:return: a string representation of a Porosity object.
"""
return " Porosity Id({0}): Type={1}".format(id(self), self.p_model)
return f" Porosity Id({id(self)}): Type={self.p_model}"
# _end_def_

# _end_class_
20 changes: 10 additions & 10 deletions code/src/richards_pde.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ def __init__(self, m_data=None):

# Check if we have been given input.
if m_data is None:
raise ValueError(" {0}: No input is given. The model"
" cannot initialize.".format(self.__class__.__name__))
raise ValueError(f" {self.__class__.__name__}:"
f" No input is given. The model cannot initialize.")
# _end_if_

# Variable output arguments.
Expand All @@ -59,8 +59,8 @@ def __init__(self, m_data=None):

# Make sure the space domain is increasing (downwards).
if np.any(dx <= 0.0):
raise RuntimeError(" {0}: Space domain is not"
" increasing.".format(self.__class__.__name__))
raise RuntimeError(f" {self.__class__.__name__}:"
f" Space domain is not increasing.")
# _end_if_

# Initialize the $nx-1$ mid-points where functions will be evaluated.
Expand Down Expand Up @@ -526,8 +526,8 @@ def solve(self, t_span, y0, *args):

# If we reach here the solver failed to integrate successfully.
if n_trials == 0:
print(" {0}: The ODE solver failed with message:"
" {1}".format(self.__class__.__name__, sol_t.message))
print(f" {self.__class__.__name__}:"
f" The ODE solver failed with message: {sol_t.message}")
# _end_if_
# _end_if_
# _end_while_
Expand Down Expand Up @@ -560,14 +560,14 @@ def midpoints(x_left, fx_left, x_right, fx_right):

# Check for input mis-match.
if fx_left.shape != fx_right.shape:
raise RuntimeError(" midpoints: Input 'fx' dimensions do not match."
" {0} not equal to {1}".format(fx_left.shape, fx_right.shape))
raise RuntimeError(f" midpoints: Input 'fx' dimensions do not match."
f" {fx_left.shape} not equal to {fx_right.shape}.")
# _end_if_

# Check for input mis-match.
if x_left.shape != x_right.shape:
raise RuntimeError(" midpoints: Input 'x' dimensions do not match."
" {0} not equal to {1}".format(x_left.shape, x_right.shape))
raise RuntimeError(f" midpoints: Input 'x' dimensions do not match."
f" {x_left.shape} not equal to {x_right.shape}. ")
# _end_if_

# Use a simple (arithmetic) average to approximate
Expand Down
69 changes: 37 additions & 32 deletions code/src/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,17 @@ def setupModel(self, params, data):

# Check if the Well number exists in the site info file.
if not str(self.mData["Well_No"]) in site_info["Well"]:
raise ValueError(" {0}: The selected well does not exist"
" in the site information file.".format(self.__class__.__name__))
raise ValueError(f" {self.__class__.__name__}:"
f" The selected well does not exist in the site information file.")
# _end_if_

# Extract the Well information.
well = site_info["Well"][str(self.mData["Well_No"])]

# Make sure the well is not defined as fully saturated.
if well["sat_depth"] >= well["max_depth"]:
raise RuntimeError(" {0}: The well seems fully saturated.".format(self.__class__.__name__))
raise RuntimeError(f" {self.__class__.__name__}:"
f" The well seems fully saturated.")
# _end_if_

# Compute the number of continuously saturated cell (from the bottom).
Expand Down Expand Up @@ -149,8 +150,8 @@ def setupModel(self, params, data):
params["Soil_Properties"]["epsilon"])
except Exception as e0:
# Display the error message.
print(" SoilProperties failed to initialize: {}.\n"
" It will use default initialization parameters.".format(e0))
print(f" SoilProperties failed to initialize: {e0}."
f" It will use default initialization parameters.")

# Default initialization.
soil = SoilProperties()
Expand All @@ -168,8 +169,8 @@ def setupModel(self, params, data):
params["Water_Content"]["Field_Capacity_cm"])
except Exception as e0:
# Display the error message.
print(" WaterContent failed to initialize: {}.\n"
" It will use default initialization parameters.".format(e0))
print(f" WaterContent failed to initialize: {e0}."
f" It will use default initialization parameters.")

# Default initialization.
theta = WaterContent()
Expand All @@ -187,8 +188,8 @@ def setupModel(self, params, data):
params["Hydraulic_Conductivity"]["Lambda_Exponent"])
except Exception as e0:
# Display the error message.
print(" HydraulicConductivity failed to initialize: {}.\n"
" It will use default initialization parameters.".format(e0))
print(f" HydraulicConductivity failed to initialize: {e0}."
f" It will use default initialization parameters.")

# Default initialization.
K = HydraulicConductivity()
Expand Down Expand Up @@ -245,8 +246,8 @@ def setupModel(self, params, data):

# Check if there are NaN values.
if np.any(np.isnan(z_wtd_cm)):
raise RuntimeError(" {0}: Water table depth observations"
" contain NaN values.".format(self.__class__.__name__))
raise RuntimeError(f" {self.__class__.__name__}:"
f" Water table depth observations contain NaN values.")
# _end_if_

# Since the observational data are not "gridded" we put them
Expand All @@ -258,8 +259,8 @@ def setupModel(self, params, data):

# Check if there are NaN values.
if np.any(np.isnan(precip_cm)):
raise ValueError(" {0}: Precipitation observations"
" contain NaN values.".format(self.__class__.__name__))
raise ValueError(f" {self.__class__.__name__}:"
f" Precipitation observations contain NaN values.")
# _end_if_

# Store to dictionary.
Expand Down Expand Up @@ -371,12 +372,12 @@ def setupModel(self, params, data):

# Check if the dimensions match.
if z_grid.shape != init_cond.shape:
raise RuntimeError(" {0} : IC vector's dimensions do not match"
" the spatial grid.".format(self.__class__.__name__))
raise RuntimeError(f" {self.__class__.__name__}:"
f" IC vector's dimensions do not match the spatial grid.")
# _end_if_

# Print a message.
print(" IC vector was loaded successfully from: {0}.".format(ic_data_file))
print(f" IC vector was loaded successfully from: {ic_data_file}.")
# _end_with_

# Create an initial conditions vector.
Expand All @@ -396,9 +397,12 @@ def initial_conditions(self):
# [WARNING] Set the flag to TRUE!
self.mData["sim_flags"]["SPINUP"] = True

# Extract the well number.
well_no = self.mData["Well_No"]

# Display info.
print("\n [Initial Conditions for Well no. {0}]"
" Burn in period started ...".format(self.mData["Well_No"]))
print(f" [Initial Conditions for Well no. {well_no}]"
f" Burn in period started ...")

# Spatial domain.
z = self.mData["z_grid"]
Expand Down Expand Up @@ -461,23 +465,24 @@ def initial_conditions(self):

# Repeat the burn-in integration as long as the distance
# between the two solutions is above a threshold value.
if abs_error <= (2.0 * dz) and mse_0 <= 0.01:
if abs_error <= (2.0 * dz) and (mse_0 <= 0.01):
# Change the flag.
early_stop = True

# Display final message.
print(" [Initial Conditions for Well no. {0}] finished at [itr: {1}] with"
" [abs(error): {2}] and [MSE: {3}] \n".format(self.mData["Well_No"],
j, abs_error, mse_0))
print(f" [Initial Conditions for Well no. {well_no}]"
f" finished at [itr: {j}] with [abs(error): {abs_error}]"
f" and [MSE: {mse_0}]")

# Exit the loop.
break
# _end_if_
# _end_for_

# At this point the algorithm has reached maximum number of iterations.
if not early_stop:
print(" [Initial Conditions for Well no. {0}]"
" finished at maximum number of iterations.\n".format(self.mData["Well_No"]))
print(f" [Initial Conditions for Well no. {well_no}]"
f" finished at maximum number of iterations.")
# _end_of_

# [WARNING] Set the flag to TRUE!
Expand All @@ -489,16 +494,16 @@ def initial_conditions(self):

def run(self):
"""
Runs the PDE model forward in time. All the output information is store in
self.output dictionary, where we can later save it to the disk for further
analysis.
Runs the PDE model forward in time. All the output information
is store in self.output dictionary, where we can later save it
to the disk for further analysis.
:return: None
"""
# Check if the model parameters have been initialized.
if not self.mData:
raise RuntimeError(" {0}: Simulation data structure"
" 'mData' is empty.".format(self.__class__.__name__))
raise RuntimeError(f" {self.__class__.__name__}:"
f" Simulation data structure 'mData' is empty.")
# _end_if_

# Transpiration and lateral flow values.
Expand Down Expand Up @@ -678,11 +683,11 @@ def saveResults(self):
# Check if the output dictionary is empty.
if not self.output:
# Print a message and do not save anything.
print(" {0}: Simulation data structure 'output'"
" is empty.".format(self.__class__.__name__))
print(f" {self.__class__.__name__}:"
f" Simulation data structure 'output' is empty.")
else:
# Initial message.
print(" Saving the results to: {0}.h5".format(self.name))
print(f" Saving the results to: {self.name}.h5")

# Create the output filename. Remove spaces (if any).
file_out = Path(self.name.strip().replace(" ", "_") + ".h5")
Expand Down
Loading

0 comments on commit 832cc0e

Please sign in to comment.