def test_mflist_reference(): import os import numpy as np import shapefile import flopy.modflow as fmf # model_ws = os.path.join('..', 'data', 'freyberg') # ml = fmf.Modflow.load('freyberg.nam', model_ws=model_ws) # make the model ml = fmf.Modflow() assert isinstance(ml, fmf.Modflow) perlen = np.arange(1, 20, 1) nstp = np.flipud(perlen) + 3 tsmult = 1.2 nlay = 10 nrow, ncol = 50, 40 botm = np.arange(0, -100, -10) hk = np.random.random((nrow, ncol)) dis = fmf.ModflowDis(ml, delr=100.0, delc=100.0, nrow=nrow, ncol=ncol, nlay=nlay, nper=perlen.shape[0], perlen=perlen, nstp=nstp, tsmult=tsmult, top=10, botm=botm, steady=False) assert isinstance(dis, fmf.ModflowDis) lpf = fmf.ModflowLpf(ml, hk=hk, vka=10.0, laytyp=1) assert isinstance(lpf, fmf.ModflowLpf) pcg = fmf.ModflowPcg(ml) assert isinstance(pcg, fmf.ModflowPcg) oc = fmf.ModflowOc(ml) assert isinstance(oc, fmf.ModflowOc) ibound = np.ones((nrow, ncol)) ibound[:, 0] = -1 ibound[25:30, 30:39] = 0 bas = fmf.ModflowBas(ml, strt=5.0, ibound=ibound) assert isinstance(bas, fmf.ModflowBas) rch = fmf.ModflowRch(ml, rech={0: 0.00001, 5: 0.0001, 6: 0.0}) assert isinstance(rch, fmf.ModflowRch) wel_dict = {} wel_data = [[9, 25, 20, -200], [0, 0, 0, -400], [5, 20, 32, 500]] wel_dict[0] = wel_data wel_data2 = [[45, 20, 200], [9, 49, 39, 400], [5, 20, 32, 500]] wel_dict[10] = wel_data2 wel = fmf.ModflowWel(ml, stress_period_data={0: wel_data}) assert isinstance(wel, fmf.ModflowWel) ghb_dict = {0: [1, 10, 10, 400, 300]} ghb = fmf.ModflowGhb(ml, stress_period_data=ghb_dict) assert isinstance(ghb, fmf.ModflowGhb) test = os.path.join('temp', 'test3.shp') ml.export(test, kper=0) shp = shapefile.Reader(test) assert shp.numRecords == nrow * ncol
def setup_class(cls): """Make a modflow model.""" print("setting up model...") t0 = time.time() size = 100 nlay = 10 nper = 10 nsfr = int((size**2) / 5) cls.modelname = "junk" cls.model_ws = "temp/t064" external_path = "external/" if not os.path.isdir(cls.model_ws): os.makedirs(cls.model_ws) if not os.path.isdir(os.path.join(cls.model_ws, external_path)): os.makedirs(os.path.join(cls.model_ws, external_path)) m = fm.Modflow(cls.modelname, model_ws=cls.model_ws, external_path=external_path) dis = fm.ModflowDis( m, nper=nper, nlay=nlay, nrow=size, ncol=size, top=nlay, botm=list(range(nlay)), ) rch = fm.ModflowRch( m, rech={k: 0.001 - np.cos(k) * 0.001 for k in range(nper)}) ra = fm.ModflowWel.get_empty(size**2) well_spd = {} for kper in range(nper): ra_per = ra.copy() ra_per["k"] = 1 ra_per["i"] = ((np.ones((size, size)) * np.arange(size)).transpose().ravel().astype(int)) ra_per["j"] = list(range(size)) * size well_spd[kper] = ra wel = fm.ModflowWel(m, stress_period_data=well_spd) # SFR package rd = fm.ModflowSfr2.get_empty_reach_data(nsfr) rd["iseg"] = range(len(rd)) rd["ireach"] = 1 sd = fm.ModflowSfr2.get_empty_segment_data(nsfr) sd["nseg"] = range(len(sd)) sfr = fm.ModflowSfr2(reach_data=rd, segment_data=sd, model=m) cls.init_time = time.time() - t0 cls.m = m
def get_package(self, _mf): content = self.merge() return mf.ModflowRch( _mf, nrchop=content['nrchop'], ipakcb=content['ipakcb'], rech=content['stress_period_data'], irch=content['irch'], extension=content['extension'], unitnumber=content['unitnumber'] )
# [-1., 1., 1., ..., 1., 1., -1.], # [-1., -1., -1., ..., -1., -1., -1.]]]) # set center cell in upper layer to constant head (-1) ibound[0, Nhalf, Nhalf] = -1 # defining the start-values # in the calculation only the -1 cells will be considered # # all values are set to h1 start = h1 * np.ones((N, N)) # and the center value is set to h2 start[Nhalf, Nhalf] = h2 # instantiate the modflow-basic package with iBound and startvalues bas = mf.ModflowBas(ml, ibound=ibound, strt=start) # set the aquifer properties with the lpf-package lpf = mf.ModflowLpf(ml, hk=k) # instantiation of the solver with default values pcg = mf.ModflowPcg(ml) # instantiation of the output control with default values oc = mf.ModflowOc(ml) rch = mf.ModflowRch(ml) ml.write_input() ml.run_model()
def create_package(self, name, content): if name == 'mf': model_ws = os.path.realpath(os.path.join(self._data_folder, self._model_id, content['model_ws'])) if not os.path.exists(model_ws): os.makedirs(model_ws) self._mf = mf.Modflow( modelname=content['modelname'], exe_name=content['exe_name'], version=content['version'], model_ws=model_ws ) if name == 'dis': mf.ModflowDis( self._mf, nlay=content['nlay'], nrow=content['nrow'], ncol=content['ncol'], nper=content['nper'], delr=content['delr'], delc=content['delc'], laycbd=content['laycbd'], top=content['top'], botm=content['botm'], perlen=content['perlen'], nstp=content['nstp'], tsmult=content['tsmult'], steady=content['steady'], itmuni=content['itmuni'], lenuni=content['lenuni'], extension=content['extension'], unitnumber=content['unitnumber'], xul=content['xul'], yul=content['yul'], rotation=content['rotation'], proj4_str=content['proj4_str'], start_datetime=content['start_datetime'] ) if name == 'bas': mf.ModflowBas( self._mf, ibound=content['ibound'], strt=content['strt'], ifrefm=content['ifrefm'], ixsec=content['ixsec'], ichflg=content['ichflg'], stoper=content['stoper'], hnoflo=content['hnoflo'], extension=content['extension'], unitnumber=content['unitnumber'] ) if name == 'lpf': mf.ModflowLpf( self._mf, laytyp=content['laytyp'], layavg=content['layavg'], chani=content['chani'], layvka=content['layvka'], laywet=content['laywet'], ipakcb=content['ipakcb'], hdry=content['hdry'], iwdflg=content['iwdflg'], wetfct=content['wetfct'], iwetit=content['iwetit'], ihdwet=content['ihdwet'], hk=content['hk'], hani=content['hani'], vka=content['vka'], ss=content['ss'], sy=content['sy'], vkcb=content['vkcb'], wetdry=content['wetdry'], storagecoefficient=content['storagecoefficient'], constantcv=content['constantcv'], thickstrt=content['thickstrt'], nocvcorrection=content['nocvcorrection'], novfc=content['novfc'], extension=content['extension'], unitnumber=content['unitnumber'] ) if name == 'pcg': mf.ModflowPcg( self._mf, mxiter=content['mxiter'], iter1=content['iter1'], npcond=content['npcond'], hclose=content['hclose'], rclose=content['rclose'], relax=content['relax'], nbpol=content['nbpol'], iprpcg=content['iprpcg'], mutpcg=content['mutpcg'], damp=content['damp'], dampt=content['dampt'], ihcofadd=content['ihcofadd'], extension=content['extension'], unitnumber=content['unitnumber'] ) if name == 'oc': mf.ModflowOc( self._mf, ihedfm=content['ihedfm'], iddnfm=content['iddnfm'], chedfm=content['chedfm'], cddnfm=content['cddnfm'], cboufm=content['cboufm'], compact=content['compact'], stress_period_data=self.get_stress_period_data(content['stress_period_data']), extension=content['extension'], unitnumber=content['unitnumber'] ) if name == 'risdlkfjlv': mf.ModflowRiv( self._mf, ipakcb=content['ipakcb'], stress_period_data=content['stress_period_data'], dtype=content['dtype'], extension=content['extension'], unitnumber=content['unitnumber'], options=content['options'], naux=content['naux'] ) if name == 'wel': mf.ModflowWel( self._mf, ipakcb=content['ipakcb'], stress_period_data=content['stress_period_data'], dtype=content['dtype'], extension=content['extension'], unitnumber=content['unitnumber'], options=content['options'] ) if name == 'rch': mf.ModflowRch( self._mf, ipakcb=content['ipakcb'], nrchop=content['nrchop'], rech=content['rech'], extension=content['extension'], unitnumber=content['unitnumber'] ) if name == 'chd': mf.ModflowChd( self._mf, stress_period_data=content['stress_period_data'], dtype=content['dtype'], options=content['options'], extension=content['extension'], unitnumber=content['unitnumber'] ) if name == 'ghb': mf.ModflowGhb( self._mf, ipakcb=content['ipakcb'], stress_period_data=content['stress_period_data'], dtype=content['dtype'], options=content['options'], extension=content['extension'], unitnumber=content['unitnumber'] )
laycon = 1 # layer type, confined (0), unconfined (1), constant T, variable S (2), variable T, variable S (default is 3) bcf = mf.ModflowBcf(m, hy=hy, sf1=sf, laycon=1) # BAS package (Basic Package) ibound = np.ones((nlay, nrow, ncol)) # # active cells ibound[:, :, 0] = -1 # Set every first element of every column to -1 ibound[:, :, -1] = -1 # Set every last element of every column to -1 strt = 0 * np.ones( (nrow, ncol) ) # in the calculation only the -1 cells will be considered (all values can be set to 0) bas = mf.ModflowBas(m, ibound=ibound, strt=strt) # setting up recharge data and recharge package recharge_data = 0.250 # recharge flux mm/year (default is 1.e-3) nrchop = 1 # optional code (1: to top grid layer only; 2: to layer defined in irch 3: to highest active cell) rch = mf.ModflowRch(m, nrchop=nrchop, rech=recharge_data) # setting up the well package with stress periods pumping_rate = -4e+10 # m^3 / year lrcq = {0: [[0, 5, 6, 0.]], 1: [[0, 5, 6, -4e+10]]} wel = mf.ModflowWel(m, stress_period_data=lrcq) # instantiation of the solver with default values pcg = mf.ModflowPcg(m) # pre-conjugate gradient solver # instantiation of the output control with default values oc = mf.ModflowOc(m) # output control timeStartWritingInput = datetime.now() ml.write_input() timeStartRunningModel = datetime.now()
def main(): ''' This is the main function. ''' # Package all the required file paths into the Paths object mfPaths = Paths() # Package all the required framework specifications into the mfFrame object mfFrame = Frame(Paths=mfPaths, dx_dy=dx_dy) if build_from_gis: # Build the model framework ASCII files from the GIS layers. Note that this # requires a GDAL installation. If you don't want to get into that you # can skip this step and simply build the model from the ASCII files that I've # already created. mfFrame.build_frame(Paths=mfPaths) # --------------------------------------------- # --------------------------------------------- # Now use Flopy to build the MODFLOW model packages # --------------------------------------------- # --------------------------------------------- start_dir = os.getcwd() os.chdir(mfPaths.modflow_dir ) # This is simplest if done inside the MODFLOW directory # Initialize a Flopy model object. This is the base class around which the model # packages are built. Modflow = mf.Modflow(mfFrame.model_name, external_path='./', version=mfPaths.mf_version) # The .oc ('output control') package specifies how the model output is written. # This model includes a single steady state stress period. Save the # distribution of heads as well as the flow budget/mass balance to binaries. # These can be plotted or converted to rasters (the current version of the script # doesn't do any post-processing.) oc = mf.ModflowOc(Modflow, stress_period_data={ (0, 0): ['SAVE HEAD', 'SAVE BUDGET'] }) # The .dis and .bas packages define the model framework. I've already defined # the framework attributes using the mfFrame object and simply pass those # attributes to the constructor. dis = mf.ModflowDis(Modflow,mfFrame.nlay,mfFrame.nrow,mfFrame.ncol,\ delr=mfFrame.delr,delc=mfFrame.delc,\ top=mfFrame.top,botm=mfFrame.bottom) bas = mf.ModflowBas(Modflow, ibound=mfFrame.ibound, strt=mfFrame.top, hnoflo=mfFrame.hnoflo) # The .upw package describes the system properties (e.g., transmissivity/conductivity). # For this model I simply give it a constant hydraulic conductivity field. This model # converges but I have no idea how physically realistic it is. If you would # like to make it more physically realistic (e.g., try to fit head or discharge # data) you would need to estimate the hydraulic conductivity field via # calibration/inverse modeling hk = np.ones(np.shape(mfFrame.ibound)) upw = mf.ModflowUpw(Modflow, laytyp=mfFrame.laytyp, hk=hk, ipakcb=53) # The .nwt package defines the solver specs. Just use the defaults. nwt = mf.ModflowNwt(Modflow) # RECHARGE INPUTS TO THE SYSTEM # ----------------------------- # The .rch packages specifies recharge/precipitation inputs to the water table. # Remember that I have already generated an array from the GIS layer and attached # it to the mfFrame object. rch = mf.ModflowRch(Modflow, nrchop=3, rech={0: mfFrame.rch}, ipakcb=53) # BASEFLOW DISCHARGE FROM THE SYSTEM # ---------------------------------- # The .drn package is one method of simulating the discharge of groundwater as # base-flow in streams in rivers. Define every landsurface cell as a drain # in order to allow the discharge network to emerge from topography. drn_stages = mfFrame.top drn_stages[mfFrame.ibound.squeeze() <= 0] = np.nan drn_input = build_drain_input(mfFrame=mfFrame, stages=drn_stages) drn = mf.ModflowDrn(Modflow, stress_period_data=drn_input, ipakcb=53) # Now write the files. Flopy can also run the model if you tell it where the # binary is, but if I understood your method correctly you will be invoking something # from hydroshare. For convenience I am writing a windows .bat file that # can be used to run the model. Modflow.write_input() os.chdir(start_dir) with open(mfPaths.mf_bat_file, 'w') as fout: fout.write('%s %s' % (binary_path, os.path.basename(mfPaths.nam_file))) folder = mfPaths.scratch_dir for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) folder = mfPaths.model_frame_dir for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) folder = mfPaths.data_dir for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) return
def get_package(self, _mf): content = self.merge() return mf.ModflowRch(_mf, **content)
def calculate_model(z1_hk, z2_hk, z3_hk): # Z1_hk = 15 # 3<Z1_hk<15 # Z2_hk = 15 # 3<Z2_hk<15 # Z3_hk = 3 # 3<Z3_hk<15 hobs = [ [0, 20, 10, 69.52], [0, 40, 10, 71.44], [0, 60, 10, 72.99], [0, 80, 10, 73.86], [0, 20, 45, 58.73], [0, 40, 45, 50.57], [0, 60, 45, 54.31], [0, 80, 45, 58.06], [0, 20, 80, 56.31], [0, 40, 80, 52.32], [0, 60, 80, 46.35], [0, 80, 80, 29.01], [0, 20, 100, 57.24], [0, 40, 100, 54.24], [0, 60, 100, 39.48], [0, 80, 100, 48.47], ] model_path = os.path.join('_model') if os.path.exists(model_path): shutil.rmtree(model_path) modelname = 'parEstMod' version = 'mf2005' exe_name = 'mf2005' if platform.system() == 'Windows': exe_name = 'mf2005.exe' ml = mf.Modflow(modelname=modelname, exe_name=exe_name, version=version, model_ws=model_path) nlay = 1 nrow = 90 ncol = 120 area_width_y = 9000 area_width_x = 12000 delc = area_width_x / ncol delr = area_width_y / nrow nper = 1 top = 100 botm = 0 dis = mf.ModflowDis(ml, nlay=nlay, nrow=nrow, ncol=ncol, delr=delr, delc=delc, top=top, botm=botm, nper=nper, steady=True) ibound = 1 strt = 100 bas = mf.ModflowBas(ml, ibound=ibound, strt=strt) mask_arr = np.zeros((nlay, nrow, ncol)) mask_arr[:, :, 0] = 80 mask_arr[:, :, -1] = 60 ghb_spd = {0: []} for layer_id in range(nlay): for row_id in range(nrow): for col_id in range(ncol): if mask_arr[layer_id][row_id][col_id] > 0: ghb_spd[0].append([ layer_id, row_id, col_id, mask_arr[layer_id][row_id][col_id], 200 ]) ghb = mf.ModflowGhb(ml, stress_period_data=ghb_spd) rch = 0.0002 rech = {} rech[0] = rch rch = mf.ModflowRch(ml, rech=rech, nrchop=3) welSp = {} welSp[0] = [ [0, 20, 20, -20000], [0, 40, 40, -20000], [0, 60, 60, -20000], [0, 80, 80, -20000], [0, 60, 100, -20000], ] wel = mf.ModflowWel(ml, stress_period_data=welSp) hk = np.zeros((nlay, nrow, ncol)) hk[:, :, 0:40] = z1_hk hk[:, :, 40:80] = z2_hk hk[:, :, 80:120] = z3_hk lpf = mf.ModflowLpf(ml, hk=hk, layavg=0, layvka=0, sy=0.3, ipakcb=53) pcg = mf.ModflowPcg(ml, rclose=1e-1) oc = mf.ModflowOc(ml) ml.write_input() ml.run_model(silent=True) hds = fu.HeadFile(os.path.join(model_path, modelname + '.hds')) times = hds.get_times() response = [] for hob in hobs: observed = hob[3] calculated = hds.get_data(totim=times[-1])[hob[0]][hob[1]][hob[2]] response.append(observed - calculated) return json.dumps(response)
nrow=nrow, ncol=ncol, laycbd=0, delr=delr, delc=delc, top=botm[0], botm=botm[1:], nper=nper, perlen=perlen, nstp=nstp, steady=steady) bas = mf.ModflowBas(ml, ibound=ibound, strt=ihead) lpf = mf.ModflowLpf(ml, laytyp=laytyp, hk=hk, vka=vka) wel = mf.ModflowWel(ml, stress_period_data=base_well_data) ghb = mf.ModflowGhb(ml, stress_period_data=ghb_data) rch = mf.ModflowRch(ml, rech=rch_data) swi = mf.ModflowSwi2(ml, nsrf=1, istrat=1, toeslope=toeslope, tipslope=tipslope, nu=nu, zeta=z, ssz=ssz, isource=iso, nsolver=1, adaptive=adaptive, nadptmx=nadptmx, nadptmn=nadptmn, nobs=nobs, iswiobs=iswiobs,
Ny, Nx, delr=dx, delc=dy, top=zTop, botm=zBot, laycbd=LAYCBD, nper=NPER, perlen=PERLEN, nstp=NSTP, steady=STEADY) bas = fm.ModflowBas(mf, ibound=IBOUND, strt=STRTHD) lpf = fm.ModflowLpf(mf, hk=HK, vka=VKA, sy=SY, ss=SS, laytyp=LAYTYP, vkcb=VKCB) ghb = fm.ModflowGhb(mf, stress_period_data=GHB) wel = fm.ModflowWel(mf, stress_period_data=WEL) rch = fm.ModflowRch(mf, nrchop=3, rech=RECH) evt = fm.ModflowEvt(mf, nevtop=3, evtr=EVTR) oc = fm.ModflowOc(mf, stress_period_data=OC, compact=True) pcg = fm.ModflowPcg(mf) #%% Write the model input files and running MODFLOW mf.write_input() success, mfoutput = mf.run_model(silent=False, pause=False) print('Running success = {}'.format(success)) if not success: raise Exception('MODFLOW did not terminate normally.') #%% SHOWING RESULTS
steady=STEADY) bas = fm.ModflowBas(mf, ibound=IBOUND, strt=STRTHD) lpf = fm.ModflowLpf(mf, hk=HK, vka=VKA, chani=[1.e-20, 1.e-20], sy=SY, ss=SS, laytyp=LAYTYP, vkcb=VKCB, ipakcb=53) ghb = fm.ModflowGhb(mf, stress_period_data=GHB, ipakcb=53) riv = fm.ModflowRiv(mf, stress_period_data=RIV, ipakcb=53) drn = fm.ModflowDrn(mf, stress_period_data=DRN, ipakcb=53) wel = fm.ModflowWel(mf, stress_period_data=SEEP, ipakcb=53) rch = fm.ModflowRch(mf, nrchop=3, rech=RECH, ipakcb=53) evt = fm.ModflowEvt(mf, nevtop=3, evtr=EVTR, ipakcb=53) oc = fm.ModflowOc(mf, stress_period_data=OC, compact=True) #pcg = fm.ModflowPcg(mf, mxiter=200, iter1=200, hclose=0.001, rclose=0.001) sms = fm.ModflowSms(mf) #, mxiter=200, iter1=200, hclose=0.001, rclose=0.001) #%% Write the model input files and run MODFLOW mf.write_input() success, mfoutput = mf.run_model(silent=False, pause=False) print('Running success = {}'.format(success)) if not success: raise Exception('MODFLOW did not terminate normally.') #%% SHOWING RESULTS
#to 1m (delc = 1). The latter requires specification #of the layer, row, column, and injection rate of the #well for each stress period. The layers, rows, columns, #and the stress period are numbered (consistent with #Python's zero-based numbering convention) starting at #0. The required data are stored in a Python dictionary #(lrcQ in the code below), which is used in FloPy to #store data that can vary by stress period. The lrcQ #dictionary specifies that two wells (one in cell 1, 1, #51 and one in cell 1, 1, 151), each with a rate of #-1 m3/d, will be active for the first stress period. #Because this is a steady-state model, there is only #one stress period and therefore only one entry in the #dictionary. fpm.ModflowRch(model, rech=0.001) lrcQ = {0: [[0, 0, 50, -1], [0, 0, 150, -1]]} fpm.ModflowWel(model, stress_period_data=lrcQ) #5. The preconditioned conjugate-gradient (PCG) solver, #using the default settings, is specified to solve the #model. fpm.ModflowPcg(model) #6. The frequency and type of output that MODFLOW #writes to an output file is specified with the output #control (OC) package. In this case, the budget is printed #and heads are saved (the default), so no arguments are #needed.