Modelamiento de acuíferos colgados con Modflow6 y mf6Voronoi - Tutorial

Ejemplo aplicado para la simulación de un "doble" nivel freático en Modflow6 y mf6Voronoi sobre un modelo geoespacial. El tutorial cubre los desafíos, técnicas y una discusión sobre la formulación de Newton que permite la simulación de un nivel freático localizado por encima de un nivel freático regional.

Tutorial

Code


#get the latest modflow binary
from mf6Voronoi.utils import initiateOutputFolder
import flopy
from mf6Voronoi.utils import listTemplates, copyTemplate
binDir = '../bin'
initiateOutputFolder(binDir)
The output folder ../bin has been generated.
flopy.utils.get_modflow(binDir, subset=['mf6'])
fetched release '23.0' info from MODFLOW-ORG/executables
downloading 'https://github.com/MODFLOW-ORG/executables/releases/download/23.0/win64.zip' to 'C:\Users\saulm\Downloads\modflow_executables-23.0-win64.zip'
extracting 1 file to 'C:\Users\saulm\Documents\modelPerchedAquifersMF6voronoi\bin'
mf6.exe (6.6.3)
wrote new flopy metadata file: 'C:\Users\saulm\AppData\Local\flopy\get_modflow.json'
copyTemplate('generateVoronoi','perched')
copyTemplate('multilayeredTransient','perched')

Mesh generation

Part 1 : Voronoi mesh generation

import warnings ## Org
warnings.filterwarnings('ignore') ## Org

import os, sys ## Org
import geopandas as gpd ## Org
from mf6Voronoi.geoVoronoi import createVoronoi ## Org
from mf6Voronoi.meshProperties import meshShape ## Org
from mf6Voronoi.utils import initiateOutputFolder, getVoronoiAsShp ## Org
#Create mesh object specifying the coarse mesh and the multiplier
vorMesh = createVoronoi(meshName='perchedAquifer',maxRef = 20, multiplier=1.5) ## Org

#Open limit layers and refinement definition layers
vorMesh.addLimit('basin','../shp/modelLimit.shp') ## <=== updated
vorMesh.addLayer('ref','../shp/refArea.shp',8) ## <=== updated
vorMesh.addLayer('regionalFlow','../shp/regionalFlow.shp',8) ## <=== updated
#Generate point pair array
vorMesh.generateOrgDistVertices() ## Org

#Generate the point cloud and voronoi
vorMesh.createPointCloud() ## Org
vorMesh.generateVoronoi() ## Org
Hatarilabs

mf6Voronoi will have a web version in 2028

Follow us:

Hatarilabs Hatarilabs Hatarilabs Hatarilabs Hatarilabs Hatarilabs
/--------Layer ref discretization-------/
Progressive cell size list: [8, 20.0] m.

/--------Layer regionalFlow discretization-------/
Progressive cell size list: [8, 20.0] m.

/----Sumary of points for voronoi meshing----/
Distributed points from layers: 2
Points from layer buffers: 938
Points from max refinement areas: 683
Points from min refinement areas: 2294
Total points inside the limit: 4150
/--------------------------------------------/

Time required for point generation: 0.52 seconds 


/----Generation of the voronoi mesh----/

Time required for voronoi generation: 0.40 seconds
#Uncomment the next two cells if you have strong differences on discretization or you have encounter an FORTRAN error while running MODFLOW6
vorMesh.checkVoronoiQuality(threshold=0.01)
/----Performing quality verification of voronoi mesh----/
Short side on polygon: 4149 with length = 0.00028
Short side on polygon: 4149 with length = 0.00028
vorMesh.fixVoronoiShortSides()
vorMesh.generateVoronoi()
vorMesh.checkVoronoiQuality(threshold=0.01)
/----Generation of the voronoi mesh----/

Time required for voronoi generation: 0.47 seconds 


/----Performing quality verification of voronoi mesh----/
Your mesh has no edges shorter than your threshold
#Export generated voronoi mesh
initiateOutputFolder('../output') ## Org
getVoronoiAsShp(vorMesh.modelDis, shapePath='../output/'+vorMesh.modelDis['meshName']+'.shp') ## Org
The output folder ../output exists and has been cleared

/----Generation of the voronoi shapefile----/

Time required for voronoi shapefile: 0.93 seconds
# Show the resulting voronoi mesh

#open the mesh file
mesh=gpd.read_file('../output/'+vorMesh.modelDis['meshName']+'.shp') ## Org
#plot the mesh
mesh.plot(figsize=(35,25), fc='crimson', alpha=0.3, ec='teal') ## Org

Part 2 generate disv properties

# open the mesh file
mesh=meshShape('../output/'+vorMesh.modelDis['meshName']+'.shp') ## Org
# get the list of vertices and cell2d data
gridprops=mesh.get_gridprops_disv() ## Org
Creating a unique list of vertices [[x1,y1],[x2,y2],...]


100%|███████████████████████████████████████████████████████████████████████████| 4151/4151 [00:00<00:00, 18468.51it/s]



Extracting cell2d data and grid index


100%|████████████████████████████████████████████████████████████████████████████| 4151/4151 [00:01<00:00, 2428.66it/s]
#create folder
initiateOutputFolder('../json') ## Org

#export disv
mesh.save_properties('../json/disvDict.json') ## Org
The output folder ../json exists and has been cleared

Multilayer and transient model

Part 2a: generate disv properties

import sys, json, os ## Org
import rasterio, flopy ## Org
import numpy as np ## Org
import matplotlib.pyplot as plt ## Org
import geopandas as gpd ## Org
from mf6Voronoi.meshProperties import meshShape ## Org
from shapely.geometry import MultiLineString ## Org
from mf6Voronoi.tools.cellWork import getLayCellElevTupleFromRaster, getLayCellElevTupleFromElev
# open the json file
with open('../json/disvDict.json') as file: ## Org
    gridProps = json.load(file) ## Org
cell2d = gridProps['cell2d']           #cellid, cell centroid xy, vertex number and vertex id list
vertices = gridProps['vertices']       #vertex id and xy coordinates
ncpl = gridProps['ncpl']               #number of cells per layer
nvert = gridProps['nvert']             #number of verts
centroids=gridProps['centroids']       #cell centroids xy

Part 2b: Model construction and simulation

#Extract dem values for each centroid of the voronois
src = rasterio.open('../rst/modelDem.tif')  ## Org
elevation=[x for x in src.sample(centroids)] ## Org
nlay = 20 ## Org

mtop=np.array([elev[0] for i,elev in enumerate(elevation)]) ## Org
zbot=np.zeros((nlay,ncpl)) ## Org


AcuifInf_Bottom = 2300 ## Org
zbot[0,] = AcuifInf_Bottom + (0.95 * (mtop - AcuifInf_Bottom)) ## Org
zbot[1,] = AcuifInf_Bottom + (0.9 * (mtop - AcuifInf_Bottom)) ## Org
zbot[2,] = AcuifInf_Bottom + (0.875 * (mtop - AcuifInf_Bottom)) ## Org
zbot[3,] = AcuifInf_Bottom + (0.85 * (mtop - AcuifInf_Bottom)) ## Org
zbot[4,] = AcuifInf_Bottom + (0.825 * (mtop - AcuifInf_Bottom)) ## Org
zbot[5,] = AcuifInf_Bottom + (0.8 * (mtop - AcuifInf_Bottom)) ## Org
zbot[6,] = AcuifInf_Bottom + (0.775 * (mtop - AcuifInf_Bottom)) ## Org
zbot[7,] = AcuifInf_Bottom + (0.75 * (mtop - AcuifInf_Bottom)) ## Org
zbot[8,] = AcuifInf_Bottom + (0.725 * (mtop - AcuifInf_Bottom)) ## Org
zbot[9,] = AcuifInf_Bottom + (0.7 * (mtop - AcuifInf_Bottom)) ## Org
zbot[10,] = AcuifInf_Bottom + (0.675 * (mtop - AcuifInf_Bottom)) ## Org
zbot[11,] = AcuifInf_Bottom + (0.65 * (mtop - AcuifInf_Bottom)) ## Org
zbot[12,] = AcuifInf_Bottom + (0.625 * (mtop - AcuifInf_Bottom)) ## Org
zbot[13,] = AcuifInf_Bottom + (0.6 * (mtop - AcuifInf_Bottom)) ## Org
zbot[14,] = AcuifInf_Bottom + (0.5 * (mtop - AcuifInf_Bottom)) ## Org
zbot[15,] = AcuifInf_Bottom + (0.4 * (mtop - AcuifInf_Bottom)) ## Org
zbot[16,] = AcuifInf_Bottom + (0.3 * (mtop - AcuifInf_Bottom)) ## Org
zbot[17,] = AcuifInf_Bottom + (0.2 * (mtop - AcuifInf_Bottom)) ## Org
zbot[18,] = AcuifInf_Bottom + (0.1 * (mtop - AcuifInf_Bottom)) ## Org
zbot[19,] = AcuifInf_Bottom ## Org

Create simulation and model

# create simulation
simName = 'mf6Sim' ## Org
modelName = 'mf6Model' ## Org
modelWs = '../modelFiles' ## Org
sim = flopy.mf6.MFSimulation(sim_name=modelName, version='mf6', ## Org
                             exe_name='../bin/mf6.exe', ## Org
                             continue_=True,
                             sim_ws=modelWs) ## Org
# create tdis package
tdis_rc = [(86400*365*80,1,1)]+[(86400*365*30, 3, 1.5) for level in range(2)] 
print(tdis_rc[:3]) ## Org

tdis = flopy.mf6.ModflowTdis(sim, pname='tdis', time_units='SECONDS', ## Org
                             perioddata=tdis_rc, ## Org
                            nper=3) ## Org
[(2522880000, 1, 1), (946080000, 3, 1.5), (946080000, 3, 1.5)]
# create gwf model
gwf = flopy.mf6.ModflowGwf(sim, ## Org
                           modelname=modelName, ## Org
                           save_flows=True, ## Org
                           newtonoptions="NEWTON UNDER_RELAXATION") ## Org
# create iterative model solution and register the gwf model with it
ims = flopy.mf6.ModflowIms(sim, ## Org
                           complexity='COMPLEX', ## Org
                           outer_maximum=150, ## Org
                           inner_maximum=50, ## Org
                           outer_dvclose=0.1, ## Org
                           inner_dvclose=0.0001, ## Org
                           backtracking_number=20, ## Org
                           linear_acceleration='BICGSTAB') ## Org
sim.register_ims_package(ims,[modelName]) ## Org
# disv
disv = flopy.mf6.ModflowGwfdisv(gwf, nlay=nlay, ncpl=ncpl, ## Org
                                top=mtop, botm=zbot, ## Org
                                nvert=nvert, vertices=vertices, ## Org
                                cell2d=cell2d) ## Org
disv.top.plot(figsize=(12,8), alpha=0.8) ## Org
crossSection = gpd.read_file('../shp/crossSection.shp') ## Org
sectionLine =list(crossSection.iloc[0].geometry.coords) ## Org

fig, ax = plt.subplots(figsize=(12,8)) ## Org
modelxsect = flopy.plot.PlotCrossSection(model=gwf, line={'Line': sectionLine}) ## Org
linecollection = modelxsect.plot_grid(lw=0.5) ## Org
ax.grid() ## Org
# initial conditions

ic = flopy.mf6.ModflowGwfic(gwf, strt=np.stack([mtop for i in range(nlay)])) ## Org
#headsInitial = np.load('npy/headCalibInitial.npy')
#ic = flopy.mf6.ModflowGwfic(gwf, strt=headsInitial)
KxArray = np.ones((nlay, ncpl)) * 4e-4
KxArray[1:6] = 5e-6
KxArray[6:15] = 3e-6
KxArray[15:] = 7e-7
icelltype = [1 for x in range(15)] + [0 for x in range(nlay - 15)] 

interIx = flopy.utils.gridintersect.GridIntersect(gwf.modelgrid) ## Org
layCellTupleList = getLayCellElevTupleFromElev(gwf,
                                           interIx,
                                           2400,
                                           '../shp/impermeableLens.shp')
for layCellTuple in layCellTupleList:
    KxArray[layCellTuple[0],layCellTuple[1]] = 1e-10 
    KxArray[layCellTuple[0]+1,layCellTuple[1]] = 1e-10 
    
# node property flow
npf = flopy.mf6.ModflowGwfnpf(gwf, ## Org
                              save_specific_discharge=True, ## Org
                              icelltype=icelltype, ## Org
                              k=KxArray, ## Org
                              k33=KxArray) ## Org
You have inserted a fixed elevation
crossSection = gpd.read_file('../shp/crossSection.shp') ## Org
sectionLine =list(crossSection.iloc[0].geometry.coords) ## Org

fig, ax = plt.subplots(figsize=(12,8)) ## Org
modelxsect = flopy.plot.PlotCrossSection(model=gwf, line={'Line': sectionLine}) ## Org
linecollection = modelxsect.plot_grid(lw=0.5) ## Org
modelxsect.plot_array(np.log(npf.k.array), cmap='autumn')
ax.grid() ## Org
# define storage and transient stress periods
sto = flopy.mf6.ModflowGwfsto(gwf, ## Org
                              iconvert=1, ## Org
                              steady_state={ ## Org
                                0:False, ## Org
                              },
                              transient={
                                  0:True, ## Org
                                  1:True, ## Org
                                  2:True, ## Org
                              },
                              ss=1e-06,
                              sy=0.001,
                              ) ## Org

Working with rechage, evapotranspiration

rchr = 0.2/365/86400 ## Org
rch = flopy.mf6.ModflowGwfrcha(gwf, recharge=rchr) ## Org
evtr = 1.2/365/86400 ## Org
evt = flopy.mf6.ModflowGwfevta(gwf,ievt=1,surface=mtop,rate=evtr,depth=1.0) ## Org

Definition of the intersect object

For the manipulation of spatial data to determine hydraulic parameters or boundary conditions

# Define intersection object
interIx = flopy.utils.gridintersect.GridIntersect(gwf.modelgrid) ## Org
#regional flow package
ghbDf = gpd.read_file('../shp/regionalFlow.shp')
ghbDf

FID Elev geometry
0 0.0 2380 LINESTRING (-2631221.561 5121955.296, -2631223...
1 1.0 2370 LINESTRING (-2630546.781 5122056.513, -2630945...
2 NaN 2360 LINESTRING (-2630479.303 5121538.693, -2630483...
ghbSpd = {} ## Org
ghbSpd[0] = [] ## Org

for index , row in ghbDf.iterrows():
    ghbGeom = row.geometry
    layCellTupleList = getLayCellElevTupleFromElev(gwf,interIx,row.Elev,ghbGeom)
    for index, layCellTuple in enumerate(layCellTupleList): ## <=== updated
        for lay in range(layCellTuple[0],nlay):
            ghbSpd[0].append([(lay,layCellTuple[1]),row.Elev,0.01]) ## <=== updated

ghbSpd[0][-10:]
You have inserted a fixed elevation
You have inserted a fixed elevation
You have inserted a fixed elevation





[[(10, 4122), 2360, 0.01],
 [(11, 4122), 2360, 0.01],
 [(12, 4122), 2360, 0.01],
 [(13, 4122), 2360, 0.01],
 [(14, 4122), 2360, 0.01],
 [(15, 4122), 2360, 0.01],
 [(16, 4122), 2360, 0.01],
 [(17, 4122), 2360, 0.01],
 [(18, 4122), 2360, 0.01],
 [(19, 4122), 2360, 0.01]]
ghb = flopy.mf6.ModflowGwfghb(gwf, stress_period_data=ghbSpd)
#regional flow plot
ghb.plot(mflay=4, kper=0) ## <===== modified

Set the Output Control and run simulation

#oc
head_filerecord = f"{gwf.name}.hds" ## Org
budget_filerecord = f"{gwf.name}.cbc" ## Org
oc = flopy.mf6.ModflowGwfoc(gwf, ## Org
                            head_filerecord=head_filerecord, ## Org
                            budget_filerecord = budget_filerecord, ## Org
                            saverecord=[("HEAD", "LAST"),("BUDGET","LAST")]) ## Org
# Run the simulation
sim.write_simulation() ## Org
success, buff = sim.run_simulation() ## Org
writing simulation...
  writing simulation name file...
  writing simulation tdis package...
  writing solution package ims_-1...
  writing model mf6Model...
    writing model name file...
    writing package disv...
    writing package ic...
    writing package npf...
    writing package sto...
    writing package rcha_0...
    writing package evta_0...
    writing package ghb_0...
INFORMATION: maxbound in ('gwf6', 'ghb', 'dimensions') changed to 1421 based on size of stress_period_data
    writing package oc...
FloPy is using the following executable to run the model: ..\bin\mf6.exe
                                   MODFLOW 6
                U.S. GEOLOGICAL SURVEY MODULAR HYDROLOGIC MODEL
                            VERSION 6.6.3 09/29/2025

   MODFLOW 6 compiled Oct 07 2025 23:07:48 with Intel(R) Fortran Intel(R) 64
   Compiler Classic for applications running on Intel(R) 64, Version 2021.7.0
                             Build 20220726_000000

This software has been approved for release by the U.S. Geological 
Survey (USGS). Although the software has been subjected to rigorous 
review, the USGS reserves the right to update the software as needed 
pursuant to further analysis and review. No warranty, expressed or 
implied, is made by the USGS or the U.S. Government as to the 
functionality of the software and related material nor shall the 
fact of release constitute any such warranty. Furthermore, the 
software is released on condition that neither the USGS nor the U.S. 
Government shall be held liable for any damages resulting from its 
authorized or unauthorized use. Also refer to the USGS Water 
Resources Software User Rights Notice for complete use, copyright, 
and distribution information.

 
 MODFLOW runs in SEQUENTIAL mode
 
 Run start date and time (yyyy/mm/dd hh:mm:ss): 2025/11/03 16:12:36
 
 Writing simulation list file: mfsim.lst
 Using Simulation name file: mfsim.nam
 
    Solving:  Stress period:     1    Time step:     1
    Solving:  Stress period:     2    Time step:     1
    Solving:  Stress period:     2    Time step:     2
    Solving:  Stress period:     2    Time step:     3
    Solving:  Stress period:     3    Time step:     1
    Solving:  Stress period:     3    Time step:     2
    Solving:  Stress period:     3    Time step:     3
 
 Run end date and time (yyyy/mm/dd hh:mm:ss): 2025/11/03 16:12:58
 Elapsed run time: 21.973 Seconds
 
 Normal termination of simulation.

Model output visualization

headObj = gwf.output.head() ## Org
headObj.get_kstpkper() ## Org
[(np.int32(0), np.int32(0)),
 (np.int32(2), np.int32(1)),
 (np.int32(2), np.int32(2))]
kper = 2 ## Org
nstp = 2
lay = 0 ## Org
heads = headObj.get_data(kstpkper=(nstp,kper)) 
waterTable = flopy.utils.postprocessing.get_water_table(heads)
#heads[lay,0,:5] 
#heads = headObj.get_data(kstpkper=(0,0)) 
#np.save('npy/headCalibInitial', heads)
### Plot the heads for a defined layer and boundary conditions
fig = plt.figure(figsize=(12,8)) ## Org
ax = fig.add_subplot(1, 1, 1, aspect='equal') ## Org
modelmap = flopy.plot.PlotMapView(model=gwf) ## Org

####
levels = np.linspace(heads[heads>-1e+30].min(),heads[heads>-1e+30].max(),num=50) ## Org
contour = modelmap.contour_array(waterTable,ax=ax,levels=levels,cmap='PuBu') 
ax.clabel(contour) ## Org


quadmesh = modelmap.plot_bc('GHB') ## Org
cellhead = modelmap.plot_array(heads[lay],ax=ax, cmap='Blues', alpha=0.8) 

linecollection = modelmap.plot_grid(linewidth=0.3, alpha=0.5, color='cyan', ax=ax) ## Org

plt.colorbar(cellhead, shrink=0.75) ## Org

plt.show() ## Org
crossSection = gpd.read_file('../shp/crossSection.shp')
sectionLine =list(crossSection.iloc[0].geometry.coords)

waterTable = flopy.utils.postprocessing.get_water_table(heads)

fig, ax = plt.subplots(figsize=(12,8))
xsect = flopy.plot.PlotCrossSection(model=gwf, line={'Line': sectionLine})
lc = modelxsect.plot_grid(lw=0.5)
xsect.plot_array(heads, alpha=0.5)
xsect.plot_surface(waterTable)
xsect.plot_surface(heads[15])
xsect.plot_bc('ghb', kper=kper, facecolor='none', edgecolor='teal')
xsect.plot_grid(lw=0.1)
ax.axis('off')
plt.show()

Datos de ingreso

Puede descargar los datos de ingreso desde este link:

owncloud.hatarilabs.com/s/l2WH5jNVKCuCfvu


 

Suscríbete a nuestro boletín electrónico

Suscríbase a nuestro boletín gratuito para recibir noticias, datos interesantes y fechas de nuestros cursos en recursos hídricos.

 

Posted on November 4, 2025 and filed under TutorialPython, TutorialModflow, Modelamiento.