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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
 
# 导入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
 
 
# strt = ml.bas6.strt
# # strs = ml.bas6.strt.__getitem__(1)
# # print(strs.get_value())
 
# mdBase = flopy.modflow.ModflowBas(ml,strt=1.0,ibound=ml.bas6.ibound)
# mdBase.write_file(check=False)
 
 
base_init_year=["2020","2021","2022"]
river_start_index = 454
river_end_index =562
 
#预测周期数
predict_per = 12
 
#降水量
# def predict_water_chart(base_year,start_time ,end_time):
#      model_ws = base.baseModel
#      baseMdoel = flopy.modflow.Modflow.load("modflow.nam", model_ws=model_ws,
#                                     exe_name="mf2005", verbose=True,  version="mf2005", check=False)   
#      index = 0
#      if base_year in base_init_year:
#          index = base_init_year.index(str(base_year))
         
#      y_data=[]
#      x_data=[]
#      satrt_index = index*12
#      end_index = satrt_index+12
#      for per in range(satrt_index,end_index):
#          item = baseMdoel.rch.rech.__getitem__(kper=per)
#          value = item.get_value()
#          value_float = np.array(value)
#          avg = value_float.mean()
#          y_data.append(float (avg))
         
#      start_month = str(base_year) +"-01"
#      end_month = str(base_year) +"-12"
#      x_data= ModelPeriod.get_months_in_range_ym(start_month,end_month)
#      result = {"y_data": y_data, "x_data": x_data}
#      return result
 
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')
     print(water_array)
     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
    
#河流的折线图
# def predict_river_chart(base_year,start_time ,end_time):
#      model_ws = base.baseModel
#      baseMdoel = flopy.modflow.Modflow.load("modflow.nam", model_ws=model_ws,
#                                     exe_name="mf2005", verbose=True,  version="mf2005", check=False)    
#      index = 0
#      if base_year in base_init_year:
#          index = base_init_year.index(str(base_year))
         
#      y_data=[]
#      x_data=[]
#      satrt_index = index*12
#      end_index = satrt_index+12 
#      for per in range(satrt_index,end_index):
#         wel = baseMdoel.wel.stress_period_data.__getitem__(kper=per)
#         arr=[]
#         for i in range(river_start_index, river_end_index):
#             Q = wel[i][3]
#             arr.append(float(Q))
#         avg = np.array(arr).mean()
#         y_data.append(float(avg))    
#      start_month = str(base_year) +"-01"
#      end_month = str(base_year) +"-12"
#      x_data= ModelPeriod.get_months_in_range_ym(start_month,end_month)
#      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')
     print(river_array)
     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:
  
            per =  ModelPeriod.get_months_in_range_count(
                predictiondata["start_time"], predictiondata["end_time"])
                    
            # updateDisFile(model_name,per)
            
            # updateBase6File(model_name,predictiondata)
 
            #updateRchFile(model_name,predictiondata)
            
            updateRiverFile(model_name,predictiondata)
            
            #updateMineFile(model_name,predictiondata)
    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 jsonify("运行成功!")
 
 
 
 
#更新采集区的数据,分为1.按照区域,2.按照全部 进行更新
def updateMineFile(model_name,predictiondata):
    
    start_time =predictiondata["start_time"] 
    end_time = predictiondata["end_time"]   
    base_year = predictiondata["mine"]["base_year"]  
    
    base_start= str(base_year) + "-" +  str(start_time.split("-")[1])
    base_end= str(base_year) + "-" +  str(end_time.split("-")[1])
    
    start_index = (int)(base.times_month_per_dict[base_start])
    end_index = (int)(base.times_month_per_dict[base_end])
    
    pers= end_index-start_index + 1  
    
    area= predictiondata["mine"]["area"]       
    flag = check_mine_param(predictiondata) 
    
    if flag == 'true':
        baseMdoel = flopy.modflow.Modflow.load("modflow.nam", model_ws= base.baseModel,
                                    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(pers):
            wel = [] 
            wel = baseMdoel.wel.stress_period_data.__getitem__(kper = (per + start_index ))
            array2d = []      
            count = 1      
            for Layer, Row, Column, Q in wel:
                array = []
                # 如果是河流的数据范围
                if count > river_end_index :  
                    
                     r = (float) (get_row_column_ratio(Row, Column, district_dict, area_dict))
                    
                     array = [Layer, Row, Column, Q * r]
                     
                else:
                     array = [Layer, Row, Column, Q]
                              
                array2d.append(array)  
                count +=1
            
            lrcq[per] = array2d 
            
        flopy.modflow.ModflowWel(updateMdoel,stress_period_data=lrcq)
        updateMdoel.write_input()          
    else:
           print("Well--Mine文件无需修改!")    
 
    
#获取 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 check_mine_param(predictiondata):
    
     mine = predictiondata["mine"]
     if not mine:
         print("抽水井 预测参数为空,无需要修改")
         return "false"
     
     base_year = predictiondata["mine"]["base_year"]
     if not base_year :
         print(" Mine : base_year预测参数为空,无需要修改")
         return "false"
     
     area= predictiondata["mine"]["area"]
     if not area  :
         print(" Mine : area预测参数为空,无需要修改")
         return "false"
     
     return "true"
 
 
#更新河流的倍数
# def updateRiverFile(model_name,predictiondata):
  
#     start_time =predictiondata["start_time"] 
#     end_time = predictiondata["end_time"] 
#     base_year = predictiondata["river"]["base_year"]  
    
#     ratio= float(predictiondata["river"]["ratio"])
    
#     base_start= str(base_year) + "-" +  str(start_time.split("-")[1])
#     base_end= str(base_year) + "-" +  str(end_time.split("-")[1])
    
#     start_index = (int)(base.times_month_per_dict[base_start])
#     end_index = (int)(base.times_month_per_dict[base_end])
    
#     pers= end_index-start_index + 1
    
 
#     flag = check_river_param(predictiondata)
    
#     if flag == "true":
        
#         baseMdoel = flopy.modflow.Modflow.load("modflow.nam", model_ws= base.baseModel,
#                                     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)
          
#         lrcq = {}
#         for per in range(pers):
#             wel = [] 
 
#             wel = baseMdoel.wel.stress_period_data.__getitem__(kper = (per + start_index ))
#             array2d = []
            
#             count = 1
            
#             for Layer, Row, Column, Q in wel:
#                 array = []
#                 # 如果是河流的数据范围
#                 if count > river_start_index and count <= river_end_index:             
#                      array = [Layer, Row, Column, Q * ratio]
#                 else:
#                      array = [Layer, Row, Column, Q]
                              
#                 array2d.append(array)  
#                 count +=1
            
#             lrcq[per] = array2d 
            
#         flopy.modflow.ModflowWel(updateMdoel,stress_period_data=lrcq)
#         updateMdoel.write_input()          
                               
#     else:     
#         print("Well--River文件无需修改!")
 
 
def updateRiverFile(model_name,predictiondata):
  
    start_time =predictiondata["start_time"] 
    end_time = predictiondata["end_time"] 
   
    
    river_ratio= float(predictiondata["river"]["ratio"])
  
    rain_ratio = float(predictiondata["rain"]["ratio"])
    rain_base_year = predictiondata["rain"]["base_year"]
    
    area= predictiondata["mine"]["area"] 
 
    flag = check_river_param(predictiondata)
    
    if flag == "true":
        
        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 = [] 
 
            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    
               
            lrcq[per] = wel 
            
        flopy.modflow.ModflowWel(updateMdoel,stress_period_data=lrcq)
        updateMdoel.write_input()          
                               
    else:     
        print("Well--River文件无需修改!")
 
def check_river_param(predictiondata):
    
     river = predictiondata["river"]
     if not river:
         print("River预测参数为空,无需要修改")
         return "false"
     
     base_year = predictiondata["river"]["base_year"]
     if not base_year :
         print(" River : base_year预测参数为空,无需要修改")
         return "false"
     
     ratio= predictiondata["river"]["ratio"]
     if not ratio or ratio == "1" :
         print(" River : ratio预测参数为空,无需要修改")
         return "false"
     
     return "true"
 
 
# def  updateRchFile(model_name,predictiondata):
    
#     start_time =predictiondata["start_time"] 
#     end_time = predictiondata["end_time"] 
    
#     base_year = predictiondata["rain"]["base_year"]  
#     ratio= float(predictiondata["rain"]["ratio"])
    
#     base_start= str(base_year) + "-" +  str(start_time.split("-")[1])
#     base_end= str(base_year) + "-" +  str(end_time.split("-")[1])
    
#     start_index = (int)(base.times_month_per_dict[base_start])
#     end_index = (int)(base.times_month_per_dict[base_end])
#     pers= end_index-start_index + 1
    
    
#     flag = check_rain_param(predictiondata)
  
#     if flag == "true":
        
#         baseMdoel = flopy.modflow.Modflow.load("modflow.nam", model_ws= base.baseModel,
#                                     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(pers):
            
#             item = baseMdoel.rch.rech.__getitem__(kper = (per + start_index))
#             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  updateRchFile(model_name,predictiondata):
    
    start_time =predictiondata["start_time"] 
    end_time = predictiondata["end_time"] 
    
    #丰水年 枯水年
    base_year = predictiondata["rain"]["base_year"]  
    ratio= float(predictiondata["rain"]["ratio"])
    
    
    flag = check_rain_param(predictiondata)
    
    #数据来源的模型文件夹
    base_ws=  base.predictParamModel + base_year
  
    if flag == "true":
        
        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 or ratio == "1" :
         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)