zmk
2023-12-26 736a7162bc5e5da76cafacecd821a46efc09f143
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
 
# 导入Flask类
from flask import Flask
from flask import jsonify
from flask import request
from flask_cors import CORS
import sys
import numpy as np
import pandas as pd
import flopy
import flopy.utils.binaryfile as bf
import csv
import time
from openpyxl import load_workbook
import os
import shutil
import json
import Base as base
import CalHead
import ModelPeriod
 
 
base_init_year=["2020","2021","2022"]
river_start_index = 454
river_end_index =562
 
#预测周期数
predict_per = 12
 
#降水量
 
base_water = base.prefix + 'base_water.ini'
def predict_water_chart(base_year,start_time ,end_time):
    
    
     water_array = np.loadtxt(base_water, dtype=str,encoding='utf-8')
 
     y_data=[]
     x_data= ModelPeriod.get_months_in_range_ym("2022-01","2022-12")
     water= water_array[0]
     for e in water:
         y_data.append(e)
    
     result = {"y_data": y_data, "x_data": x_data}
     return result
    
#河流的折线图
 
base_river = base.prefix + 'base_river.ini'
def predict_river_chart(base_year,start_time ,end_time):
     
    
     river_array = np.loadtxt(base_river, dtype=str,encoding='utf-8')
     
     y_data=[]
     x_data= ModelPeriod.get_months_in_range_ym("2022-01","2022-12")
     for e in river_array:
         y_data.append(e)
         
     result = {"y_data": y_data, "x_data": x_data}
     return result
 
 
def run_model_predict(model_name):
       
    predictiondata=""   
    prediction_path = base.model_dir + model_name +"\\prediction.json"
    if os.path.exists(prediction_path):
        with open(prediction_path,encoding='utf-8') as f:
             predictiondata = json.load(f)
    
    if predictiondata:
                    
        try:
            updateDisFile(model_name,predict_per)
            
            updateBase6File(model_name,predictiondata)
 
            updateRchFile(model_name,predictiondata)
            
            updateRiverFile(model_name,predictiondata)
        except:
            
            return "请检查初始水头、降水量、永定河入渗量、开采量等参数是否填写完整!"
            
            
    else:
        print("prediction.json 预测场景文件为空,无需更改相应文件")
    
    
    model_ws = base.model_dir + model_name
 
    ml = flopy.modflow.Modflow.load("modflow.nam", model_ws=model_ws,
                                     exe_name="mf2005", verbose=True,  version="mf2005", check=False)   
    ml.run_model(report = True)
    return "预测模型运行成功!"
 
 
    
#获取 area的 name--> ratio 的结构
def get_area_dict(area):
    result ={}
    
    for i in range(len(area)):
        name = area[i]["name"]
        rt = area[i]["ratio"]
        result[name]= rt
    return result
 
 
#获取区县的 row+column --> name结构
def get_distric_dict():
    data =  base.district   
    result = {}
    for row ,column ,id ,name in data:
        key = str(row)+","+str(column)
        result[key]= name 
    return result
    
    
#根据 row clomn  获取 ratio
def get_row_column_ratio(row, column ,district_dict, area_dict ):
     key = str(row) +"," + str(column)
     if area_dict.__contains__("全部区域"):
         return area_dict["全部区域"]
     
     if district_dict.__contains__(key):
          name = district_dict[key]
          ratio = area_dict[name]
          return float(ratio)
        
     return float(1.0)
    
 
 
 
def updateRiverFile(model_name,predictiondata):
  
    flag = check_rain_param(predictiondata)
    
    if flag == "true":
        
        rain_ratio = float(predictiondata["rain"]["ratio"])
        rain_base_year = predictiondata["rain"]["base_year"]
        
        river_ratio= float(predictiondata["river"]["ratio"])
        area= predictiondata["mine"]["area"] 
        
        ws = base.predictParamModel + rain_base_year
        
        baseMdoel = flopy.modflow.Modflow.load("modflow.nam", model_ws= ws,
                                    exe_name="mf2005", verbose=True,  version="mf2005", check=False)
        
        update_model_ws = base.model_dir + model_name
        updateMdoel = flopy.modflow.Modflow.load("modflow.nam", model_ws= update_model_ws,
                                    exe_name="mf2005", verbose=True,  version="mf2005", check=False)
        
        district_dict = get_distric_dict()
  
        area_dict = get_area_dict(area)
        
        lrcq = {}
        
        for per in range(predict_per):
            wel = [] 
            array2d = [] 
            
            wel = baseMdoel.wel.stress_period_data.__getitem__(kper = per)
            wel_len = len(wel)
            
            #侧向边界
            for i in range (0,453):
                wel[i][3] = wel[i][3] * rain_ratio
                     
            #河流
            for i in range(453, 562):
                 wel[i][3] = wel[i][3] * river_ratio
                     
            #抽水井
            for i in range(562,wel_len):
                
                r = (float) (get_row_column_ratio(wel[i][1], wel[i][2], district_dict, area_dict))
                wel[i][3] = wel[i][3]  * r    
            
 
            #重置数组
            for Layer, Row, Column, Q in wel:
                array = [Layer, Row, Column, Q]
                array2d.append(array)
                
            flex_data= getFlexdata(model_name)
    
            for i in range(len(flex_data)):
                array2d.append(flex_data[i])
          
            lrcq[per] = array2d 
            
        flopy.modflow.ModflowWel(updateMdoel,stress_period_data=lrcq)
        updateMdoel.write_input()          
                               
    else:     
        print("Well--River文件无需修改!")
 
#追加复杂原汇项信息
def getFlexdata(model_name):
    welldata=""
    well_path = base.model_dir + model_name +"\\pump_well.json"
    data=[]
    if os.path.exists(well_path):
        with open(well_path,encoding='utf-8') as f:
             welldata = json.load(f)    
             wel= welldata["well"]
            
             for i in range (len(wel)):
                 layer = int (wel[i]['layer'])-1
                 row= int(wel[i]['row'])-1
                 column = int(wel[i]['column'])-1
                 v = float(wel[i]['value'])
                 arr = [layer,row, column, v]
                 data.append(arr)
                 
    return data
  
 
def  updateRchFile(model_name,predictiondata):   
    flag = check_rain_param(predictiondata)
    if flag == "true":
         #丰水年 枯水年
        base_year = predictiondata["rain"]["base_year"]  
        ratio= float(predictiondata["rain"]["ratio"])
        
         #数据来源的模型文件夹
        base_ws=  base.predictParamModel + base_year
        
        baseMdoel = flopy.modflow.Modflow.load("modflow.nam", model_ws= base_ws,
                                    exe_name="mf2005", verbose=True,  version="mf2005", check=False)
        
        update_model_ws = base.model_dir + model_name
        updateMdoel = flopy.modflow.Modflow.load("modflow.nam", model_ws= update_model_ws,
                                    exe_name="mf2005", verbose=True,  version="mf2005", check=False)
        
        for per in range(predict_per):
            
            item = baseMdoel.rch.rech.__getitem__(kper = per)
            array2d = item.get_value()
            array2d_len = len(array2d)
            
            for i in range(array2d_len):
      
                  array_len = len(array2d[i])
                  for j in range(array_len):
                  
                      if str(base.area_array[i][j]) != '-9999':
                    
                          array2d[i][j] =  array2d[i][j] * ratio
                           
            updateMdoel.rch.rech.__setitem__(key = per, value=array2d) 
          
        rch = flopy.modflow.ModflowRch(updateMdoel, rech=updateMdoel.rch.rech)
        rch.write_file(check=False)
        
    else:   
        print("Rch文件无需修改!")      
        
def check_rain_param(predictiondata):
    
     rain = predictiondata["rain"]
     if not rain:
         print("Rch预测参数为空,无需要修改")
         return "false"
     
     base_year = predictiondata["rain"]["base_year"]
     if not base_year :
         print(" Rch : base_year预测参数为空,无需要修改")
         return "false"
     
     ratio= predictiondata["rain"]["ratio"]
     if not ratio :
         print(" Rch : ratio预测参数为空,无需要修改")
         return "false"
     
     return "true"
     
        
     #更新bas6文件 初始水头信息
def updateBase6File(model_name,predictdata):
     model_ws = base.model_dir + model_name
     ml = flopy.modflow.Modflow.load("modflow.nam", model_ws=model_ws,
                                    exe_name="mf2005", verbose=True,  version="mf2005", check=False)
     
     
     #初始水头
     init_header = predictdata["initHeader"]
     
     dir = base.model_dir + init_header + "\\modflow.head"
     head = bf.HeadFile(dir)
     alldata = head.get_alldata()
     
     lens = len(alldata)
     last_index = lens-3
     
     last_array3= alldata[last_index]
 
     strt = ml.bas6.strt
     # strs = ml.bas6.strt.__getitem__(2)
     # print(strs.get_value())
     strt.__setitem__(0,last_array3[0])
     strt.__setitem__(1,last_array3[1])
     strt.__setitem__(2,last_array3[2])
     
    
     mfBase6 = flopy.modflow.ModflowBas(
          ml,
          strt= strt,
          ibound=ml.bas6.ibound,
          hnoflo=ml.bas6.hnoflo,
          extension="bas6",)
     
     mfBase6.write_file(check=False)
 
 
#修改dis 文件
def updateDisFile(model_name, per):
 
    model_ws = base.model_dir + model_name
    ml = flopy.modflow.Modflow.load("modflow.nam", model_ws=model_ws,
                                    exe_name="mf2005", verbose=True,  version="mf2005", check=False)
 
    mfDis = flopy.modflow.ModflowDis(
        ml,
        nlay=ml.dis.nlay,
        nrow=ml.dis.nrow,
        ncol=ml.dis.ncol,
        nper=per,
        delr=ml.dis.delr,
        delc=ml.dis.delc,
        top=ml.dis.top,
        botm=ml.dis.botm,
        perlen=ml.dis.perlen,
        nstp=ml.dis.nstp,
        tsmult=ml.dis.tsmult,
        steady=ml.dis.steady,
        itmuni=ml.dis.itmuni,
        lenuni=ml.dis.lenuni,
        extension="dis")
 
    mfDis.write_file(check=False)