def run_modpath7(fn): model_ws = os.path.dirname(fn) # run the flow model run = True if 'modflow-2005' in fn.lower(): exe = emf2005 v = flopy.which(exe) if v is None: run = False nam = [name for name in os.listdir(model_ws) if '.nam' in name.lower()] if len(nam) > 0: fpth = nam[0] # read and rewrite the name file set_lowercase(os.path.join(model_ws, fpth)) else: fpth = None run = False elif 'modflow-usg' in fn.lower(): exe = emfusg v = flopy.which(exe) if v is None: run = False nam = [name for name in os.listdir(model_ws) if '.nam' in name.lower()] if len(nam) > 0: fpth = nam[0] else: fpth = None run = False elif 'modflow-6' in fn.lower(): exe = emf6 v = flopy.which(exe) if v is None: run = False fpth = None else: run = False if run: # fix any known problems replace_data(model_ws) # run the model msg = '{}'.format(exe) if fpth is not None: msg += ' {}'.format(os.path.basename(fpth)) success, buff = flopy.run_model(exe, fpth, model_ws=model_ws, silent=False) assert success, 'could not run...{}'.format(msg) # run the modpath model print('running model...{}'.format(fn)) exe = emp7 fpth = os.path.basename(fn) success, buff = flopy.run_model(exe, fpth, model_ws=model_ws, silent=False) assert success, 'could not run...{}'.format(os.path.basename(fn)) return
def target_pth(target, pth): exe_exists = flopy.which(target, path=pth) # if target does not exist in specified path determine if it # exists anywhere in the path if exe_exists is None: exe_exists = flopy.which(target) if exe_exists is None: exe_exists = os.path.abspath(os.path.join(pth, target)) raise Exception(f"{exe_exists} does not exist or is not executable.") return os.path.abspath(exe_exists)
def load_swi(mfnam, pth): exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, 'flopy') compth = lpth pymake.setup(os.path.join(pth, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, model_ws=lpth, verbose=True, exe_name=exe_name) assert m.load_fail is False if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'base model run did not terminate successfully' fn0 = os.path.join(lpth, mfnam) # write free format files - # won't run without resetting to free format - evt external file issue m.free_format_input = True # rewrite files m.change_model_ws(apth, reset_external=True) # l1b2k_bath wont run without this m.write_input() if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'base model run did not terminate successfully' fn1 = os.path.join(apth, mfnam) if run: fsum = os.path.join(compth, '{}.budget.out'.format(os.path.splitext(mfnam)[0])) try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: print('could not perform budget comparison') assert success, 'budget comparison failure' return
def target_pth(target, pth): exe_exists = flopy.which(target) if exe_exists is None: target = os.path.abspath(os.path.join(pth, target)) else: target = os.path.abspath(exe_exists) return target
def test_build_triangle(keep=True): if pymake is None: return starget = 'TRIANGLE' exe_name = 'triangle' dirname = 'triangle' url = "http://www.netlib.org/voronoi/{}.zip".format(dirname) print('Determining if {} needs to be built'.format(starget)) if platform.system().lower() == 'windows': exe_name += '.exe' exe_exists = flopy.which(exe_name) if exe_exists is not None and keep: print('No need to build {}'.format(starget) + ' since it exists in the current path') return # get current directory cpth = os.getcwd() # create temporary path dstpth = os.path.join('tempbin', 'triangle') print('create...{}'.format(dstpth)) if not os.path.exists(dstpth): os.makedirs(dstpth) os.chdir(dstpth) pymake.download_and_unzip(url) srcdir = 'src' os.mkdir(srcdir) shutil.move('triangle.c', 'src/triangle.c') shutil.move('triangle.h', 'src/triangle.h') fct, cct = set_compiler(starget) pymake.main(srcdir, 'triangle', fct, cct) # move the file src = os.path.join('.', exe_name) dst = os.path.join(bindir, exe_name) try: shutil.move(src, dst) except: print('could not move {}'.format(exe_name)) # change back to original path os.chdir(cpth) # Clean up downloaded directory print('delete...{}'.format(dstpth)) if os.path.isdir(dstpth): shutil.rmtree(dstpth) # make sure the gridgen was built msg = '{} does not exist.'.format(os.path.relpath(dst)) assert os.path.isfile(dst), msg return
def rebuild_exe(target, starget): rebuild = True epth = os.path.basename(target) exe_exists = flopy.which(epth) if exe_exists is not None: print('No need to build {}'.format(starget) + ' since it exists in the current path') rebuild = False return rebuild
def build_target(starget, exe_name, url, dirname, srcname='src', replace_function=None, verify=True, keep=True, dble=dbleprec, include_subdirs=False): print('Determining if {} needs to be built'.format(starget)) if platform.system().lower() == 'windows': exe_name += '.exe' exe_exists = flopy.which(exe_name) if exe_exists is not None and keep: print('No need to build {}'.format(starget) + ' since it exists in the current path') return fct, cct = set_compiler(starget) # set up target target = os.path.abspath(os.path.join(bindir, exe_name)) # get current directory cpth = os.getcwd() # create temporary path dstpth = os.path.join('tempbin') print('create...{}'.format(dstpth)) if not os.path.exists(dstpth): os.makedirs(dstpth) os.chdir(dstpth) # Download the distribution pymake.download_and_unzip(url, verify=verify) # Set srcdir name srcdir = os.path.join(dirname, srcname) if replace_function is not None: replace_function(srcdir) # compile code print('compiling...{}'.format(os.path.relpath(target))) pymake.main(srcdir, target, fct, cct, makeclean=True, expedite=False, dryrun=False, double=dble, debug=False, include_subdirs=include_subdirs) # change back to original path os.chdir(cpth) # Clean up downloaded directory print('delete...{}'.format(dstpth)) if os.path.isdir(dstpth): shutil.rmtree(dstpth) msg = '{} does not exist.'.format(os.path.relpath(target)) assert os.path.isfile(target), msg return
def load_lak(mfnam, pth): exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, 'flopy') compth = lpth pymake.setup(os.path.join(pth, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, model_ws=lpth, verbose=True, exe_name=exe_name) assert m.load_fail is False if run: try: success, buff = m.run_model(silent=True) except: pass assert success, 'base model run did not terminate successfully' fn0 = os.path.join(lpth, mfnam) # write free format files - wont run without resetting to free format - evt externa file issue m.free_format_input = True # rewrite files m.change_model_ws(apth, reset_external=True) # l1b2k_bath wont run without this m.write_input() if run: try: success, buff = m.run_model(silent=True) except: pass assert success, 'base model run did not terminate successfully' fn1 = os.path.join(apth, mfnam) fsum = os.path.join(compth, '{}.budget.out'.format(os.path.splitext(mfnam)[0])) success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) assert success, 'budget comparison failure' return
def test_create_and_run_model(): # names sim_name = 'testsim' model_name = 'testmodel' exe_name = 'mf6' if platform.system() == 'Windows': exe_name += '.exe' # set up simulation tdis_name = '{}.tdis'.format(sim_name) sim = MFSimulation(sim_name=sim_name, version='mf6', exe_name=exe_name, sim_ws=out_dir, sim_tdis_file=tdis_name) tdis_rc = [(6.0, 2, 1.0), (6.0, 3, 1.0)] tdis = mftdis.ModflowTdis(sim, time_units='DAYS', nper=2, perioddata=tdis_rc) # create model instance model = MFModel(sim, model_type='gwf6', modelname=model_name, model_nam_file='{}.nam'.format(model_name)) # create solution and add the model ims_package = mfims.ModflowIms(sim, print_option='ALL', complexity='SIMPLE', outer_hclose=0.00001, outer_maximum=50, under_relaxation='NONE', inner_maximum=30, inner_hclose=0.00001, linear_acceleration='CG', preconditioner_levels=7, preconditioner_drop_tolerance=0.01, number_orthogonalizations=2) sim.register_ims_package(ims_package, [model_name]) # add packages to model dis_package = mfgwfdis.ModflowGwfdis(model, length_units='FEET', nlay=1, nrow=1, ncol=10, delr=500.0, delc=500.0, top=100.0, botm=50.0, fname='{}.dis'.format(model_name)) ic_package = mfgwfic.ModflowGwfic(model, strt=[100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0], fname='{}.ic'.format(model_name)) npf_package = mfgwfnpf.ModflowGwfnpf(model, save_flows=True, icelltype=1, k=100.0) sto_package = mfgwfsto.ModflowGwfsto(model, save_flows=True, iconvert=1, ss=0.000001, sy=0.15) wel_package = mfgwfwel.ModflowGwfwel(model, print_input=True, print_flows=True, save_flows=True, maxbound=2, stress_period_data=[((0, 0, 4), -2000.0), ((0, 0, 7), -2.0)]) wel_package.stress_period_data.add_transient_key(1) wel_package.stress_period_data.set_data([((0, 0, 4), -200.0)], 1) drn_package = mfgwfdrn.ModflowGwfdrn(model, print_input=True, print_flows=True, save_flows=True, maxbound=1, stress_period_data=[ ((0, 0, 0), 80, 60.0)]) riv_package = mfgwfriv.ModflowGwfriv(model, print_input=True, print_flows=True, save_flows=True, maxbound=1, stress_period_data=[ ((0, 0, 9), 110, 90.0, 100.0)]) oc_package = mfgwfoc.ModflowGwfoc(model, budget_filerecord=[ '{}.cbc'.format(model_name)], head_filerecord=[ '{}.hds'.format(model_name)], saverecord=[('HEAD', 'ALL'), ('BUDGET', 'ALL')], printrecord=[('HEAD', 'ALL'), ('BUDGET', 'ALL')]) oc_package.saverecord.add_transient_key(1) oc_package.saverecord.set_data([('HEAD', 'ALL'), ('BUDGET', 'ALL')], 1) oc_package.printrecord.add_transient_key(1) oc_package.printrecord.set_data([('HEAD', 'ALL'), ('BUDGET', 'ALL')], 1) # write the simulation input files sim.write_simulation() # determine whether or not to run v = flopy.which(exe_name) run = True if v is None: run = False # run the simulation and look for output if run: sim.run_simulation() #head = sim.simulation_data.mfdata[(model_name, 'HDS', 'HEAD')] #print('HEAD: ', head) return
import os import shutil import numpy as np import flopy model_ws = os.path.join('temp', 't057') # delete the directory if it exists if os.path.isdir(model_ws): shutil.rmtree(model_ws) exe_names = {'mf2005': 'mf2005', 'mf6': 'mf6', 'mp7': 'mp7'} run = True for key in exe_names.keys(): v = flopy.which(exe_names[key]) if v is None: run = False break nper, nstp, perlen, tsmult = 1, 1, 1., 1. nlay, nrow, ncol = 3, 21, 20 delr = delc = 500. top = 400. botm = [220., 200., 0.] laytyp = [1, 0, 0] kh = [50., 0.01, 200.] kv = [10., 0.01, 20.] wel_loc = (2, 10, 9) wel_q = -150000. rch = 0.005 riv_h = 320. riv_z = 317.
def test_uzf_unit_numbers(): exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False mfnam = 'UZFtest2.nam' pt = os.path.join('..', 'examples', 'data', 'uzf_examples') # copy files try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, 'flopy') compth = lpth pymake.setup(os.path.join(pt, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, verbose=True, model_ws=lpth, forgive=False, exe_name=exe_name) assert m.load_fail is False, 'failed to load all packages' if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'base model run did not terminate successfully' fn0 = os.path.join(lpth, mfnam) # change uzf iuzfcb2 and add binary uzf output file m.uzf.iuzfcb2 = 61 m.add_output_file(m.uzf.iuzfcb2, extension='uzfcb2.bin', package='UZF') # change the model work space m.change_model_ws(apth, reset_external=True) # rewrite files m.write_input() # run and compare the output files if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'base model run did not terminate successfully' fn1 = os.path.join(apth, mfnam) if run: fsum = os.path.join(compth, '{}.budget.out'.format(os.path.splitext(mfnam)[0])) try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: print('could not perform ls' 'budget comparison') assert success, 'budget comparison failure' return
def load_and_write_fhb(mfnam, pth): exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, 'flopy') compth = lpth pymake.setup(os.path.join(pth, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, model_ws=lpth, verbose=True, exe_name=exe_name) assert m.load_fail is False if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, 'base model run did not terminate successfully' fn0 = os.path.join(lpth, mfnam) # rewrite files m.change_model_ws(apth, reset_external=True) m.write_input() if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, 'new model run did not terminate successfully' fn1 = os.path.join(apth, mfnam) if run: fsum = os.path.join(compth, '{}.head.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_heads(fn0, fn1, outfile=fsum) except: success = False print('could not perform head comparison') assert success, 'head comparison failure' fsum = os.path.join(compth, '{}.budget.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: success = False print('could not perform budget comparison') assert success, 'budget comparison failure' return
def test_mfnwt_run(): import os import flopy exe_name = 'mfnwt' exe = flopy.which(exe_name) if exe is None: print( 'Specified executable {} does not exist in path'.format(exe_name)) return modelname = 'watertable' model_ws = os.path.join('temp', 't020') if not os.path.exists(model_ws): os.makedirs(model_ws) # model dimensions nlay, nrow, ncol = 1, 1, 100 # cell spacing delr = 50. delc = 1. # domain length L = 5000. # boundary heads h1 = 20. h2 = 11. # ibound ibound = np.ones((nlay, nrow, ncol), dtype=np.int) # starting heads strt = np.zeros((nlay, nrow, ncol), dtype=np.float) strt[0, 0, 0] = h1 strt[0, 0, -1] = h2 # top of the aquifer top = 25. # bottom of the aquifer botm = 0. # hydraulic conductivity hk = 50. # location of cell centroids x = np.arange(0.0, L, delr) + (delr / 2.) # location of cell edges xa = np.arange(0, L + delr, delr) # recharge rate rchrate = 0.001 # calculate the head at the cell centroids using the analytical solution function hac = analyticalWaterTableSolution(h1, h2, botm, rchrate, hk, L, x) # calculate the head at the cell edges using the analytical solution function ha = analyticalWaterTableSolution(h1, h2, botm, rchrate, hk, L, xa) # ghbs # ghb conductance b1, b2 = 0.5 * (h1 + hac[0]), 0.5 * (h2 + hac[-1]) c1, c2 = hk * b1 * delc / (0.5 * delr), hk * b2 * delc / (0.5 * delr) # dtype ghb_dtype = flopy.modflow.ModflowGhb.get_default_dtype() # build ghb recarray stress_period_data = np.zeros((2), dtype=ghb_dtype) stress_period_data = stress_period_data.view(np.recarray) # fill ghb recarray stress_period_data[0] = (0, 0, 0, h1, c1) stress_period_data[1] = (0, 0, ncol - 1, h2, c2) mf = flopy.modflow.Modflow(modelname=modelname, exe_name=exe, model_ws=model_ws, version='mfnwt') dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, top=top, botm=botm, perlen=1, nstp=1, steady=True) bas = flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) lpf = flopy.modflow.ModflowUpw(mf, hk=hk, laytyp=1) ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) rch = flopy.modflow.ModflowRch(mf, rech=rchrate, nrchop=1) oc = flopy.modflow.ModflowOc(mf) nwt = flopy.modflow.ModflowNwt(mf) mf.write_input() # remove existing heads results, if necessary try: os.remove(os.path.join(model_ws, '{0}.hds'.format(modelname))) except: pass # run existing model mf.run_model() # Read the simulated MODFLOW-2005 model results # Create the headfile object headfile = os.path.join(model_ws, '{0}.hds'.format(modelname)) headobj = flopy.utils.HeadFile(headfile, precision='single') times = headobj.get_times() head = headobj.get_data(totim=times[-1]) # Plot the results if plt is not None: fig = plt.figure(figsize=(16, 6)) ax = fig.add_subplot(1, 3, 1) ax.plot(xa, ha, linewidth=8, color='0.5', label='analytical solution') ax.plot(x, head[0, 0, :], color='red', label='MODFLOW-NWT') leg = ax.legend(loc='lower left') leg.draw_frame(False) ax.set_xlabel('Horizontal distance, in m') ax.set_ylabel('Head, in m') ax = fig.add_subplot(1, 3, 2) ax.plot(x, head[0, 0, :] - hac, linewidth=1, color='blue') ax.set_xlabel('Horizontal distance, in m') ax.set_ylabel('Error, in m') ax = fig.add_subplot(1, 3, 3) ax.plot(x, 100. * (head[0, 0, :] - hac) / hac, linewidth=1, color='blue') ax.set_xlabel('Horizontal distance, in m') ax.set_ylabel('Percent Error') fig.savefig(os.path.join(model_ws, '{}.png'.format(modelname))) return
for name in files: if name.endswith('.nam'): pth = os.path.join(nwtpth, name) nf = flopy.utils.parsenamefile(pth, m.mfnam_packages) lpf = False wel = False for key, value in nf.items(): if 'LPF' in value.filetype: lpf = True if 'WEL' in value.filetype: wel = True if lpf and wel: nwt_files.append(os.path.join(path, name)) mfnwt_exe = 'mfnwt' v = flopy.which(mfnwt_exe) run = True if v is None: run = False # def test_mfnwt_model(): for fnwt in nwt_files: d, f = os.path.split(fnwt) yield mfnwt_model, f, d # function to load a MODFLOW-2005 model, convert to a MFNWT model, # write it back out, run the MFNWT model, load the MFNWT model,
def test_mfnwt_run(): import os import flopy exe_name = 'mfnwt' exe = flopy.which(exe_name) if exe is None: print('Specified executable {} does not exist in path'.format(exe_name)) return modelname = 'watertable' model_ws = os.path.join('temp', 't020') if not os.path.exists(model_ws): os.makedirs(model_ws) # model dimensions nlay, nrow, ncol = 1, 1, 100 # cell spacing delr = 50. delc = 1. # domain length L = 5000. # boundary heads h1 = 20. h2 = 11. # ibound ibound = np.ones((nlay, nrow, ncol), dtype=np.int) # starting heads strt = np.zeros((nlay, nrow, ncol), dtype=np.float) strt[0, 0, 0] = h1 strt[0, 0, -1] = h2 # top of the aquifer top = 25. # bottom of the aquifer botm = 0. # hydraulic conductivity hk = 50. # location of cell centroids x = np.arange(0.0, L, delr) + (delr / 2.) # location of cell edges xa = np.arange(0, L + delr, delr) # recharge rate rchrate = 0.001 # calculate the head at the cell centroids using the analytical solution function hac = analyticalWaterTableSolution(h1, h2, botm, rchrate, hk, L, x) # calculate the head at the cell edges using the analytical solution function ha = analyticalWaterTableSolution(h1, h2, botm, rchrate, hk, L, xa) # ghbs # ghb conductance b1, b2 = 0.5 * (h1 + hac[0]), 0.5 * (h2 + hac[-1]) c1, c2 = hk * b1 * delc / (0.5 * delr), hk * b2 * delc / (0.5 * delr) # dtype ghb_dtype = flopy.modflow.ModflowGhb.get_default_dtype() # build ghb recarray stress_period_data = np.zeros((2), dtype=ghb_dtype) stress_period_data = stress_period_data.view(np.recarray) # fill ghb recarray stress_period_data[0] = (0, 0, 0, h1, c1) stress_period_data[1] = (0, 0, ncol - 1, h2, c2) mf = flopy.modflow.Modflow(modelname=modelname, exe_name=exe, model_ws=model_ws, version='mfnwt') dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, top=top, botm=botm, perlen=1, nstp=1, steady=True) bas = flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) lpf = flopy.modflow.ModflowUpw(mf, hk=hk, laytyp=1) ghb = flopy.modflow.ModflowGhb(mf, stress_period_data=stress_period_data) rch = flopy.modflow.ModflowRch(mf, rech=rchrate, nrchop=1) oc = flopy.modflow.ModflowOc(mf) nwt = flopy.modflow.ModflowNwt(mf) mf.write_input() # remove existing heads results, if necessary try: os.remove(os.path.join(model_ws, '{0}.hds'.format(modelname))) except: pass # run existing model mf.run_model() # Read the simulated MODFLOW-2005 model results # Create the headfile object headfile = os.path.join(model_ws, '{0}.hds'.format(modelname)) headobj = flopy.utils.HeadFile(headfile, precision='single') times = headobj.get_times() head = headobj.get_data(totim=times[-1]) # Plot the results if plt is not None: fig = plt.figure(figsize=(16, 6)) ax = fig.add_subplot(1, 3, 1) ax.plot(xa, ha, linewidth=8, color='0.5', label='analytical solution') ax.plot(x, head[0, 0, :], color='red', label='MODFLOW-NWT') leg = ax.legend(loc='lower left') leg.draw_frame(False) ax.set_xlabel('Horizontal distance, in m') ax.set_ylabel('Head, in m') ax = fig.add_subplot(1, 3, 2) ax.plot(x, head[0, 0, :] - hac, linewidth=1, color='blue') ax.set_xlabel('Horizontal distance, in m') ax.set_ylabel('Error, in m') ax = fig.add_subplot(1, 3, 3) ax.plot(x, 100. * (head[0, 0, :] - hac) / hac, linewidth=1, color='blue') ax.set_xlabel('Horizontal distance, in m') ax.set_ylabel('Percent Error') fig.savefig(os.path.join(model_ws, '{}.png'.format(modelname))) return
import flopy pthtest = os.path.join('..', 'examples', 'data', 'mt3d_test') pth2005 = os.path.join(pthtest, 'mf2005mt3d') pth2000 = os.path.join(pthtest, 'mf2kmt3d') pthNWT = os.path.join(pthtest, 'mfnwt_mt3dusgs') newpth = os.path.join('.', 'temp', 't012') mf2k_exe = 'mf2000' mf2005_exe = 'mf2005' mfnwt_exe = 'mfnwt' mt3d_exe = 'mt3dms' mt3d_usgs_exe = 'mt3dusgs' ismf2k = flopy.which(mf2k_exe) ismf2005 = flopy.which(mf2005_exe) ismfnwt = flopy.which(mfnwt_exe) ismt3d = flopy.which(mt3d_exe) ismt3dusgs = flopy.which(mt3d_usgs_exe) def test_mf2005_p07(): pth = os.path.join(pth2005, 'P07') namfile = 'p7mf2005.nam' mf = flopy.modflow.Modflow.load(namfile, model_ws=pth, verbose=True, exe_name=mf2005_exe) cpth = os.path.join(newpth, 'P07') mf.model_ws = cpth mf.write_input()
""" Test MT3D model creation and file writing """ import os import flopy import numpy as np mf_exe_name = 'mf2005' mt_exe_name = 'mt3dms' v1 = flopy.which(mf_exe_name) v2 = flopy.which(mt_exe_name) run = True if v1 is None or v2 is None: run = False def test_mt3d_ssm_with_nodata_in_1st_sp(): nlay, nrow, ncol = 3, 5, 5 perlen = np.zeros((10), dtype=float) + 10 nper = len(perlen) ibound = np.ones((nlay, nrow, ncol), dtype=int) botm = np.arange(-1, -4, -1) top = 0. # creating MODFLOW model model_ws = os.path.join('.', 'temp', 't068a')
matplotlib = None import flopy try: import pymake except: pymake = None tpth = os.path.abspath(os.path.join("temp", "t015")) # make the directory if it does not exist if not os.path.isdir(tpth): os.makedirs(tpth) mfexe = "mf2005" v = flopy.which(mfexe) run = True if v is None: run = False print(os.getcwd()) if os.path.split(os.getcwd())[-1] == "flopy3": path = os.path.join("examples", "data", "mf2005_test") else: path = os.path.join("..", "examples", "data", "mf2005_test") str_items = { 0: { "mfnam": "str.nam", "sfrfile": "str.str",
def test_unitnums_load_and_write(): exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False mfnam = 'testsfr2_tab.nam' # copy files try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, 'flopy') compth = lpth pymake.setup(os.path.join(pth, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, verbose=True, model_ws=lpth, exe_name=exe_name) assert m.load_fail is False, 'failed to load all packages' msg = 'modflow-2005 testsfr2_tab does not have ' + \ '1 layer, 7 rows, and 100 colummns' v = (m.nlay, m.nrow, m.ncol, m.nper) assert v == (1, 7, 100, 50), msg if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'base model run did not terminate successfully' fn0 = os.path.join(lpth, mfnam) # rewrite files m.change_model_ws(apth, reset_external=True) m.write_input() if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'base model run did not terminate successfully' fn1 = os.path.join(apth, mfnam) if run: fsum = os.path.join(compth, '{}.budget.out'.format(os.path.splitext(mfnam)[0])) try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: print('could not perform ls' 'budget comparison') assert success, 'budget comparison failure' return
def test_uzf_unit_numbers(): exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False mfnam = 'UZFtest2.nam' pt = os.path.join('..', 'examples', 'data', 'uzf_examples') # copy files try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, 'flopy') compth = lpth pymake.setup(os.path.join(pt, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, verbose=True, model_ws=lpth, exe_name=exe_name) assert m.load_fail is False, 'failed to load all packages' if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'base model run did not terminate successfully' fn0 = os.path.join(lpth, mfnam) # change uzf iuzfcb2 and add binary uzf output file m.uzf.iuzfcb2 = 61 m.add_output_file(m.uzf.iuzfcb2, extension='uzfcb2.bin', package='UZF') # change the model work space m.change_model_ws(apth, reset_external=True) # rewrite files m.write_input() # run and compare the output files if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'base model run did not terminate successfully' fn1 = os.path.join(apth, mfnam) if run: fsum = os.path.join(compth, '{}.budget.out'.format(os.path.splitext(mfnam)[0])) try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: print('could not perform ls' 'budget comparison') assert success, 'budget comparison failure' return
import flopy from flopy.utils.gridgen import Gridgen try: import matplotlib import matplotlib.pyplot as plt except: print("Matplotlib not installed, tests cannot be run.") matplotlib = None plt = None # Set gridgen executable gridgen_exe = "gridgen" if platform.system() in "Windows": gridgen_exe += ".exe" gridgen_exe = flopy.which(gridgen_exe) # set mf6 executable mf6_exe = "mf6" if platform.system() in "Windows": mf6_exe += ".exe" mf6_exe = flopy.which(mf6_exe) # set mfusg executable mfusg_exe = "mfusg" if platform.system() in "Windows": mfusg_exe += ".exe" mfusg_exe = flopy.which(mfusg_exe) # set up the example folder tpth = os.path.join("temp", "t506")
def test_uzf_unit_numbers(): exe_name = "mf2005" v = flopy.which(exe_name) run = True if v is None: run = False mfnam = "UZFtest2.nam" pt = os.path.join("..", "examples", "data", "uzf_examples") # copy files try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, "flopy") compth = lpth pymake.setup(os.path.join(pt, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, verbose=True, model_ws=lpth, forgive=False, exe_name=exe_name) assert m.load_fail is False, "failed to load all packages" # reset the oc file m.remove_package("OC") output = ["save head", "print budget"] spd = {} for iper in range(1, m.dis.nper): for istp in [0, 4, 9, 14]: spd[(iper, istp)] = output spd[(0, 0)] = output spd[(1, 1)] = output spd[(1, 2)] = output spd[(1, 3)] = output oc = flopy.modflow.ModflowOc(m, stress_period_data=spd) oc.write_file() if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, "base model run did not terminate successfully" fn0 = os.path.join(lpth, mfnam) # change uzf iuzfcb2 and add binary uzf output file m.uzf.iuzfcb2 = 61 m.add_output_file(m.uzf.iuzfcb2, extension="uzfcb2.bin", package="UZF") # change the model work space m.change_model_ws(apth, reset_external=True) # rewrite files m.write_input() # run and compare the output files if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, "new model run did not terminate successfully" fn1 = os.path.join(apth, mfnam) # compare budget terms if run: fsum = os.path.join(compth, "{}.budget.out".format(os.path.splitext(mfnam)[0])) try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: success = False print("could not perform ls" "budget comparison") assert success, "budget comparison failure" # clean up shutil.rmtree(lpth) return
def load_and_write(mfnam, pth): """ test045 load and write of MODFLOW-2005 GMG example problem """ exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, 'flopy') compth = lpth pymake.setup(os.path.join(pth, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, model_ws=lpth, verbose=True, exe_name=exe_name) assert m.load_fail is False if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, 'base model run did not terminate successfully' fn0 = os.path.join(lpth, mfnam) # change model workspace m.change_model_ws(apth) # recreate oc file oc = m.oc unitnumber = [oc.unit_number[0], oc.iuhead, oc.iuddn, 0, 0] spd = {(0, 0): ['save head', 'save drawdown']} chedfm = '(10(1X1PE13.5))' cddnfm = '(10(1X1PE13.5))' oc = flopy.modflow.ModflowOc(m, stress_period_data=spd, chedfm=chedfm, cddnfm=cddnfm, unitnumber=unitnumber) # rewrite files m.write_input() if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, 'new model run did not terminate successfully' fn1 = os.path.join(apth, mfnam) if run: # compare heads fsum = os.path.join(compth, '{}.head.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_heads(fn0, fn1, outfile=fsum) except: success = False print('could not perform head comparison') assert success, 'head comparison failure' # compare heads fsum = os.path.join(compth, '{}.ddn.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_heads(fn0, fn1, outfile=fsum, text='drawdown') except: success = False print('could not perform drawdown comparison') assert success, 'head comparison failure' # compare budgets fsum = os.path.join(compth, '{}.budget.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: success = False print('could not perform budget comparison') assert success, 'budget comparison failure' return
def test_build_gridgen(keep=True): if pymake is None: return starget = 'GRIDGEN' exe_name = 'gridgen' dirname = 'gridgen.1.0.02' url = "https://water.usgs.gov/ogw/gridgen/{}.zip".format(dirname) print('Determining if {} needs to be built'.format(starget)) if platform.system().lower() == 'windows': exe_name += '.exe' exe_exists = flopy.which(exe_name) if exe_exists is not None and keep: print('No need to build {}'.format(starget) + ' since it exists in the current path') return # get current directory cpth = os.getcwd() # create temporary path dstpth = os.path.join('tempbin') print('create...{}'.format(dstpth)) if not os.path.exists(dstpth): os.makedirs(dstpth) os.chdir(dstpth) pymake.download_and_unzip(url) # clean print('Cleaning...{}'.format(exe_name)) apth = os.path.join(dirname, 'src') cmdlist = ['make', 'clean'] run_cmdlist(cmdlist, apth) # build with make print('Building...{}'.format(exe_name)) apth = os.path.join(dirname, 'src') cmdlist = ['make', exe_name] run_cmdlist(cmdlist, apth) # move the file src = os.path.join(apth, exe_name) dst = os.path.join(bindir, exe_name) try: shutil.move(src, dst) except: print('could not move {}'.format(exe_name)) # change back to original path os.chdir(cpth) # Clean up downloaded directory print('delete...{}'.format(dstpth)) if os.path.isdir(dstpth): shutil.rmtree(dstpth) # make sure the gridgen was built msg = '{} does not exist.'.format(os.path.relpath(dst)) assert os.path.isfile(dst), msg return
def run_modpath7(fn): success = False if os.path.exists(emp7): model_ws = os.path.dirname(fn) # run the flow model run = True if "modflow-2005" in fn.lower(): exe = emf2005 v = flopy.which(exe) if v is None: run = False nam = [ name for name in os.listdir(model_ws) if ".nam" in name.lower() ] if len(nam) > 0: fpth = nam[0] # read and rewrite the name file set_lowercase(os.path.join(model_ws, fpth)) else: fpth = None run = False elif "modflow-usg" in fn.lower(): exe = emfusg v = flopy.which(exe) if v is None: run = False nam = [ name for name in os.listdir(model_ws) if ".nam" in name.lower() ] if len(nam) > 0: fpth = nam[0] else: fpth = None run = False elif "modflow-6" in fn.lower(): exe = emf6 v = flopy.which(exe) if v is None: run = False fpth = None else: run = False if run: # fix any known problems replace_data(model_ws) # run the model msg = "{}".format(exe) if fpth is not None: msg += " {}".format(os.path.basename(fpth)) success, buff = flopy.run_model(exe, fpth, model_ws=model_ws, silent=False) if success: # run the modpath model print("running model...{}".format(fn)) exe = emp7 fpth = os.path.basename(fn) success, buff = flopy.run_model(exe, fpth, model_ws=model_ws, silent=False) return success
def test_create_and_run_model(): # names sim_name = "testsim" model_name = "testmodel" exe_name = "mf6" # set up simulation tdis_name = "{}.tdis".format(sim_name) sim = MFSimulation( sim_name=sim_name, version="mf6", exe_name=exe_name, sim_ws=out_dir ) tdis_rc = [(6.0, 2, 1.0), (6.0, 3, 1.0)] tdis = mftdis.ModflowTdis( sim, time_units="DAYS", nper=2, perioddata=tdis_rc ) # create model instance model = mfgwf.ModflowGwf( sim, modelname=model_name, model_nam_file="{}.nam".format(model_name) ) # create solution and add the model ims_package = mfims.ModflowIms( sim, print_option="ALL", complexity="SIMPLE", outer_hclose=0.00001, outer_maximum=50, under_relaxation="NONE", inner_maximum=30, inner_hclose=0.00001, linear_acceleration="CG", preconditioner_levels=7, preconditioner_drop_tolerance=0.01, number_orthogonalizations=2, ) sim.register_ims_package(ims_package, [model_name]) # add packages to model dis_package = mfgwfdis.ModflowGwfdis( model, length_units="FEET", nlay=1, nrow=1, ncol=10, delr=500.0, delc=500.0, top=100.0, botm=50.0, filename="{}.dis".format(model_name), ) ic_package = mfgwfic.ModflowGwfic( model, strt=[ 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, ], filename="{}.ic".format(model_name), ) npf_package = mfgwfnpf.ModflowGwfnpf( model, save_flows=True, icelltype=1, k=100.0 ) sto_package = mfgwfsto.ModflowGwfsto( model, save_flows=True, iconvert=1, ss=0.000001, sy=0.15 ) wel_package = mfgwfwel.ModflowGwfwel( model, print_input=True, print_flows=True, save_flows=True, maxbound=2, stress_period_data=[((0, 0, 4), -2000.0), ((0, 0, 7), -2.0)], ) wel_package.stress_period_data.add_transient_key(1) wel_package.stress_period_data.set_data([((0, 0, 4), -200.0)], 1) drn_package = mfgwfdrn.ModflowGwfdrn( model, print_input=True, print_flows=True, save_flows=True, maxbound=1, stress_period_data=[((0, 0, 0), 80, 60.0)], ) riv_package = mfgwfriv.ModflowGwfriv( model, print_input=True, print_flows=True, save_flows=True, maxbound=1, stress_period_data=[((0, 0, 9), 110, 90.0, 100.0)], ) oc_package = mfgwfoc.ModflowGwfoc( model, budget_filerecord=["{}.cbc".format(model_name)], head_filerecord=["{}.hds".format(model_name)], saverecord=[("HEAD", "ALL"), ("BUDGET", "ALL")], printrecord=[("HEAD", "ALL"), ("BUDGET", "ALL")], ) oc_package.saverecord.add_transient_key(1) oc_package.saverecord.set_data([("HEAD", "ALL"), ("BUDGET", "ALL")], 1) oc_package.printrecord.add_transient_key(1) oc_package.printrecord.set_data([("HEAD", "ALL"), ("BUDGET", "ALL")], 1) # write the simulation input files sim.write_simulation() # determine whether or not to run v = flopy.which(exe_name) run = True if v is None: run = False # run the simulation and look for output if run: sim.run_simulation() # head = sim.simulation_data.mfdata[(model_name, 'HDS', 'HEAD')] # print('HEAD: ', head) return
import flopy pthtest = os.path.join('..', 'examples', 'data', 'mt3d_test') pth2005 = os.path.join(pthtest, 'mf2005mt3d') pth2000 = os.path.join(pthtest, 'mf2kmt3d') pthNWT = os.path.join(pthtest, 'mfnwt_mt3dusgs') newpth = os.path.join('.', 'temp', 't012') mf2k_exe = 'mf2000' mf2005_exe = 'mf2005' mfnwt_exe = 'mfnwt' mt3d_exe = 'mt3dms' mt3d_usgs_exe = 'mt3dusgs' ismf2k = flopy.which(mf2k_exe) ismf2005 = flopy.which(mf2005_exe) ismfnwt = flopy.which(mfnwt_exe) ismt3d = flopy.which(mt3d_exe) ismt3dusgs = flopy.which(mt3d_usgs_exe) def test_mf2005_p07(): pth = os.path.join(pth2005, 'P07') namfile = 'p7mf2005.nam' mf = flopy.modflow.Modflow.load(namfile, model_ws=pth, verbose=True, exe_name=mf2005_exe) cpth = os.path.join(newpth, 'P07') mf.model_ws = cpth
import matplotlib.pyplot as plt try: import pymake except: print('could not import pymake') cpth = os.path.join('temp', 't049') # delete the directory if it exists if os.path.isdir(cpth): shutil.rmtree(cpth) # make the directory os.makedirs(cpth) mf2005_exe = 'mf2005' v = flopy.which(mf2005_exe) mpth_exe = 'mp6' v2 = flopy.which(mpth_exe) rung = True if v is None or v2 is None: rung = False def test_modpath(): pth = os.path.join('..', 'examples', 'data', 'freyberg') mfnam = 'freyberg.nam' run = rung try:
""" Some basic tests for SEAWAT Henry create and run. """ import os import numpy as np import flopy workspace = os.path.join('temp', 't026') # make the directory if it does not exist if not os.path.isdir(workspace): os.makedirs(workspace) seawat_exe = 'swt_v4' isseawat = flopy.which(seawat_exe) # Setup problem parameters Lx = 2. Lz = 1. nlay = 50 nrow = 1 ncol = 100 delr = Lx / ncol delc = 1.0 delv = Lz / nlay henry_top = 1. henry_botm = np.linspace(henry_top - delv, 0., nlay) qinflow = 5.702 # m3/day dmcoef = 0.57024 # m2/day Could also try 1.62925 hk = 864. # m/day
import os import shutil import filecmp import flopy try: import pymake except: print('could not import pymake') cpth = os.path.join('temp', 't043') # delete the directory if it exists if os.path.isdir(cpth): shutil.rmtree(cpth) exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False def test_gage_load_and_write(): """ test043 load and write of MODFLOW-2005 GAGE example problem """ pth = os.path.join('..', 'examples', 'data', 'mf2005_test') opth = os.path.join(cpth, 'testsfr2_tab', 'orig') # delete the directory if it exists if os.path.isdir(opth): shutil.rmtree(opth)
def load_and_write(mfnam, pth): """ test045 load and write of MODFLOW-2005 GMG example problem """ exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, 'flopy') compth = lpth pymake.setup(os.path.join(pth, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, model_ws=lpth, verbose=True, exe_name=exe_name) assert m.load_fail is False if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, 'base model run did not terminate successfully' fn0 = os.path.join(lpth, mfnam) # change model workspace m.change_model_ws(apth) # recreate oc file oc = m.oc unitnumber = [oc.unit_number[0], oc.iuhead, oc.iuddn, 0, 0] spd = {(0,0): ['save head', 'save drawdown']} chedfm = '(10(1X1PE13.5))' cddnfm = '(10(1X1PE13.5))' oc = flopy.modflow.ModflowOc(m, stress_period_data=spd, chedfm=chedfm, cddnfm=cddnfm, unitnumber=unitnumber) # rewrite files m.write_input() if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, 'new model run did not terminate successfully' fn1 = os.path.join(apth, mfnam) if run: # compare heads fsum = os.path.join(compth, '{}.head.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_heads(fn0, fn1, outfile=fsum) except: success = False print('could not perform head comparison') assert success, 'head comparison failure' # compare heads fsum = os.path.join(compth, '{}.ddn.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_heads(fn0, fn1, outfile=fsum, text='drawdown') except: success = False print('could not perform drawdown comparison') assert success, 'head comparison failure' # compare budgets fsum = os.path.join(compth, '{}.budget.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: success = False print('could not perform budget comparison') assert success, 'budget comparison failure' return
import os import shutil import flopy pthtest = os.path.join('..', 'examples', 'data', 'swtv4_test') newpth = os.path.join('.', 'temp', 't028') # make the directory if it does not exist if not os.path.isdir(newpth): os.makedirs(newpth) swtv4_exe = 'swt_v4' isswtv4 = flopy.which(swtv4_exe) runmodel = False verbose = False swtdir = [ '1_box', '1_box', '2_henry', '2_henry', '2_henry', '2_henry', '2_henry', '2_henry', '3_elder', '4_hydrocoin', '5_saltlake', '6_rotation', '6_rotation', '7_swtv4_ex', '7_swtv4_ex', '7_swtv4_ex', '7_swtv4_ex', '7_swtv4_ex', '7_swtv4_ex', '7_swtv4_ex' ] subds = [ 'case1', 'case2', '1_classic_case1', '2_classic_case2', '3_VDF_no_Trans', '4_VDF_uncpl_Trans', '5_VDF_DualD_Trans', '6_age_simulation', '', '', '', '1_symmetric', '2_asymmetric', 'case1', 'case2', 'case3', 'case4', 'case5', 'case6', 'case7' ] def test_seawat_array_format(): d = '2_henry'
import flopy import matplotlib.pyplot as plt try: import pymake except: print('could not import pymake') cpth = os.path.join('temp', 't049') # delete the directory if it exists if os.path.isdir(cpth): shutil.rmtree(cpth) # make the directory os.makedirs(cpth) mf2005_exe = 'mf2005' v = flopy.which(mf2005_exe) mpth_exe = 'mp6' v2 = flopy.which(mpth_exe) rung = True if v is None or v2 is None: rung = False def test_modpath(): pth = os.path.join('..', 'examples', 'data', 'freyberg') mfnam = 'freyberg.nam' run = rung
def load_and_write_fhb(mfnam, pth): exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, 'flopy') compth = lpth pymake.setup(os.path.join(pth, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, model_ws=lpth, verbose=True, exe_name=exe_name) assert m.load_fail is False if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'base model run did not terminate successfully' fn0 = os.path.join(lpth, mfnam) # rewrite files m.change_model_ws(apth, reset_external=True) m.write_input() if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'new model run did not terminate successfully' fn1 = os.path.join(apth, mfnam) if run: fsum = os.path.join(compth, '{}.head.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_heads(fn0, fn1, outfile=fsum) except: print('could not perform head comparison') assert success, 'head comparison failure' fsum = os.path.join(compth, '{}.budget.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: print('could not perform budget comparison') assert success, 'budget comparison failure' return
def build_target(starget, exe_name, url, dirname, srcname='src', replace_function=None, verify=True, keep=True, dble=dbleprec, include_subdirs=False): print('Determining if {} needs to be built'.format(starget)) if platform.system().lower() == 'windows': exe_name += '.exe' exe_exists = flopy.which(exe_name) if exe_exists is not None and keep: print('No need to build {}'.format(starget) + ' since it exists in the current path') return fct, cct = set_compiler(starget) # set up target target = os.path.abspath(os.path.join(bindir, exe_name)) # get current directory cpth = os.getcwd() # create temporary path dstpth = os.path.join('tempbin') print('create...{}'.format(dstpth)) if not os.path.exists(dstpth): os.makedirs(dstpth) os.chdir(dstpth) # Download the distribution pymake.download_and_unzip(url, verify=verify) # Set srcdir name srcdir = os.path.join(dirname, srcname) if replace_function is not None: replace_function(srcdir) # compile code print('compiling...{}'.format(os.path.relpath(target))) pymake.main(srcdir, target, fct, cct, makeclean=True, expedite=False, dryrun=False, double=dble, debug=False, include_subdirs=include_subdirs) # change back to original path os.chdir(cpth) msg = '{} does not exist.'.format(os.path.relpath(target)) assert os.path.isfile(target), msg # Clean up downloaded directory print('delete...{}'.format(dstpth)) if os.path.isdir(dstpth): shutil.rmtree(dstpth) return
for name in files: if name.endswith('.nam'): pth = os.path.join(nwtpth, name) nf = flopy.utils.parsenamefile(pth, m.mfnam_packages) lpf = False wel = False for key, value in nf.items(): if 'LPF' in value.filetype: lpf = True if 'WEL' in value.filetype: wel = True if lpf and wel: nwt_files.append(os.path.join(path, name)) mfnwt_exe = 'mfnwt' v = flopy.which(mfnwt_exe) run = True if v is None: run = False # fix for intermittent CI failure on windows else: if sys.platform.lower() in ("win32", "darwin"): run = False # def test_mfnwt_model(): for fnwt in nwt_files: d, f = os.path.split(fnwt) yield mfnwt_model, f, d
def test_unitnums_load_and_write(): exe_name = "mf2005" v = flopy.which(exe_name) run = True if v is None: run = False mfnam = "testsfr2_tab.nam" # copy files try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, "flopy") compth = lpth pymake.setup(os.path.join(pth, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, verbose=True, model_ws=lpth, exe_name=exe_name) assert m.load_fail is False, "failed to load all packages" msg = ("modflow-2005 testsfr2_tab does not have " + "1 layer, 7 rows, and 100 columns") v = (m.nlay, m.nrow, m.ncol, m.nper) assert v == (1, 7, 100, 50), msg if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, "base model run did not terminate successfully" fn0 = os.path.join(lpth, mfnam) # rewrite files m.change_model_ws(apth, reset_external=True) m.write_input() if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, "base model run did not terminate successfully" fn1 = os.path.join(apth, mfnam) if run: fsum = os.path.join(compth, "{}.budget.out".format(os.path.splitext(mfnam)[0])) try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: success = False print("could not perform ls" "budget comparison") assert success, "budget comparison failure" # clean up shutil.rmtree(lpth) return
def test_modpath(): pth = os.path.join('..', 'examples', 'data', 'freyberg') mfnam = 'freyberg.nam' mf2005_exe = 'mf2005' v = flopy.which(mf2005_exe) mpth_exe = 'mp6' v2 = flopy.which(mpth_exe) run = True if v is None or v2 is None: run = False try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) pymake.setup(os.path.join(pth, mfnam), lpth) except: run = False lpth = pth m = flopy.modflow.Modflow.load(mfnam, model_ws=lpth, verbose=True, exe_name=mf2005_exe) assert m.load_fail is False if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'modflow model run did not terminate successfully' # create the forward modpath file mpnam = 'freybergmp' mp = flopy.modpath.Modpath(mpnam, exe_name=mpth_exe, modflowmodel=m, model_ws=lpth) mpbas = flopy.modpath.ModpathBas(mp, hnoflo=m.bas6.hnoflo, hdry=m.lpf.hdry, ibound=m.bas6.ibound.array, prsity=0.2, prsityCB=0.2) sim = mp.create_mpsim(trackdir='forward', simtype='endpoint', packages='RCH') # write forward particle track files mp.write_input() if run: try: success, buff = mp.run_model(silent=False) except: pass assert success, 'forward modpath model run ' + \ 'did not terminate successfully' mpnam = 'freybergmpp' mpp = flopy.modpath.Modpath(mpnam, exe_name=mpth_exe, modflowmodel=m, model_ws=lpth) mpbas = flopy.modpath.ModpathBas(mpp, hnoflo=m.bas6.hnoflo, hdry=m.lpf.hdry, ibound=m.bas6.ibound.array, prsity=0.2, prsityCB=0.2) sim = mpp.create_mpsim(trackdir='backward', simtype='pathline', packages='WEL') # write backward particle track files mpp.write_input() if run: try: success, buff = mpp.run_model(silent=False) except: pass assert success, 'backward modpath model run ' + \ 'did not terminate successfully' # load modpath output files if run: endfile = os.path.join(lpth, mp.sim.endpoint_file) pthfile = os.path.join(lpth, mpp.sim.pathline_file) else: endfile = os.path.join('..', 'examples', 'data', 'mp6_examples', 'freybergmp.gitmpend') pthfile = os.path.join('..', 'examples', 'data', 'mp6_examples', 'freybergmpp.gitmppth') # load the endpoint data try: endobj = flopy.utils.EndpointFile(endfile) except: assert False, 'could not load endpoint file' ept = endobj.get_alldata() assert ept.shape == (695,), 'shape of endpoint file is not (695,)' # load the pathline data try: pthobj = flopy.utils.PathlineFile(pthfile) except: assert False, 'could not load pathline file' plines = pthobj.get_alldata() assert len(plines) == 576, 'there are not 576 particle pathlines in file' return
import os import flopy import numpy as np path = os.path.join('..', 'examples', 'data', 'mf2005_test') pthgw = os.path.join('..', 'examples', 'groundwater_paper', 'uspb', 'flopy') cpth = os.path.join('temp', 't014') # make the directory if it does not exist if not os.path.isdir(cpth): os.makedirs(cpth) mf_items = ['str.nam', 'DG.nam'] pths = [path, pthgw] exe_name = 'mf2005dbl' v = flopy.which(exe_name) run = True if v is None: run = False def load_str(mfnam, pth): m = flopy.modflow.Modflow.load(mfnam, exe_name=exe_name, forgive=False, model_ws=pth, verbose=True) assert m.load_fail is False # rewrite files
def build_target(starget, exe_name, url, dirname, srcname='src', replace_function=None, verify=True, keep=True, dble=None, include_subdirs=False): print('Determining if {} needs to be built'.format(starget)) # update exe_name, if necessary, and set double (dble) flag if dble is None: dble, exe_name = set_dbl(exe_name) if platform.system().lower() == 'windows': exe_name += '.exe' # set compiler fct, cct = set_compiler(starget) # set up architecture arch = set_arch() # set up target target = os.path.abspath(os.path.join(bindir, exe_name)) # test if executable exists epth = exe_name for idx, arg in enumerate(sys.argv): if '--root' in arg.lower() or '--appdir' in arg.lower(): epth = target exe_exists = flopy.which(epth) if exe_exists is not None and keep: print('No need to build {}'.format(starget) + ' since it exists in the current path') return # get current directory cpth = os.getcwd() # create temporary path dstpth = os.path.join('tempbin') print('create...{}'.format(dstpth)) if not os.path.exists(dstpth): os.makedirs(dstpth) os.chdir(dstpth) # Download the distribution pymake.download_and_unzip(url, verify=verify) # Set srcdir name srcdir = os.path.join(dirname, srcname) if replace_function is not None: replace_function(srcdir) # compile code print('compiling...{}'.format(os.path.relpath(target))) pymake.main(srcdir, target, fct, cct, makeclean=True, expedite=False, dryrun=False, double=dble, debug=False, include_subdirs=include_subdirs, arch=arch) # change back to original path os.chdir(cpth) # Clean up downloaded directory print('delete...{}'.format(dstpth)) if os.path.isdir(dstpth): try: shutil.rmtree(dstpth) except: pass msg = '{} does not exist.'.format(os.path.relpath(target)) assert os.path.isfile(target), msg return
# Test loading of MODFLOW and MT3D models that come with MT3D distribution import os import flopy pthtest = os.path.join('..', 'examples', 'data', 'mt3d_test') pth2005 = os.path.join(pthtest, 'mf2005mt3d') pth2000 = os.path.join(pthtest, 'mf2kmt3d') newpth = os.path.join('.', 'temp') mf2k_exe = 'mf2000' mf2005_exe = 'mf2005' mt3d_exe = 'mt3dms' ismf2k = flopy.which(mf2k_exe) ismf2005 = flopy.which(mf2005_exe) ismt3d = flopy.which(mt3d_exe) def test_mf2005_p07(): pth = os.path.join(pth2005, 'P07') namfile = 'p7mf2005.nam' mf = flopy.modflow.Modflow.load(namfile, model_ws=pth, verbose=True, exe_name=mf2005_exe) mf.model_ws = newpth mf.write_input() if ismf2005 is not None: success, buff = mf.run_model(silent=False) assert success, '{} did not run'.format(mf.name) namfile = 'p7mt.nam' mt = flopy.mt3d.mt.Mt3dms.load(namfile, model_ws=pth, verbose=True,
def test_uzf_unit_numbers(): exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False mfnam = 'UZFtest2.nam' pt = os.path.join('..', 'examples', 'data', 'uzf_examples') # copy files try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, 'flopy') compth = lpth pymake.setup(os.path.join(pt, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, verbose=True, model_ws=lpth, forgive=False, exe_name=exe_name) assert m.load_fail is False, 'failed to load all packages' # reset the oc file m.remove_package('OC') output = ['save head', 'print budget'] spd = {} for iper in range(1, m.dis.nper): for istp in [0, 4, 9, 14]: spd[(iper, istp)] = output spd[(0, 0)] = output spd[(1, 1)] = output spd[(1, 2)] = output spd[(1, 3)] = output oc = flopy.modflow.ModflowOc(m, stress_period_data=spd) oc.write_file() if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, 'base model run did not terminate successfully' fn0 = os.path.join(lpth, mfnam) # change uzf iuzfcb2 and add binary uzf output file m.uzf.iuzfcb2 = 61 m.add_output_file(m.uzf.iuzfcb2, extension='uzfcb2.bin', package='UZF') # change the model work space m.change_model_ws(apth, reset_external=True) # rewrite files m.write_input() # run and compare the output files if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, 'new model run did not terminate successfully' fn1 = os.path.join(apth, mfnam) # compare budget terms if run: fsum = os.path.join(compth, '{}.budget.out'.format(os.path.splitext(mfnam)[0])) try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: success = False print('could not perform ls' 'budget comparison') assert success, 'budget comparison failure' # clean up shutil.rmtree(lpth) return
import os import shutil import flopy pthtest = os.path.join('..', 'examples', 'data', 'swtv4_test') newpth = os.path.join('.', 'temp', 't028') # make the directory if it does not exist if not os.path.isdir(newpth): os.makedirs(newpth) swtv4_exe = 'swt_v4' isswtv4 = flopy.which(swtv4_exe) runmodel = False verbose = False swtdir = ['1_box', '1_box', '2_henry', '2_henry', '2_henry', '2_henry', '2_henry', '2_henry', '3_elder', '4_hydrocoin', '5_saltlake', '6_rotation', '6_rotation', '7_swtv4_ex', '7_swtv4_ex', '7_swtv4_ex', '7_swtv4_ex', '7_swtv4_ex', '7_swtv4_ex', '7_swtv4_ex'] subds = ['case1', 'case2', '1_classic_case1', '2_classic_case2', '3_VDF_no_Trans', '4_VDF_uncpl_Trans', '5_VDF_DualD_Trans', '6_age_simulation', '', '', '', '1_symmetric', '2_asymmetric', 'case1', 'case2', 'case3', 'case4', 'case5', 'case6', 'case7'] def test_seawat_array_format(): d = '2_henry' subds = ['1_classic_case1'] for subd in subds: pth = os.path.join(pthtest, d, subd)
import os import shutil import numpy as np import flopy model_ws = os.path.join('temp', 't059') # delete the directory if it exists if os.path.isdir(model_ws): shutil.rmtree(model_ws) exe_names = {'mf6': 'mf6', 'mp7': 'mp7'} run = True for key in exe_names.keys(): v = flopy.which(exe_names[key]) if v is None: run = False break ws = model_ws nm = 'ex01_mf6' # model data nper, nstp, perlen, tsmult = 1, 1, 1., 1. nlay, nrow, ncol = 3, 21, 20 delr = delc = 500. top = 400. botm = [220., 200., 0.] laytyp = [1, 0, 0] kh = [50., 0.01, 200.] kv = [10., 0.01, 20.]
def load_and_write_pcgn(mfnam, pth): """ test044 load and write of MODFLOW-2005 PCGN example problem """ exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, 'flopy') compth = lpth pymake.setup(os.path.join(pth, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, model_ws=lpth, verbose=True, exe_name=exe_name) assert m.load_fail is False if mfnam in ['twri.nam']: # update this list for fixed models assert m.free_format_input is False else: assert m.free_format_input is True if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'base model run did not terminate successfully' fn0 = os.path.join(lpth, mfnam) # rewrite files m.change_model_ws(apth) m.write_input() if run: try: success, buff = m.run_model(silent=False) except: pass assert success, 'new model run did not terminate successfully' fn1 = os.path.join(apth, mfnam) if run: fsum = os.path.join(compth, '{}.head.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_heads(fn0, fn1, outfile=fsum) except: print('could not perform head comparison') assert success, 'head comparison failure' fsum = os.path.join(compth, '{}.budget.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: print('could not perform budget comparison') assert success, 'budget comparison failure' return
def load_and_write_pcgn(mfnam, pth): """ test044 load and write of MODFLOW-2005 PCGN example problem """ exe_name = 'mf2005' v = flopy.which(exe_name) run = True if v is None: run = False try: import pymake lpth = os.path.join(cpth, os.path.splitext(mfnam)[0]) apth = os.path.join(lpth, 'flopy') compth = lpth pymake.setup(os.path.join(pth, mfnam), lpth) except: run = False lpth = pth apth = cpth compth = cpth m = flopy.modflow.Modflow.load(mfnam, model_ws=lpth, verbose=True, exe_name=exe_name) assert m.load_fail is False if mfnam in ['twri.nam']: # update this list for fixed models assert m.free_format_input is False else: assert m.free_format_input is True if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, 'base model run did not terminate successfully' fn0 = os.path.join(lpth, mfnam) # rewrite files m.change_model_ws(apth) m.write_input() if run: try: success, buff = m.run_model(silent=False) except: success = False assert success, 'new model run did not terminate successfully' fn1 = os.path.join(apth, mfnam) if run: fsum = os.path.join(compth, '{}.head.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_heads(fn0, fn1, outfile=fsum, htol=0.005) except: success = False print('could not perform head comparison') assert success, 'head comparison failure' fsum = os.path.join(compth, '{}.budget.out'.format(os.path.splitext(mfnam)[0])) success = False try: success = pymake.compare_budget(fn0, fn1, max_incpd=0.1, max_cumpd=0.1, outfile=fsum) except: success = False print('could not perform budget comparison') assert success, 'budget comparison failure' return