Exporting to netCDF and shapefile
[1]:
import os
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
import git
import pooch
import flopy
print(sys.version)
print(f"flopy version: {flopy.__version__}")
3.12.10 | packaged by conda-forge | (main, Apr 10 2025, 22:21:13) [GCC 13.3.0]
flopy version: 3.9.3
Load our old friend…the Freyberg model
[2]:
sim_name = "freyberg_multilayer_transient"
Check if we are in the repository and define the data path.
[3]:
try:
root = Path(git.Repo(".", search_parent_directories=True).working_dir)
except:
root = None
[4]:
data_path = root / "examples" / "data" if root else Path.cwd()
[5]:
file_names = {
"freyberg.bas": None,
"freyberg.cbc": None,
"freyberg.ddn": None,
"freyberg.dis": None,
"freyberg.drn": None,
"freyberg.hds": None,
"freyberg.list": None,
"freyberg.nam": None,
"freyberg.nwt": None,
"freyberg.oc": None,
"freyberg.rch": None,
"freyberg.upw": None,
"freyberg.wel": None,
}
for fname, fhash in file_names.items():
pooch.retrieve(
url=f"https://github.com/modflowpy/flopy/raw/develop/examples/data/{sim_name}/{fname}",
fname=fname,
path=data_path / sim_name,
known_hash=fhash,
)
[6]:
nam_file = "freyberg.nam"
model_ws = data_path / sim_name
ml = flopy.modflow.Modflow.load(nam_file, model_ws=model_ws, check=False)
We can see the Modelgrid instance has generic entries, as does start_datetime
[7]:
ml.modelgrid
[7]:
xll:622241.1904510253; yll:3343617.741737109; rotation:15.0; crs:EPSG:32614; units:meters; lenuni:2
[8]:
ml.modeltime.start_datetime
[8]:
datetime.datetime(2015, 1, 1, 0, 0)
Setting the attributes of the ml.modelgrid is easy:
[9]:
ml.modelgrid.set_coord_info(xoff=123456.7, yoff=765432.1, angrot=15.0, crs=3070)
ml.dis.start_datetime = "7/4/1776"
[10]:
ml.modeltime.start_datetime
[10]:
datetime.datetime(1776, 7, 4, 0, 0)
Basic netCDF export capabilities
[11]:
# temporary directory
temp_dir = TemporaryDirectory()
pth = temp_dir.name
[12]:
# export the whole model (inputs and outputs)
fnc = ml.export(os.path.join(pth, f"{ml.name}.in.nc"))
initialize_geometry::
model crs: EPSG:3070
initialize_geometry::nc_crs = EPSG:4326
transforming coordinates using = unavailable until proj_trans is called
/home/runner/micromamba/envs/flopy/lib/python3.12/site-packages/flopy/export/netcdf.py:700: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
"date_created", datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
[13]:
# export outputs using spatial reference info
hds = flopy.utils.HeadFile(os.path.join(model_ws, "freyberg.hds"))
flopy.export.utils.output_helper(
os.path.join(pth, f"{ml.name}.out.nc"), ml, {"hds": hds}
)
initialize_geometry::
model crs: EPSG:3070
initialize_geometry::nc_crs = EPSG:4326
transforming coordinates using = unavailable until proj_trans is called
/home/runner/micromamba/envs/flopy/lib/python3.12/site-packages/flopy/export/netcdf.py:700: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
"date_created", datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
[13]:
<flopy.export.netcdf.NetCdf at 0x7f8cbd16b230>
Export an array to netCDF or shapefile
[14]:
# export a 2d array
ml.dis.top.export(os.path.join(pth, "top.nc"))
ml.dis.top.export(os.path.join(pth, "top.shp"))
initialize_geometry::
model crs: EPSG:3070
initialize_geometry::nc_crs = EPSG:4326
transforming coordinates using = unavailable until proj_trans is called
/home/runner/micromamba/envs/flopy/lib/python3.12/site-packages/flopy/export/netcdf.py:700: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
"date_created", datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
sparse export of stress period data for a boundary condition package
excludes cells that aren’t in the package (aren’t in
package.stress_period_data)by default, stress periods with duplicate parameter values (e.g., stage, conductance, etc.) are omitted (
squeeze=True); only stress periods with different values are exportedargue
squeeze=Falseto export all stress periods
[15]:
ml.drn.stress_period_data.export(os.path.join(pth, "drn.shp"), sparse=True)
/home/runner/micromamba/envs/flopy/lib/python3.12/site-packages/geopandas/_compat.py:7: DeprecationWarning: The 'shapely.geos' module is deprecated, and will be removed in a future version. All attributes of 'shapely.geos' are available directly from the top-level 'shapely' namespace (since shapely 2.0.0).
import shapely.geos
Export a 3d array
[16]:
# export a 3d array
ml.upw.hk.export(os.path.join(pth, "hk.nc"))
ml.upw.hk.export(os.path.join(pth, "hk.shp"))
initialize_geometry::
model crs: EPSG:3070
initialize_geometry::nc_crs = EPSG:4326
transforming coordinates using = unavailable until proj_trans is called
/home/runner/micromamba/envs/flopy/lib/python3.12/site-packages/flopy/export/netcdf.py:700: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
"date_created", datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
Export a number of things to the same netCDF file
[17]:
# export lots of things to the same nc file
fnc = ml.dis.botm.export(os.path.join(pth, "test.nc"))
ml.upw.hk.export(fnc)
ml.dis.top.export(fnc)
# export transient 2d
ml.rch.rech.export(fnc)
initialize_geometry::
model crs: EPSG:3070
initialize_geometry::nc_crs = EPSG:4326
transforming coordinates using = unavailable until proj_trans is called
/home/runner/micromamba/envs/flopy/lib/python3.12/site-packages/flopy/export/netcdf.py:700: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
"date_created", datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
[17]:
<flopy.export.netcdf.NetCdf at 0x7f8cb81829f0>
Export a package to netCDF
[18]:
# export mflist
fnc = ml.wel.export(os.path.join(pth, "packages.nc"))
ml.upw.export(fnc)
/home/runner/micromamba/envs/flopy/lib/python3.12/site-packages/flopy/export/netcdf.py:700: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
"date_created", datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
initialize_geometry::
model crs: EPSG:3070
initialize_geometry::nc_crs = EPSG:4326
transforming coordinates using = unavailable until proj_trans is called
[18]:
<flopy.export.netcdf.NetCdf at 0x7f8cb81a2630>
Export an entire model to netCDF
[19]:
fnc = ml.export(os.path.join(pth, "model.nc"))
initialize_geometry::
model crs: EPSG:3070
initialize_geometry::nc_crs = EPSG:4326
transforming coordinates using = unavailable until proj_trans is called
/home/runner/micromamba/envs/flopy/lib/python3.12/site-packages/flopy/export/netcdf.py:700: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
"date_created", datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
Export model outputs to netCDF
FloPy has utilities to export model outputs to a netcdf file. Valid output types for export are MODFLOW binary head files, formatted head files, cell budget files, seawat concentration files, and zonebudget output.
Let’s use output from the Freyberg model as an example of these functions
[20]:
# load binary head and cell budget files
fhead = os.path.join(model_ws, "freyberg.hds")
fcbc = os.path.join(model_ws, "freyberg.cbc")
hds = flopy.utils.HeadFile(fhead)
cbc = flopy.utils.CellBudgetFile(fcbc)
export_dict = {"hds": hds, "cbc": cbc}
# export head and cell budget outputs to netcdf
fnc = flopy.export.utils.output_helper(os.path.join(pth, "output.nc"), ml, export_dict)
initialize_geometry::
model crs: EPSG:3070
initialize_geometry::nc_crs = EPSG:4326
transforming coordinates using = unavailable until proj_trans is called
/home/runner/micromamba/envs/flopy/lib/python3.12/site-packages/flopy/export/netcdf.py:700: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
"date_created", datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
error getting data for cell_by_cell_flowstorage at time 1.0:list index out of range
error getting data for cell_by_cell_flowstorage at time 1097.0:list index out of range
[21]:
try:
# ignore PermissionError on Windows
temp_dir.cleanup()
except:
pass