Skip to content

Commit

Permalink
refactor(FlopyBinaryData): make properties readonly, deprecate set_fl…
Browse files Browse the repository at this point in the history
…oat() (#2421)

Minor cleanup. Use properties instead of attributes. Deprecate set_float() and replace usages with precision setter.
  • Loading branch information
wpbonelli authored Jan 20, 2025
1 parent 1f9c0e3 commit ef5ca6a
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 41 deletions.
36 changes: 18 additions & 18 deletions flopy/mf6/utils/binarygrid_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def __init__(self, filename, precision="double", verbose=False):
super().__init__()

# set attributes
self.set_float(precision=precision)
self.precision = precision
self.verbose = verbose
self._initial_len = 50
self._recorddict = {}
Expand All @@ -83,7 +83,7 @@ def __init__(self, filename, precision="double", verbose=False):
t = line.split()
self._version = t[1]

# version
# ntxt
line = self.read_text(self._initial_len).strip()
t = line.split()
self._ntxt = int(t[1])
Expand Down Expand Up @@ -154,20 +154,20 @@ def __init__(self, filename, precision="double", verbose=False):
self.file.close()

# initialize the model grid to None
self.__modelgrid = None
self._modelgrid = None

# set ia and ja
self.__set_iaja()
self._set_iaja()

# internal functions
def __set_iaja(self):
def _set_iaja(self):
"""
Set ia and ja from _datadict.
"""
self._ia = self._datadict["IA"] - 1
self._ja = self._datadict["JA"] - 1

def __set_modelgrid(self):
def _set_modelgrid(self):
"""
Define structured, vertex, or unstructured grid based on MODFLOW 6
discretization type.
Expand Down Expand Up @@ -246,11 +246,11 @@ def __set_modelgrid(self):
except:
print(f"could not set model grid for {self.file.name}")

self.__modelgrid = modelgrid
self._modelgrid = modelgrid

return

def __build_vertices_cell2d(self):
def _build_vertices_cell2d(self):
"""
Build the mf6 vertices and cell2d array to generate a VertexGrid
Expand All @@ -268,7 +268,7 @@ def __build_vertices_cell2d(self):
]
return vertices, cell2d

def __get_iverts(self):
def _get_iverts(self):
"""
Get a list of the vertices that define each model cell.
Expand All @@ -292,7 +292,7 @@ def __get_iverts(self):
print(f"returning iverts from {self.file.name}")
return iverts

def __get_verts(self):
def _get_verts(self):
"""
Get a list of the x, y pair for each vertex from the data in the
binary grid file.
Expand All @@ -317,7 +317,7 @@ def __get_verts(self):
print(f"returning verts from {self.file.name}")
return verts

def __get_cellcenters(self):
def _get_cellcenters(self):
"""
Get the cell centers centroids for a MODFLOW 6 GWF model that uses
the DISV or DISU discretization.
Expand Down Expand Up @@ -689,7 +689,7 @@ def iverts(self):
-------
iverts : list of lists of ints
"""
return self.__get_iverts()
return self._get_iverts()

@property
def verts(self):
Expand All @@ -700,7 +700,7 @@ def verts(self):
-------
verts : ndarray of floats
"""
return self.__get_verts()
return self._get_verts()

@property
def cellcenters(self):
Expand All @@ -711,7 +711,7 @@ def cellcenters(self):
-------
cellcenters : ndarray of floats
"""
return self.__get_cellcenters()
return self._get_cellcenters()

@property
def modelgrid(self):
Expand All @@ -722,9 +722,9 @@ def modelgrid(self):
-------
modelgrid : StructuredGrid, VertexGrid, UnstructuredGrid
"""
if self.__modelgrid is None:
self.__set_modelgrid()
return self.__modelgrid
if self._modelgrid is None:
self._set_modelgrid()
return self._modelgrid

@property
def cell2d(self):
Expand All @@ -736,7 +736,7 @@ def cell2d(self):
cell2d : list of lists
"""
if self._grid_type in ("DISV", "DISV2D", "DISV1D"):
vertices, cell2d = self.__build_vertices_cell2d()
vertices, cell2d = self._build_vertices_cell2d()
else:
vertices, cell2d = None, None
return vertices, cell2d
6 changes: 3 additions & 3 deletions flopy/utils/observationfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ def __init__(self, filename, verbose=False, isBinary="auto"):
precision = "single"
if "double" in cline[5:11].lower():
precision = "double"
self.set_float(precision)
self.precision = precision
lenobsname = int(cline[11:])

# get number of observations
Expand Down Expand Up @@ -370,7 +370,7 @@ def __init__(self, filename, verbose=False, hydlbl_len=20):
if self.nobs < 0:
self.nobs = abs(self.nobs)
precision = "double"
self.set_float(precision)
self.precision = precision

# continue reading the file
self.itmuni = self.read_integer()
Expand Down Expand Up @@ -438,7 +438,7 @@ def __init__(self, filename, precision="double", verbose=False):
"""
super().__init__()
self.set_float(precision=precision)
self.precision = precision
# initialize class information
self.verbose = verbose
# open binary head file
Expand Down
2 changes: 1 addition & 1 deletion flopy/utils/swroutputfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def __init__(self, filename, swrtype="stage", precision="double", verbose=False)
"""
super().__init__()
self.set_float(precision=precision)
self.precision = precision
self.header_dtype = np.dtype(
[
("totim", self.floattype),
Expand Down
84 changes: 65 additions & 19 deletions flopy/utils/utils_def.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,85 @@
"""

from datetime import timedelta
from typing import Literal, get_args
from warnings import warn

import numpy as np

Precision = Literal["single", "double"]


class FlopyBinaryData:
"""
The FlopyBinaryData class is a class to that defines the data types for
integer, floating point, and character data in MODFLOW binary
files. The FlopyBinaryData class is the super class from which the
specific derived classes are formed. This class should not be
instantiated directly.
Defines integer, floating point, and character data types for
MODFLOW binary files.
"""

def __init__(self):
self.integer = np.int32
self.integerbyte = self.integer(1).nbytes
self.precision = "double"

@property
def integer(self) -> type:
return np.int32

@property
def integerbyte(self) -> int:
return self.integer(1).nbytes

@property
def character(self) -> type:
return np.uint8

@property
def textbyte(self) -> int:
return 1

@property
def precision(self) -> Precision:
return self._precision

@precision.setter
def precision(self, value: Precision):
if value not in get_args(Precision):
raise ValueError(
f"Invalid floating precision '{value}', expected 'single' or 'double'"
)

value = value.lower()
self._precision = value
if value == "double":
self._real = np.float64
self._floattype = "f8"
else:
self._real = np.float32
self._floattype = "f4"
self._realbyte = self.real(1).nbytes

self.character = np.uint8
self.textbyte = 1
@property
def real(self) -> type:
return self._real

return
@property
def realbyte(self) -> int:
return self._realbyte

@property
def floattype(self) -> str:
return self._floattype

def set_float(self, precision):
"""
Set floating point precision.
.. deprecated:: 3.5
This method will be removed in Flopy 3.10+.
Use ``precision`` property setter instead.
"""
warn(
"set_float() is deprecated, use precision property setter instead",
PendingDeprecationWarning,
)
self.precision = precision
if precision.lower() == "double":
self.real = np.float64
self.floattype = "f8"
else:
self.real = np.float32
self.floattype = "f4"
self.realbyte = self.real(1).nbytes
return

def read_text(self, nchar=20):
bytesvalue = self._read_values(self.character, nchar).tobytes()
Expand Down

0 comments on commit ef5ca6a

Please sign in to comment.