Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import pandas as pd
import pyemu
nrow,ncol = 10,5
delr = np.ones((ncol)) * 1.0/float(ncol)
delc = np.ones((nrow)) * 1.0/float(nrow)
num_pts = 0
ptx = np.random.random(num_pts)
pty = np.random.random(num_pts)
ptname = ["p{0}".format(i) for i in range(num_pts)]
pts_data = pd.DataFrame({"x":ptx,"y":pty,"name":ptname})
pts_data.index = pts_data.name
pts_data = pts_data.loc[:,["x","y","name"]]
sr = flopy.utils.SpatialReference(delr=delr,delc=delc)
pts_data.loc["i0j0", :] = [sr.xcentergrid[0,0],sr.ycentergrid[0,0],"i0j0"]
pts_data.loc["imxjmx", :] = [sr.xcentergrid[-1, -1], sr.ycentergrid[-1, -1], "imxjmx"]
str_file = os.path.join("utils","struct_test.dat")
gs = pyemu.utils.geostats.read_struct_file(str_file)[0]
ok = pyemu.utils.geostats.OrdinaryKrige(gs,pts_data)
kf = ok.calc_factors_grid(sr,verbose=False,var_filename=os.path.join("utils","test_var.ref"),minpts_interp=1)
ok.to_grid_factors_file(os.path.join("utils","test.fac"))
def test_endpoint_output():
# if models not run then there will be no output
if not run:
return
fpth0 = os.path.join(model_ws, 'mf2005', 'ex01_mf2005_mp.mpend')
e = flopy.utils.EndpointFile(fpth0)
maxtime0 = e.get_maxtime()
maxid0 = e.get_maxid()
maxtravel0 = e.get_maxtraveltime()
e0 = e.get_alldata()
fpth1 = os.path.join(model_ws, 'mf6', 'ex01_mf6_mp.mpend')
e = flopy.utils.EndpointFile(fpth1)
maxtime1 = e.get_maxtime()
maxid1 = e.get_maxid()
maxtravel1 = e.get_maxtraveltime()
e1 = e.get_alldata()
# check maxid
msg = 'endpoint maxid ({}) '.format(maxid0) + \
'in {} '.format(os.path.basename(fpth0)) + \
'are not equal to the ' + \
'endpoint maxid ({}) '.format(maxid1) + \
'in {}'.format(os.path.basename(fpth1))
assert maxid0 == maxid1, msg
# # check maxtravel
# msg = 'endpoint maxtraveltime ({}) '.format(maxtravel0) + \
# 'in {} '.format(os.path.basename(fpth0)) + \
def test_pathline_output():
# if models not run then there will be no output
if not run:
return
fpth0 = os.path.join(model_ws, 'mf2005', 'ex01_mf2005_mp.mppth')
p = flopy.utils.PathlineFile(fpth0)
maxtime0 = p.get_maxtime()
maxid0 = p.get_maxid()
p0 = p.get_alldata()
fpth1 = os.path.join(model_ws, 'mf6', 'ex01_mf6_mp.mppth')
p = flopy.utils.PathlineFile(fpth1)
maxtime1 = p.get_maxtime()
maxid1 = p.get_maxid()
p1 = p.get_alldata()
# # check maxtimes
# msg = 'pathline maxtime ({}) '.format(maxtime0) + \
# 'in {} '.format(os.path.basename(fpth0)) + \
# 'are not equal to the ' + \
# 'pathline maxtime ({}) '.format(maxtime1) + \
# 'in {}'.format(os.path.basename(fpth1))
# assert maxtime0 == maxtime1, msg
m4ds = ml.wel.stress_period_data.masked_4D_arrays
sp_data = flopy.utils.MfList.masked4D_arrays_to_stress_period_data \
(flopy.modflow.ModflowWel.get_default_dtype(), m4ds)
assert np.array_equal(sp_data[0], ml.wel.stress_period_data[0])
assert np.array_equal(sp_data[1], ml.wel.stress_period_data[1])
# the last entry in sp_data (kper==9) should equal the last entry
# with actual data in the well file (kper===1)
assert np.array_equal(sp_data[9], ml.wel.stress_period_data[1])
pth = os.path.join('..', 'examples', 'data', 'mf2005_test')
ml = flopy.modflow.Modflow.load(os.path.join(pth, "swi2ex4sww.nam"),
verbose=True)
m4ds = ml.wel.stress_period_data.masked_4D_arrays
sp_data = flopy.utils.MfList.masked4D_arrays_to_stress_period_data \
(flopy.modflow.ModflowWel.get_default_dtype(), m4ds)
# make a new wel file
wel = flopy.modflow.ModflowWel(ml, stress_period_data=sp_data)
flx1 = m4ds["flux"]
flx2 = wel.stress_period_data.masked_4D_arrays["flux"]
flx1 = np.nan_to_num(flx1)
flx2 = np.nan_to_num(flx2)
assert flx1.sum() == flx2.sum()
# test get_dataframe() on mflist obj
sp_data3 = {0: [1, 1, 1, 1.0],
1: [[1, 1, 3, 3.0], [1, 1, 2, 6.0]],
2: [[1, 2, 4, 8.0], [1, 2, 3, 4.0], [1, 2, 2, 4.0],
def test_endpoint_output():
# if models not run then there will be no output
if not run:
return
fpth0 = os.path.join(model_ws, 'mf2005', 'ex01_mf2005_mp.mpend')
e = flopy.utils.EndpointFile(fpth0)
maxtime0 = e.get_maxtime()
maxid0 = e.get_maxid()
maxtravel0 = e.get_maxtraveltime()
e0 = e.get_alldata()
fpth1 = os.path.join(model_ws, 'mf6', 'ex01_mf6_mp.mpend')
e = flopy.utils.EndpointFile(fpth1)
maxtime1 = e.get_maxtime()
maxid1 = e.get_maxid()
maxtravel1 = e.get_maxtraveltime()
e1 = e.get_alldata()
# check maxid
msg = 'endpoint maxid ({}) '.format(maxid0) + \
'in {} '.format(os.path.basename(fpth0)) + \
'are not equal to the ' + \
'endpoint maxid ({}) '.format(maxid1) + \
ncomp=1, nprs=nprs, timprs=timprs, mxstrn=1e8)
dsp = flopy.mt3d.Mt3dDsp(m, al=0., trpt=1., trpv=1., dmcoef=0.)
gcg = flopy.mt3d.Mt3dGcg(m, mxiter=1, iter1=50, isolve=3, cclose=1e-6,
iprgcg=5)
ssm = flopy.mt3d.Mt3dSsm(m, stress_period_data=ssm_data)
# Create the SEAWAT model files
vdf = flopy.seawat.SeawatVdf(m, nswtcpl=1, iwtable=0, densemin=0,
densemax=0,
denseref=1000., denseslp=25., firstdt=1.0e-03)
m.write_input()
# run seawat model
if not skipRuns:
m = m.run_model(silent=False)
# read seawat model data
ucnfile = os.path.join(dirs[1], 'MT3D001.UCN')
uobj = flopy.utils.UcnFile(ucnfile)
times = uobj.get_times()
print(times)
ukstpkper = uobj.get_kstpkper()
print(ukstpkper)
c = uobj.get_data(totim=times[-1])
conc = np.zeros((swt_nlay, swt_ncol), np.float)
for icol in range(0, swt_ncol):
for ilay in range(0, swt_nlay):
conc[ilay, icol] = c[ilay, 0, icol]
#
# figure
fwid = 7.0 # 6.50
fhgt = 4.5 # 6.75
flft = 0.125
frgt = 0.95
fbot = 0.125
-------
flx : pandas.DataFrame
the flux dataframe
vol : pandas.DataFrame
the volume dataframe
Note
----
requires flopy
"""
try:
import flopy
except Exception as e:
raise Exception("error import flopy: {0}".format(str(e)))
mlf = flopy.utils.MfListBudget(list_filename)
flx,vol = mlf.get_dataframes(start_datetime=start_datetime,diff=True)
flx.to_csv(flx_filename,sep=' ',index_label="datetime",date_format="%Y%m%d")
vol.to_csv(vol_filename,sep=' ',index_label="datetime",date_format="%Y%m%d")
return flx,vol
def get_baseQ(model):
sys.stdout.write('\nrunning base model to get base head-dependent flow\n\n')
success, report = model.run_model(silent=True, report=True)
sys.stdout.write('Base model run: {}\n'.format(report[-3]))
# get base model results
cbcObj = flopy.utils.CellBudgetFile(os.path.join(model.model_ws, 'DG.cbc'), precision=precision)
v1 = cbcObj.get_data(kstpkper=(0, 0), text='DRAINS', full3D=True)[0]
v2 = cbcObj.get_data(kstpkper=(0, 0), text='STREAM LEAKAGE', full3D=True)[0]
v3 = cbcObj.get_data(kstpkper=(0, 0), text='ET', full3D=True)[0]
return v1.sum() + v2.sum() + v3.sum()
performed. If level=1, full checks are performed.
Returns
-------
None
Examples
--------
>>> import flopy
>>> m = flopy.modflow.Modflow.load('model.nam')
>>> m.check()
"""
# check instance for model-level check
chk = utils.check(self, f=f, verbose=verbose, level=level)
results = {}
for p in self.packagelist:
if chk.package_check_levels.get(p.name[0].lower(), 0) <= level:
results[p.name[0]] = p.check(f=None, verbose=False,
level=level - 1)
# model level checks
# solver check
if self.version in chk.solver_packages.keys():
solvers = set(chk.solver_packages[self.version]).intersection(
set(self.get_package_list()))
if not solvers:
chk._add_to_summary('Error', desc='\r No solver package',
package='model')
elif len(list(solvers)) > 1:
Returns
-------
df : pandas.DataFrame
pandas DataFrame with hymod_file values
Note
----
requires flopy
"""
try:
import flopy.utils as fu
except Exception as e:
print('flopy is not installed - cannot read {0}\n{1}'.format(hydmod_file, e))
return
#print('Starting to read HYDMOD data from {0}'.format(hydmod_file))
obs = fu.HydmodObs(hydmod_file)
hyd_df = obs.get_dataframe()
hyd_df.columns = [i[2:] if i.lower() != 'totim' else i for i in hyd_df.columns]
#hyd_df.loc[:,"datetime"] = hyd_df.index
hyd_df['totim'] = hyd_df.index.map(lambda x: x.strftime("%Y%m%d"))
hyd_df.rename(columns={'totim': 'datestamp'}, inplace=True)
# reshape into a single column
hyd_df = pd.melt(hyd_df, id_vars='datestamp')
hyd_df.rename(columns={'value': 'obsval'}, inplace=True)
hyd_df['obsnme'] = [i.lower() + '_' + j.lower() for i, j in zip(hyd_df.variable, hyd_df.datestamp)]