# Coverage for grm\GRM_dialog.py : 0%

## 2002 statements

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1# -*- coding: utf-8 -*-

2"""

3

4/***************************************************************************

5 GRMDialog

6 A QGIS plugin

7 GRM

8 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/

9 -------------------

10 begin : 2019-12-18

11 git sha : $Format:%H$

12 copyright : (C) 2019 by KICT/Hermesys

13 email : shpark@hermesys.co.kr

14 ***************************************************************************/

15

16/***************************************************************************

17 * *

18 * This program is free software; you can redistribute it and/or modify *

19 * it under the terms of the GNU General Public License as published by *

20 * the Free Software Foundation; either version 2 of the License, or *

21 * (at your option) any later version. *

22 * *

23 ***************************************************************************/

24"""

25

26 import os

27 import xml.etree.ElementTree as ET

28 from typing import List

29

30 from qgis.core import (

31 QgsGeometry,

32 QgsPointXY,

33 QgsProject,

34 QgsRaster,

35 QgsRasterLayer,

36 QgsRectangle,

37 QgsVectorLayer,

38)

39 from qgis.gui import (

40 QgsMapTool,

41 QgsMapToolPan,

42 QgsMapToolZoom,

43 QgsRubberBand,

44 QgsVertexMarker,

45)

46 from qgis.PyQt import QtGui, QtWidgets

47 from qgis.PyQt.QtCore import QDateTime, QFileInfo, QSize, Qt, pyqtSignal

48 from qgis.PyQt.QtGui import QColor

49 from qgis.PyQt.QtWidgets import (

50 QAbstractItemView,

51 QAction,

52 QColorDialog,

53 QDockWidget,

54 QGridLayout,

55 QInputDialog,

56 QLineEdit,

57 QListWidgetItem,

58 QMessageBox,

59 QPushButton,

60 QRadioButton,

61 QTabBar,

62 QTableWidgetItem,

63 QWidget,

64)

65

66 from grm.AddFlowControl_dialog import AddFlowControl

67 from grm.css import css_sheet

68 from grm.lib.Get_Set import set_Controls

69 from grm.lib.GRM_DLL import grmWSinfo

70 from grm.lib.Raster import AscToShape

71 from grm.lib.Util import Execute, MsError, MsInfo, Opewn_ViewFile

72 from grm.lib.xmltodict import parse, unparse

73 from grm.plugin.flow_layer import get_flow_layer

74 from grm.plugin.grid_layer import get_point_layer

75 from grm.ui.GRM_dialog_base import Ui_MainWindow

76 from grm.utils.enum_types import (

77 EnumInterceptionMethod,

78 EnumPETMethod,

79 EnumSnowMeltMethod,

80)

81 from grm.XMLCheck import xmls

82 from grm.utils.ex_float_conv import ex_to_float

83

84_get_set_control = set_Controls()

85_XmlCheck = xmls()

86

87

88 class GRMDialog(QtWidgets.QMainWindow, Ui_MainWindow):

89 closeDialogEvent = pyqtSignal()

90

91 def __init__(

92 self,

93 project_file_path,

94 _xmltodict={},

95 _WatchPointCount=0,

96 _SubWatershedCount=0,

97 _GreenAmptCount=0,

98 _SoilDepthCount=0,

99 _LandCoverCount=0,

100 _FlowControlCount=0,

101 _ChannelSettingsCount=0,

102 parent=None,

103 ):

104 super(GRMDialog, self).__init__(parent)

105 self.setupUi(self)

106 self.ProjectFile = project_file_path

107 self._StreamWSID = []

108 self._wsinfo = None

109 self._Flowcontrolgrid_flag = False

110

111 self._xmltodict = _xmltodict

112 self._WatchPointCount = _WatchPointCount

113 self._SubWatershedCount = _SubWatershedCount

114 self._GreenAmptCount = _GreenAmptCount

115 self._SoilDepthCount = _SoilDepthCount

116 self._LandCoverCount = _LandCoverCount

117 self._FlowControlCount = _FlowControlCount

118 self._ChannelSettingsCount = _ChannelSettingsCount

119 self._Flowcontrolgrid_flag = True

120

121 self.canvasRubberBand = []

122

123 self.qTabBar()

124 self.firstTab.currentChanged.connect(lambda: self.connectionTabBar("first"))

125 self.secondTab.currentChanged.connect(lambda: self.connectionTabBar("second"))

126

127 # 2020-01-20 박: 프로젝트 데이터 초기 셋팅

128 self.Set_ProjectDataInit()

129

130 # 2020-01-09 박: 스타일 적용

131 self.setStyleSheet(css_sheet)

132 self.groupBox_2.setStyleSheet("QGroupBox{padding-top:15px;margin-top:-15px;}")

133 self.groupBox_6.setStyleSheet("QGroupBox{padding-top:15px;margin-top:-15px;}")

134

135 # 2020-01-09 박:캔버스 툴 버튼 아이콘 셋팅

136 self.Set_Canvas_Tool_Icon()

137

138 # 2020-01-20 박:캔버스에 레이어 올리기

139 self.Set_Canvas_Layer_default()

140

141 # 시뮬레이션 탭 기능 기본값 셋팅

142 self.Set_simulation_tab_default()

143 # default 설정이지만 프로그램 흐름상 나중에 처리 해야 하는 목록

144 # Watchpoint 체크박스 선택 상태로 처리

145 self.chkWatch_Point.setChecked(True)

146 self.chkFlowContorGird.setChecked(True)

147

148 self.watchpoint()

149

150 self.click_FlowContorGird()

151

152 # WatchPoint 탭 기능 기본값 셋팅

153 # 프로젝트 파일을 읽고 테이블에 셋팅(watch point)

154 self.Set_Wathpoint_tab_default()

155

156 # Channel CS 탭 기능 기본값 셋팅

157 self.Set_ChannelCS_tab_default()

158

159 # Watershed 탭 기능 기본값 셋팅

160 # 데이터 값들이 다 들어 오지 않았음 확인 해야 함

161 self.Set_Watershed_Parameter_tab_default()

162

163 # Flow Control 탭 기능 기본값 셋팅

164 self.Set_FlowControl_tab_default()

165

166 # 2020-01-20 박: dockwidget 창 분리 비활성화

167 self.dockDisableButton()

168

169 _get_set_control.GlobalLabel(self.lblColRow)

170

171 # Cell info Flow 텍스트 박스에 값 셋팅에 사용 하기 위해 유틸에 텍스트 박스 넘김

172 _get_set_control.GlobalControl(

173 self.txtCellCount,

174 self.txtCelltype,

175 self.txtStreamValue,

176 self.txtFD,

177 self.txtFA,

178 self.txtSlope,

179 self.txtWatershedID,

180 )

181

182 # Cell info Land cover

183 _get_set_control.GlobalControl_Landcover(

184 self.txtLandGridValue,

185 self.txtLandType,

186 self.txtRoughness,

187 self.txtratio,

188 self.txtCanopyRatio,

189 self.txtInterceptionMaxWaterCanopy,

190 )

191

192 # Cell info Depth

193 _get_set_control.GlobalControl_Depth(

194 self.txtDepthValue, self.txtSoilDepthClass, self.txtSoilDepth

195 )

196

197 # Cell info Texture

198 _get_set_control.GlobalControl_texture(

199 self.txtTextureGridValue,

200 self.txtSoilTexture,

201 self.txtPorosity,

202 self.txtEffectivePorosity,

203 self.txtSuctionhead,

204 self.txtcondcutivity,

205 )

206

207 _get_set_control.set_GreenAmptCount(self._GreenAmptCount)

208 _get_set_control.set_SoilDepthCount(self._SoilDepthCount)

209 _get_set_control.set_LandCoverCount(self._LandCoverCount)

210 _get_set_control.set_xmltodict(self._xmltodict)

211

212 self.dataTimeFormat = self.chkStartingTime.isChecked()

213

214 # 2020-01-20 박: 캔버스 툴 셋팅

215 self.Set_Cavas_tool_btn()

216

217 self.btnStart_Simulation.clicked.connect(self.Click_StartSimulation)

218 self.btnSaveproject.clicked.connect(lambda: self.SaveProject(True))

219 self.btnViewResult.clicked.connect(self.Open_ViewResult)

220 self.btnClose.clicked.connect(self.Close_Form)

221

222 def Click_StartSimulation(self):

223 # 값 변경 테스트 용 WatershedFile 파일 경로를 바꿈

224 GRMCore_exe = os.path.dirname(os.path.realpath(__file__)) + "\DLL\GRM.exe"

225 self.SaveProject(False)

226

227 option = "/a " if self.chkAutoROM.isChecked() else ""

228 arg = f'"{GRMCore_exe}" {option}"{self.ProjectFile}"'

229

230 result = Execute(arg)

231

232 msg = "Simulation completed"

233 if result != 1:

234 msg = "Simulation was stopped."

235

236 MsInfo(msg)

237

238 def qTabBar(self):

239 self.firstTab = QTabBar()

240 self.secondTab = QTabBar()

241 layout = QGridLayout()

242 baseLayout = self.centralwidget.layout()

243

244 self.firstTab.addTab("")

245 self.firstTab.addTab("Simulation")

246 self.firstTab.addTab("Watch points")

247 self.firstTab.addTab("Channel cross section")

248

249 self.secondTab.addTab("")

250 self.secondTab.addTab("Flow control")

251 self.secondTab.addTab("Watershed parameters")

252 self.secondTab.addTab("Cell Info.")

253

254 self.firstTab.setExpanding(False) # 창 넓이에 맞춰 늘어나지 않음

255 self.secondTab.setExpanding(False)

256 style = "QTabBar::tab:first{ max-width: 0px; } QTabBar::tab:first:selected{ border: 0px; }"

257 self.firstTab.setStyleSheet(style)

258 self.secondTab.setStyleSheet(style)

259 self.firstTab.setDrawBase(False) # 탭 하단에 선을 표시하지 않음

260

261 # layout 세팅

262 # r, c, rspan, cspan

263 layout.addWidget(self.firstTab, 0, 0, 1, 2)

264 layout.addWidget(self.secondTab, 1, 0, 1, 2)

265 layout.addWidget(self.stackedWidget, 2, 0, 1, 2)

266 layout.setSpacing(0)

267 self.gridLayout_10.setSpacing(0)

268 self.centralwidget.setLayout(layout)

269 baseLayout.addLayout(layout, 0, 0, 2, 2)

270 baseLayout.addWidget(self.btnStart_Simulation, 2, 0)

271 baseLayout.addWidget(self.btnSaveproject, 2, 1)

272 baseLayout.addWidget(self.btnViewResult, 3, 0)

273 baseLayout.addWidget(self.btnClose, 3, 1)

274 baseLayout.addWidget(self.mapcanvas, 1, 2, 3, 2)

275

276 self.firstTab.setCurrentIndex(1)

277

278 def Set_ProjectDataInit(self):

279 # 그리드 라인 에 사용될 변수

280 # 글로벌 변수로 지정 해서 사용 하면 화면을 닫았다가 다시 켜면 값이 남아 있어서 그리드 라인이 안그려짐

281 self.grid_line = {}

282

283 # direction 그리때 사용 변수

284 # 글로벌 변수로 지정 해서 사용 하면 화면을 닫았다가 다시 켜면 값이 남아 있어서 디렉션이 안그려짐

285 self.flow_direction = {}

286

287 project_settings = self._xmltodict["GRMProject"]["ProjectSettings"]

288

289 # watershed Layer file 경로 변수

290 self.LayerPath = project_settings["DomainFile"]

291

292 # simulation Tab 변수

293 self.ComputationalTimeStep_min = project_settings["ComputationalTimeStep_min"]

294 self.MaxDegreeOfParallelism = project_settings["MaxDegreeOfParallelism"]

295 self.SimulationDuration_hr = project_settings["SimulationDuration_hr"]

296 self.OutputTimeStep_min = project_settings["OutputTimeStep_min"]

297 self.SimulateInfiltration = project_settings["SimulateInfiltration"]

298 self.SimulateSubsurfaceFlow = project_settings["SimulateSubsurfaceFlow"]

299 self.SimulateBaseFlow = project_settings["SimulateBaseFlow"]

300 self.SimulateInterception = project_settings["SimulateInterception"]

301 self.SimulateEvapotranspiration = project_settings["SimulateEvapotranspiration"]

302 self.SimulateSnowMelt = project_settings["SimulateSnowMelt"]

303 self.SimulateFlowControl = project_settings["SimulateFlowControl"]

304 self.IsFixedTimeStep = project_settings["IsFixedTimeStep"]

305 self.SimulationStartingTime = project_settings["SimulationStartingTime"]

306 self.WatershedFile = project_settings["DomainFile"]

307 self.SlopeFile = project_settings["SlopeFile"]

308 self.FlowDirectionFile = project_settings["FlowDirectionFile"]

309 self.FlowAccumFile = project_settings["FlowAccumFile"]

310 self.StreamFile = project_settings["StreamFile"]

311 self.ChannelWidthFile = project_settings["ChannelWidthFile"]

312 self.LandCoverFile = project_settings["LandCoverFile"]

313 self.SoilTextureFile = project_settings["SoilTextureFile"]

314 self.SoilDepthFile = project_settings["SoilDepthFile"]

315 self.InitialChannelFlowFile = project_settings["InitialChannelFlowFile"]

316 self.InitialSoilSaturationRatioFile = project_settings[

317 "InitialSoilSaturationRatioFile"

318 ]

319 self.MakeIMGFile = project_settings["MakeIMGFile"]

320 self.MakeASCFile = project_settings["MakeASCFile"]

321 self.MakeSoilSaturationDistFile = project_settings["MakeSoilSaturationDistFile"]

322 self.MakeRfDistFile = project_settings["MakeRfDistFile"]

323 self.MakeRFaccDistFile = project_settings["MakeRFaccDistFile"]

324 self.MakeFlowDistFile = project_settings["MakeFlowDistFile"]

325 self.PrintOption = project_settings["PrintOption"]

326 self.PrintAveValue = project_settings["PrintAveValue"]

327 self.AveValueTimeInterval_min = project_settings["AveValueTimeInterval_min"]

328 self.WriteLog = project_settings["WriteLog"]

329

330 if self.InitialChannelFlowFile is None:

331 self.InitialChannelFlowFile = ""

332 if self.InitialSoilSaturationRatioFile is None:

333 self.InitialSoilSaturationRatioFile = ""

334 if self.ChannelWidthFile is None:

335 self.ChannelWidthFile = ""

336

337 # Core DLL 연동 작업 선행 처리

338 FDType = project_settings["FlowDirectionType"]

339

340 # 2020-05-12 박: 추가 된 기능 (dll에 정보 넘겨주고 값 받기)

341 self._wsinfo = grmWSinfo(

342 FDType,

343 self.WatershedFile,

344 self.SlopeFile,

345 self.FlowDirectionFile,

346 self.FlowAccumFile,

347 self.StreamFile,

348 self.LandCoverFile,

349 self.SoilTextureFile,

350 self.SoilDepthFile,

351 self.InitialSoilSaturationRatioFile,

352 self.InitialChannelFlowFile,

353 self.ChannelWidthFile,

354 )

355 _get_set_control.set_wsinfo(self._wsinfo)

356 self.GridCellSize = self._wsinfo.cellSize

357

358 # 임시 리스트를 만들어서 데이터를 받고 받은 데이터를 _StreamWSID 에 셋팅

359 try:

360 self._StreamWSID = []

361 WSIDs = []

362 WSIDs = self._wsinfo.mostDownStreamWSIDs

363 for i in range(self._wsinfo.mostDownStreamWSCount):

364 if WSIDs[i] is not None:

365 self._StreamWSID.append(str(WSIDs[i]))

366 except Exception as e:

367 MsInfo(e)

368

369 # 2020-05-13 박: 지금 함수가 확인이 안되서 임시로 주석 처리

370 self.Set_Wathpoint_default_value()

371

372 # ChannelWidth tab 변수

373 self.WSID = []

374 self.CrossSectionType = []

375 self.SingleCSChannelWidthType = []

376 self.ChannelWidthEQc = []

377 self.ChannelWidthEQd = []

378 self.ChannelWidthEQe = []

379 self.ChannelWidthMostDownStream = []

380 self.LowerRegionHeight = []

381 self.LowerRegionBaseWidth = []

382 self.UpperRegionBaseWidth = []

383 self.CompoundCSChannelWidthLimit = []

384 self.BankSideSlopeRight = []

385 self.BankSideSlopeLeft = []

386

387 channelDic = {

388 "CrossSectionType": ["CSSingle", self.CrossSectionType],

389 "SingleCSChannelWidthType": ["CWGeneration", self.SingleCSChannelWidthType],

390 "ChannelWidthEQc": ["1.698", self.ChannelWidthEQc],

391 "ChannelWidthEQd": ["0.318", self.ChannelWidthEQd],

392 "ChannelWidthEQe": ["0.5", self.ChannelWidthEQe],

393 "ChannelWidthMostDownStream": [

394 str(self.GridCellSize),

395 self.ChannelWidthMostDownStream,

396 ],

397 "LowerRegionHeight": ["0", self.LowerRegionHeight],

398 "LowerRegionBaseWidth": ["0", self.LowerRegionBaseWidth],

399 "UpperRegionBaseWidth": ["0", self.UpperRegionBaseWidth],

400 "CompoundCSChannelWidthLimit": ["0", self.CompoundCSChannelWidthLimit],

401 "BankSideSlopeRight": ["1.5", self.BankSideSlopeRight],

402 "BankSideSlopeLeft": ["1.5", self.BankSideSlopeLeft],

403 }

404

405 if self._ChannelSettingsCount == 0:

406 self.lisw_WSID.clear()

407 # 2020-05-25 박: New 프로젝트 시행시에 값을 받아 오는 부분이 없어서 추가

408 self._ChannelSettingsCount = len(self._StreamWSID)

409 if self._ChannelSettingsCount > 0:

410 DictoXml = unparse(self._xmltodict)

411 ET.register_namespace("", "http://tempuri.org/GRMProject.xsd")

412 xmltree = ET.ElementTree(ET.fromstring(DictoXml))

413 root = xmltree.getroot()

414 for i in range(len(self._StreamWSID)):

415 child = ET.Element("ChannelSettings")

416 root.append(child)

417

418 ChannelWSID = ET.Element("WSID")

419 ChannelWSID.text = str(self._StreamWSID[i])

420 child.append(ChannelWSID)

421

422 self.WSID.append(str(self._StreamWSID[i]))

423 item1 = QListWidgetItem(str(self._StreamWSID[i]))

424 self.lisw_WSID.addItem(item1)

425

426 for k in channelDic.keys():

427 ele = ET.Element(k)

428 ele.text = channelDic[k][0]

429 child.append(ele)

430 channelDic[k][1].append(channelDic[k][0])

431

432 xmltree_string = ET.tostring(xmltree.getroot())

433 docs = dict(parse(xmltree_string))

434 self._xmltodict.clear()

435 self._xmltodict.update(docs)

436

437 elif self._ChannelSettingsCount == 1:

438 self.lisw_WSID.clear()

439 result = self._xmltodict["GRMProject"]["ChannelSettings"]["WSID"]

440 self.WSID.append(self._xmltodict["GRMProject"]["ChannelSettings"]["WSID"])

441 item1 = QListWidgetItem(str(self.WSID[0]))

442 self.lisw_WSID.addItem(item1)

443

444 for k in channelDic:

445 value = self._xmltodict["GRMProject"]["ChannelSettings"][k]

446 if k == "ChannelWidthMostDownStream" and not str(value).strip():

447 value = str(int(self.GridCellSize))

448 channelDic[k][1].append(value)

449

450 self._ChannelSettingsCount = 1

451

452 elif self._ChannelSettingsCount > 1:

453 self.lisw_WSID.clear()

454 i = 0

455 for flowitem in self._xmltodict["GRMProject"]["ChannelSettings"]:

456 self.WSID.append(str(flowitem["WSID"]))

457 item1 = QListWidgetItem(str(self.WSID[i]))

458 self.lisw_WSID.addItem(item1)

459 self.CrossSectionType.append(str(flowitem["CrossSectionType"]))

460 self.SingleCSChannelWidthType.append(

461 str(flowitem["SingleCSChannelWidthType"])

462 )

463 self.ChannelWidthEQc.append(str(flowitem["ChannelWidthEQc"]))

464 self.ChannelWidthEQd.append(str(flowitem["ChannelWidthEQd"]))

465 self.ChannelWidthEQe.append(str(flowitem["ChannelWidthEQe"]))

466

467 DSValue = str(flowitem["ChannelWidthMostDownStream"])

468 if str(DSValue).strip():

469 self.ChannelWidthMostDownStream.append(DSValue)

470 else:

471 self.ChannelWidthMostDownStream.append(str(int(self.GridCellSize)))

472

473 self.LowerRegionHeight.append(str(flowitem["LowerRegionHeight"]))

474 self.LowerRegionBaseWidth.append(str(flowitem["LowerRegionBaseWidth"]))

475 self.UpperRegionBaseWidth.append(str(flowitem["UpperRegionBaseWidth"]))

476 self.CompoundCSChannelWidthLimit.append(

477 str(flowitem["CompoundCSChannelWidthLimit"])

478 )

479 self.BankSideSlopeRight.append(str(flowitem["BankSideSlopeRight"]))

480 self.BankSideSlopeLeft.append(str(flowitem["BankSideSlopeLeft"]))

481 i = i + 1

482 self._ChannelSettingsCount = i

483

484 self.flowEle = [

485 "Name",

486 "ColX",

487 "RowY",

488 "DT_min",

489 "ControlType",

490 "FlowDataFile",

491 "IniStorage",

492 "MaxStorage",

493 "NormalHighStorage",

494 "RestrictedStorage",

495 "RestrictedPeriod_Start",

496 "RestrictedPeriod_End",

497 "ROType",

498 "AutoROMmaxOutflow_CMS",

499 "ROConstQ",

500 "ROConstQDuration",

501 ]

502

503 def SetMostDownStream(self, id):

504 try:

505 # 만약에 Cell size 값이 없으면 레이어에서 값을 받음

506 if self.GridCellSize is None:

507 self.GridCellSize = str(self._xsize) if self._xsize else "0"

508 Allsize = self.GridCellSize

509

510 IniSaturation = "0.9"

511 MinSlopeOF = "0.0001"

512 MinSlopeChBed = "0.0001"

513 intAll = float(Allsize)

514 # if intAll > 0:

515 # MinChBaseWidth = intAll / 10

516 MinChBaseWidth = intAll / 10 if intAll > 0 else 0

517 IniFlow = "0"

518 ChRoughness = "0.045"

519 DryStreamOrder = "0"

520 CalCoefLCRoughness = "1"

521 CalCoefSoilDepth = "1"

522 CalCoefPorosity = "1"

523 CalCoefWFSuctionHead = "1"

524 CalCoefHydraulicK = "1"

525 UnsturatedType = 1

526 CoefUnsatruatedk = "0.2"

527 interceptMethod = 1

528 potentialETMethod = 2

529 etCoeff = "1"

530 snowMeltMethod = 1

531 tempSnowRain = "0"

532 smeltingTemp = "1"

533 snowCovRatio = "1"

534 smeltCoef = "1"

535 self._wsinfo.setOneSWSParsAndUpdateAllSWSUsingNetwork(

536 int(id), # int wsid,

537 float(IniSaturation), # double iniSat,

538 float(MinSlopeOF), # double minSlopeLandSurface,

539 int(UnsturatedType), # int unSKType,

540 float(CoefUnsatruatedk), # double coefUnsK,

541 float(MinSlopeChBed), # double minSlopeChannel,

542 float(MinChBaseWidth), # double minChannelBaseWidth,

543 float(ChRoughness), # double roughnessChannel,

544 int(DryStreamOrder), # int dryStreamOrder,

545 float(CalCoefLCRoughness), # double ccLCRoughness,

546 float(CalCoefPorosity), # double ccPorosity,

547 float(CalCoefWFSuctionHead), # double ccWFSuctionHead,

548 float(CalCoefHydraulicK), # double ccSoilHydraulicCond,

549 float(CalCoefSoilDepth), # double ccSoilDepth,

550 int(interceptMethod),

551 int(potentialETMethod),

552 float(etCoeff),

553 int(snowMeltMethod),

554 float(tempSnowRain),

555 float(smeltingTemp),

556 float(snowCovRatio),

557 float(smeltCoef),

558 0,

559 ) # double iniFlow = 0)

560 except Exception as e:

561 MsError(e)

562

563 def dockDisableButton(self):

564 dockList = self.stackedWidget.findChildren(QDockWidget)

565 for dock in dockList:

566 dock.setFeatures(QDockWidget.NoDockWidgetFeatures)

567

568 def connectionTabBar(self, type):

569 f = self.firstTab.currentIndex()

570 s = self.secondTab.currentIndex()

571 index = 0

572

573 if type == "second" and s > 0:

574 self.firstTab.setCurrentIndex(0)

575 self.secondTab.setCurrentIndex(s)

576 index = s + (self.firstTab.count() - 2)

577 elif type == "first" and f > 0:

578 self.secondTab.setCurrentIndex(0)

579 self.firstTab.setCurrentIndex(f)

580 index = f - 1

581

582 self.stackedWidget.setCurrentIndex(index)

583

584 # canvas 버튼 아이콘 이미지 설정

585 def Set_Canvas_Tool_Icon(self):

586 root = os.path.dirname(os.path.abspath(__file__)) + "\image"

587 ZoomExtent = root + "\ZoomExtent.png"

588 Zoomin = root + "\ZoomIn.png"

589 ZoomOut = root + "\ZoomOut.png"

590 Pan = root + "\Pan.png"

591 Zoomnext = root + "\Zoomnext.png"

592 ZoomPrevious = root + "\ZoomPrevious.png"

593 SelectGrid = root + "\SelectGrid.png"

594 MoveTo = root + "\MoveTo.png"

595

596 self.btnZoomExtent.setIcon(QtGui.QIcon(ZoomExtent))

597 self.btnZoomExtent.setIconSize(QSize(200, 200))

598

599 self.btnZoomIn.setIcon(QtGui.QIcon(Zoomin))

600 self.btnZoomOut.setIcon(QtGui.QIcon(ZoomOut))

601 self.btnPan.setIcon(QtGui.QIcon(Pan))

602 self.btnZoomnext.setIcon(QtGui.QIcon(Zoomnext))

603 self.btnZoomprevious.setIcon(QtGui.QIcon(ZoomPrevious))

604 self.btnSelectgrid.setIcon(QtGui.QIcon(SelectGrid))

605 self.btnMoveto.setIcon(QtGui.QIcon(MoveTo))

606

607 # 캔버스 툴 기능 연동

608 def Set_Cavas_tool_btn(self):

609 self.tool = CanvasTool(self.mapcanvas)

610

611 # ZoomExtent

612 self.btnZoomExtent.clicked.connect(self.tool.ZoomtoExtent)

613

614 # Zoom Next

615 self.btnZoomnext.clicked.connect(self.tool.ZoomtoNextExtent)

616

617 # Zoom Previous

618 self.btnZoomprevious.clicked.connect(self.tool.ZoomtoPrevious)

619

620 # Zoom In

621 self.btnZoomIn.clicked.connect(self.tool.canvas_zoomIn)

622

623 # Zoom Out

624 self.btnZoomOut.clicked.connect(self.tool.canvas_zoomOut)

625

626 # Pan

627 self.btnPan.clicked.connect(self.tool.canvas_pan)

628

629 # Moveto

630 self.btnMoveto.clicked.connect(self.aboutApp)

631

632 # # Selectgrid

633 self.btnSelectgrid.clicked.connect(self.identify)

634

635 # Watch_Point 기본 설정은 체크

636 self.chkWatch_Point.stateChanged.connect(self.watchpoint)

637

638 # chkFC

639 self.chkFlowContorGird.stateChanged.connect(self.click_FlowContorGird)

640

641 # 체크 박스 눌렀을때 캔버스에 그리드 라인 추가 함수

642 self.show_grid_line.clicked.connect(self.show_hide_grid_line)

643

644 # 캔버스에 Flow direction

645 self.show_flow_direction.clicked.connect(self.show_hide_flow_direction)

646

647 # 캔버스에 레이어 올리기

648 def Set_Canvas_Layer_default(self):

649 # canvase 레이어 올리기

650 if self.LayerPath is not None:

651 convert_shape_path = self.LayerPath.upper().replace(

652 ".ASC", "_temp_convert_file.SHP"

653 )

654 flag_WSID_Shape = AscToShape(self.LayerPath, convert_shape_path)

655 Wsid_shape_style_path_ori = (

656 os.path.dirname(os.path.realpath(__file__)) + "\DLL\Label_Style.qml"

657 )

658

659 # self.layer = QgsRasterLayer(self.LayerPath, "FA", "gdal")

660 self.layer = QgsRasterLayer(self.LayerPath, "WSFAlayerload", "gdal")

661 self.Wsid_label_shape = QgsVectorLayer(convert_shape_path, "WSID_label")

662 self.Wsid_label_shape.loadNamedStyle(Wsid_shape_style_path_ori)

663 # 캔버스의 기본 정보를 Global에 대입 다른 클래스에서 사용

664 _layer = self.layer

665 self.Set_Global_CanvaseValue()

666

667 """#2017.11..1 원 :

668 문제1. 상기 ASC가 투영 좌표계 레이어인데. 경위도로 오인 지정되어 있었슴. 이는 PRJ 파일 만듧면 해결됨.

669 문제2 .그리고 canvas 는 직접 setDestinationCrs 해야 좌표계가 지정됨. https://issues.qgis.org/issues/9772 """

670

671 self.mapcanvas.setDestinationCrs(self.layer.crs())

672 QgsProject.instance().addMapLayer(self.layer, False)

673 self.mapcanvas.setExtent(self.layer.extent())

674 self.mapcanvas.setLayers([self.layer, self.Wsid_label_shape])

675

676 # 레이어 기본 값을 Global 로 지정해서 정의

677 def Set_Global_CanvaseValue(self):

678 self._width = self.layer.width()

679 self._height = self.layer.height()

680 self._xsize = self.layer.rasterUnitsPerPixelX()

681 self._ysize = self.layer.rasterUnitsPerPixelY()

682 self._extent = self.layer.extent()

683 self._ymax = self._extent.yMaximum()

684 self._ymin = self._extent.yMinimum()

685 self._xmax = self._extent.xMaximum()

686 self._xmin = self._extent.xMinimum()

687

688 # def 연동 함수

689 def Open_ViewResult(self):

690 self.disCharge = self.ProjectFile

691 disCharge_path = os.path.splitext(os.path.basename(self.disCharge))[0]

692 self.disCharge = self.disCharge.replace(

693 disCharge_path + ".gmp", disCharge_path + "_Discharge.out"

694 )

695 Opewn_ViewFile(self.disCharge)

696

697 # ----------------- 2017-10-24_오전 박 simulation 탭 텍스트 박스 셋팅 -----------------------------

698 def Set_simulation_tab_default(self):

699 # 프린트 옵션 콤보 박스 셋팅

700 combolist = (

701 "All",

702 "DischargeFile",

703 "DischargeAndFcFile",

704 "AverageFile",

705 "DischargeFileQ",

706 "AverageFileQ",

707 "AllQ",

708 )

709 self.cmbPrint.addItems(combolist)

710 index = self.cmbPrint.findText(self.PrintOption, Qt.MatchFixedString)

711 if index >= 0:

712 self.cmbPrint.setCurrentIndex(index)

713

714 self.cmbPrint.currentIndexChanged.connect(self.printcombo)

715 self.spTimeStep_min_2.valueChanged.connect(self.SPvaluechange)

716

717 self.chkParallel.stateChanged.connect(self.Check_Parallel)

718 self.Check_Parallel()

719

720 self.chkPrintAveValue.stateChanged.connect(self.Check_Ave_Value_Time)

721 self.Check_Ave_Value_Time()

722

723 self.chkInterception.stateChanged.connect(

724 lambda state: self.check_simulate_option(

725 state,

726 [self.groupSimulateInterception, self.txtInterceptionMaxWaterCanopy],

727 )

728 )

729 self.check_simulate_option(

730 self.chkInterception.isChecked(),

731 [self.groupSimulateInterception, self.txtInterceptionMaxWaterCanopy],

732 )

733

734 self.chkEvapotranspiration.stateChanged.connect(

735 lambda state: self.check_simulate_option(

736 state, [self.groupSimulateEvapotranspiration]

737 )

738 )

739 self.check_simulate_option(

740 self.chkEvapotranspiration.isChecked(),

741 [self.groupSimulateEvapotranspiration],

742 )

743

744 self.chkSnowMelt.stateChanged.connect(

745 lambda state: self.check_simulate_option(

746 state, [self.groupSimulateSnowMelt, self.txtCanopyRatio]

747 )

748 )

749 self.check_simulate_option(

750 self.chkSnowMelt.isChecked(),

751 [self.groupSimulateSnowMelt, self.txtCanopyRatio],

752 )

753

754 self.chkFlowControl.toggled.connect(self.Check_Flow)

755 self.Check_Flow(False)

756

757 self.chkmakeimage.setChecked(False)

758 if self.MakeIMGFile.upper() == "TRUE":

759 self.chkmakeimage.setChecked(True)

760

761 self.chkmakeASC.setChecked(False)

762 if self.MakeASCFile.upper() == "TRUE":

763 self.chkmakeASC.setChecked(True)

764

765 self.chksoiSaturation.setChecked(False)

766 if self.MakeSoilSaturationDistFile.upper() == "TRUE":

767 self.chksoiSaturation.setChecked(True)

768

769 self.chkrfDistFile.setChecked(False)

770 if self.MakeRfDistFile.upper() == "TRUE":

771 self.chkrfDistFile.setChecked(True)

772

773 self.chkrfaacDistfile.setChecked(False)

774 if self.MakeRFaccDistFile.upper() == "TRUE":

775 self.chkrfaacDistfile.setChecked(True)

776

777 self.chkdischarge.setChecked(False)

778 if self.MakeFlowDistFile.upper() == "TRUE":

779 self.chkdischarge.setChecked(True)

780

781 self.chkPrintAveValue.setChecked(False)

782 if self.PrintAveValue.upper() == "TRUE":

783 self.chkPrintAveValue.setChecked(True)

784

785 self.chklog.setChecked(False)

786 if self.WriteLog.upper() == "TRUE":

787 self.chklog.setChecked(True)

788

789 if self.SimulationStartingTime == "0":

790 now = QDateTime.currentDateTime()

791 self.dateTimeEdit.setDateTime(now)

792 self.chkStartingTime.setChecked(False)

793 self.dateTimeEdit.setEnabled(False)

794 self.dataTimeFormat = False

795 else:

796 self.chkStartingTime.setChecked(True)

797 self.dateTimeEdit.setEnabled(True)

798 dateTime = QDateTime.fromString(

799 self.SimulationStartingTime, "yyyy-MM-dd hh:mm"

800 )

801 self.dateTimeEdit.setDateTime(dateTime)

802 self.dataTimeFormat = True

803

804 self.chkParallel.setChecked(False)

805 if int(self.MaxDegreeOfParallelism) > 0:

806 self.chkParallel.setChecked(True)

807

808 if self.ComputationalTimeStep_min is not None:

809 intvalue = int(self.ComputationalTimeStep_min)

810 self.spTimeStep_min.setValue(intvalue)

811 else:

812 if self._xsize <= 200:

813 value = 3

814 elif self._xsize > 200:

815 value = 5

816 self.spTimeStep_min.setValue(value)

817

818 if self.MaxDegreeOfParallelism is not None:

819 intvalue = int(self.MaxDegreeOfParallelism)

820 self.spTimeStep_min_2.setValue(intvalue)

821

822 if self.AveValueTimeInterval_min:

823 self.spbAveValueTimeInterval_min.setValue(

824 int(self.AveValueTimeInterval_min)

825 )

826

827 if self.OutputTimeStep_min is not None and self.OutputTimeStep_min != "":

828 self.txtOutput_time_step.setText(str(self.OutputTimeStep_min))

829

830 self.txtSimulation_duration.setText("")

831 if self.SimulationDuration_hr is not None:

832 self.txtSimulation_duration.setText(self.SimulationDuration_hr)

833

834 if self.OutputTimeStep_min is not None:

835 self.txtOutput_time_step.setText(self.OutputTimeStep_min)

836

837 # 체크 박스 셋팅 (프로젝트 파일에서 체크 값 받아서 셋팅)

838 self.chkInfiltration.setChecked(True)

839 if self.SimulateInfiltration and self.SimulateInfiltration.upper() != "TRUE":

840 self.chkInfiltration.setChecked(False)

841

842 self.chkSubsurfaceFlow.setChecked(True)

843 if (

844 self.SimulateSubsurfaceFlow

845 and self.SimulateSubsurfaceFlow.upper() != "TRUE"

846 ):

847 self.chkSubsurfaceFlow.setChecked(False)

848

849 self.chkBaseFlow.setChecked(True)

850 if self.SimulateBaseFlow and self.SimulateBaseFlow.upper() != "TRUE":

851 self.chkBaseFlow.setChecked(False)

852

853 self.chkInterception.setChecked(True)

854 if self.SimulateInterception and self.SimulateInterception.upper() != "TRUE":

855 self.chkInterception.setChecked(False)

856

857 self.chkEvapotranspiration.setChecked(True)

858 if (

859 self.SimulateEvapotranspiration

860 and self.SimulateEvapotranspiration.upper() != "TRUE"

861 ):

862 self.chkEvapotranspiration.setChecked(False)

863

864 self.chkSnowMelt.setChecked(True)

865 if self.SimulateSnowMelt and self.SimulateSnowMelt.upper() != "TRUE":

866 self.chkSnowMelt.setChecked(False)

867

868 if self.SimulateFlowControl is not None:

869 if self.SimulateFlowControl.upper() == "TRUE":

870 self.chkFlowControl.setChecked(True)

871

872 self.chkStartingTime.stateChanged.connect(self.Check_StartingTime)

873

874 self.chkmakeimage.stateChanged.connect(self.MakeASC_IMAGE)

875 self.chkmakeASC.stateChanged.connect(self.MakeASC_IMAGE)

876 self.MakeASC_IMAGE()

877

878 if self.IsFixedTimeStep.upper() == "TRUE":

879 self.chkfixeTimeStep.setChecked(True)

880

881 def printcombo(self):

882 if self.cmbPrint.currentText() == "All":

883 self.chkmakeimage.setEnabled(True)

884 self.chkmakeASC.setEnabled(True)

885 self.MakeASC_IMAGE()

886 else:

887 self.chkmakeimage.setEnabled(False)

888 self.chkmakeASC.setEnabled(False)

889 self.chksoiSaturation.setEnabled(False)

890 self.chkrfDistFile.setEnabled(False)

891 self.chkrfaacDistfile.setEnabled(False)

892 self.chkdischarge.setEnabled(False)

893

894 def check_simulate_option(self, state: bool, q_widget_list: List[QWidget]):

895 for q_widget in q_widget_list:

896 q_widget.setEnabled(state)

897

898 def SPvaluechange(self):

899 value = self.spTimeStep_min_2.text()

900 if value == "0":

901 MsError(" Input 0 can not be input. ")

902

903 def Check_Parallel(self):

904 flag = self.chkParallel.isChecked()

905 self.spTimeStep_min_2.setEnabled(flag)

906

907 def Check_Ave_Value_Time(self):

908 flag = self.chkPrintAveValue.isChecked()

909 self.label_19.setEnabled(flag)

910 self.spbAveValueTimeInterval_min.setEnabled(flag)

911

912 def Check_Flow(self, flag):

913 self.chkAutoROM.setEnabled(flag)

914 self.chkAutoROM.setChecked(False)

915

916 def Check_StartingTime(self):

917 flag = self.chkStartingTime.isChecked()

918 self.dateTimeEdit.setEnabled(flag)

919 self.dataTimeFormat = flag

920

921 def MakeASC_IMAGE(self):

922 flag = self.chkmakeimage.isChecked() or self.chkmakeASC.isChecked()

923 self.chksoiSaturation.setEnabled(flag)

924 self.chkrfDistFile.setEnabled(flag)

925 self.chkrfaacDistfile.setEnabled(flag)

926 self.chkdischarge.setEnabled(flag)

927

928 # ======================WatchPoint Tab Table Setting and btn event =========================

929 def Set_Wathpoint_tab_default(self):

930 try:

931 # 테이블 상에 선택된 열을 위로 올림

932 self.btnMoveup.clicked.connect(self.MoveUp)

933

934 # 테이블 상에 선택된 열을 아래로 내림

935 self.btnMovedown.clicked.connect(self.MoveDown)

936

937 # 테이블 상에 선택된 열을 삭제

938 self.btnRemove.clicked.connect(self.ReMove)

939

940 # 테이블 셀값을 변경 불가능 하게 설정

941 self.tbList.setEditTriggers(QAbstractItemView.NoEditTriggers)

942

943 # color picker 이벤트

944 self.btnColorPicker.clicked.connect(

945 lambda: self.color_picker(self.btnColorPicker)

946 )

947 self.btnColorPicker_3.clicked.connect(

948 lambda: self.color_picker(self.btnColorPicker_3)

949 )

950

951 # 2017/11/22-------------------

952 # 테이블 셀 값 선택한 값의 위치로 view 이동

953 # self.btnGrid.clicked.connect(self.GoToGrid)

954 self.btnGrid.clicked.connect(lambda: self.btnGotoGrid(self.tbList))

955

956 # 테이블 셀값을 변경 가능하게 설정 ----> 색상값 변경임 잘못된 구현 변경 해야함

957 self.btnEdit.clicked.connect(self.Edit)

958

959 self.btnAddSelectCell.clicked.connect(self.Add_Selected_Cell)

960

961 # 최하류 셀 넣기

962 self.btnAddMostDown.clicked.connect(self.Add_MostDown_Stream)

963

964 # 각각의 컬럼에 갑셋팅(xml 상에 'ObTSId', 'ObTSLegend', 'ObTSMissingCount' 항목의 값이 없음

965 self.Watchpoint_TableCreate(len(self.Name))

966 self.Watchpoint_Table_Insert()

967 except Exception as wa:

968 MsError(wa)

969

970 def MoveUp(self):

971 row = self.tbList.currentRow()

972 column = self.tbList.currentColumn()

973 if row > 0:

974 self.tbList.insertRow(row - 1)

975 for i in range(self.tbList.columnCount()):

976 self.tbList.setItem(row - 1, i, self.tbList.takeItem(row + 1, i))

977 self.tbList.setCurrentCell(row - 1, column)

978 self.tbList.removeRow(row + 1)

979

980 def MoveDown(self):

981 row = self.tbList.currentRow()

982 column = self.tbList.currentColumn()

983 if row >= 0:

984 if row < self.tbList.rowCount() - 1:

985 self.tbList.insertRow(row + 2)

986 for i in range(self.tbList.columnCount()):

987 self.tbList.setItem(row + 2, i, self.tbList.takeItem(row, i))

988 self.tbList.setCurrentCell(row + 2, column)

989 self.tbList.removeRow(row)

990

991 def check_add_watchpoint(self, x, y, name):

992 rowCount = self.tbList.rowCount()

993 self.RetBool = True

994 for row in range(0, rowCount):

995 Names = self.tbList.item(row, 0).text()

996 X = self.tbList.item(row, 1).text()

997 Y = self.tbList.item(row, 2).text()

998 if (X == str(x) and Y == str(y)) or name == Names:

999 self.RetBool = False

1000 return self.RetBool

1001

1002 def ReMove(self):

1003 row = self.tbList.currentIndex().row()

1004 mess = "Are you sure you want to delete the selected items?"

1005 result = QMessageBox.question(

1006 None, "Watershed Setup", mess, QMessageBox.Yes, QMessageBox.No

1007 )

1008 if result == QMessageBox.Yes:

1009 self.tbList.removeRow(row)

1010

1011 self.post_grid_remove2()

1012 if self.chkFlowContorGird.isChecked():

1013 self.FlowContorGird_paint()

1014 if self.chkWatch_Point.isChecked():

1015 if self.tbList.rowCount() != 0:

1016 self.watchpoint_paint()

1017

1018 def btnGotoGrid(self, tbl):

1019 row = tbl.currentRow()

1020 if row > -1:

1021 ColX = int(tbl.item(row, 1).text())

1022 RowY = int(tbl.item(row, 2).text())

1023

1024 self.post_grid_remove()

1025 self.mapcanvas.refresh()

1026 self.scale_changed_mapcanvas()

1027 self.row_cols_grid(ColX, RowY, None)

1028 self.tool.scale_changed_disconnect()

1029 else:

1030 MsInfo("Check! select row")

1031

1032 def CheckTableValue(self, x, y):

1033 rowCount = self.tbList.rowCount()

1034 self.RetBool = True

1035 for row in range(0, rowCount):

1036 X = self.tbList.item(row, 1).text()

1037 Y = self.tbList.item(row, 2).text()

1038 if X == str(x) and Y == str(y):

1039 self.RetBool = False

1040 return self.RetBool

1041

1042 # 에디트 클릭시에 선택된 Row 의 name 변경

1043 def Edit(self):

1044 # 현재 선택된 Row

1045 row = self.tbList.currentRow()

1046

1047 if row > -1:

1048 cell = self.tbList.item(row, 0).text()

1049 # 다이얼 로그 출력하여 사용자가 셀값 제정의

1050 # text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter name:',QLineEdit.Normal,cell)

1051 text, ok = QInputDialog.getText(

1052 self, "Input Dialog", "Enter name:", QLineEdit.Normal, cell

1053 )

1054 if ok:

1055 item = QTableWidgetItem(str(text)) # create a new Item

1056 self.tbList.setItem(row, 0, item)

1057 else:

1058 MsInfo("check! select Row")

1059

1060 # 2017 -12-15 박: 추가 버튼 눌렀을때 Watchpoint table 에 데이터 추가 하기

1061 def Add_Selected_Cell(self):

1062 try:

1063 if self.tool._FXCOL != 0 and self.tool._FYROW != 0:

1064 rowCount = self.tbList.rowCount()

1065 if rowCount > 0:

1066 text, ok = QInputDialog.getText(

1067 self, "Input Dialog", "Enter name:", QLineEdit.Normal, ""

1068 )

1069 if text.strip() != "":

1070 if self.check_add_watchpoint(

1071 self.tool._YROW, self.tool._XCOL, text

1072 ):

1073 self.tbList.insertRow(rowCount)

1074 self.tbList.setItem(rowCount, 0, QTableWidgetItem(text))

1075 self.tbList.setItem(

1076 rowCount, 1, QTableWidgetItem(str(self.tool._FYROW))

1077 )

1078 self.tbList.setItem(

1079 rowCount, 2, QTableWidgetItem(str(self.tool._FXCOL))

1080 )

1081 self.ColX.append(self.tool._FXCOL)

1082 self.RowY.append(self.tool._FYROW)

1083 if self.chkWatch_Point.isChecked():

1084 self.row_cols_grid(

1085 self.tool._FYROW, self.tool._FXCOL, "watchpoint"

1086 )

1087 else:

1088 MsInfo(" Name or watchpoint is required. ")

1089 else:

1090 MsInfo(" Name is required. ")

1091 else:

1092 text, ok = QInputDialog.getText(

1093 self, "Input Dialog", "Enter name:", QLineEdit.Normal, ""

1094 )

1095 if text.strip() != "":

1096 self.tbList.insertRow(0)

1097 self.tbList.setItem(rowCount, 0, QTableWidgetItem(text))

1098 self.tbList.setItem(

1099 0, 1, QTableWidgetItem(str(self.tool._FYROW))

1100 )

1101 self.tbList.setItem(

1102 0, 2, QTableWidgetItem(str(self.tool._FXCOL))

1103 )

1104 self.ColX.append(self.tool._FXCOL)

1105 self.RowY.append(self.tool._FYROW)

1106 if self.chkWatch_Point.isChecked():

1107 self.row_cols_grid(

1108 self.tool._FYROW, self.tool._FXCOL, "watchpoint"

1109 )

1110 else:

1111 MsInfo(" Name is required. ")

1112 except Exception as e:

1113 MsError(e)

1114

1115 def Add_MostDown_Stream(self):

1116 if len(self._StreamWSID) == 1:

1117 x = self._wsinfo.facMaxCellxCol

1118 y = self._wsinfo.facMaxCellyRow

1119

1120 rowCount = self.tbList.rowCount()

1121 if self.CheckTableValue(x, y):

1122 self.tbList.insertRow(rowCount)

1123 text, ok = QInputDialog.getText(

1124 self, "Input Dialog", "Enter name:", QLineEdit.Normal, ""

1125 )

1126 self.tbList.setItem(rowCount, 0, QTableWidgetItem(text))

1127 self.tbList.setItem(rowCount, 1, QTableWidgetItem(str(x)))

1128 self.tbList.setItem(rowCount, 2, QTableWidgetItem(str(y)))

1129 self.row_cols_grid(x, y, "watchpoint")

1130 for id in range(len(self._StreamWSID)):

1131 self.SetMostDownStream(self._StreamWSID[id])

1132 else:

1133 MsInfo(" The most downstream value already exists. ")

1134 else:

1135 # 최박사님이 문구 주실거임

1136 # 2018-07-24 박: 최하류 유역이 1개일때만 자동 추가 2개 이상일때는 추가하지 않고 문구로 대체함

1137 MsInfo(

1138 " The number of most down stream cells are more than 1."

1139 + "\r\n"

1140 + " Add most down stream cells manually. "

1141 )

1142

1143 def Watchpoint_TableCreate(self, Row):

1144 self.tbList.setColumnCount(3)

1145 self.tbList.setRowCount(Row)

1146 self.tbList.setHorizontalHeaderLabels(["Name", "ColX", "RowY"])

1147 # 테이블 넓이 에 맞게 Name 항목 넓이 지정

1148 self.tbList.setColumnWidth(0, 176)

1149

1150 # watchpoint datault 값을 변수에 저장

1151 def Set_Wathpoint_default_value(self):

1152 self.Name = []

1153 self.ColX = []

1154 self.RowY = []

1155 if self._WatchPointCount == 0:

1156 # Dll 에서 X,Y 값을 넣었을때 받는 값

1157

1158 # 2020-05-19 박: 기존에서 함수명 변경됨

1159 x = self._wsinfo.facMaxCellxCol

1160 y = self._wsinfo.facMaxCellyRow

1161

1162 # 2018-07-24 박: 처음 로드시 최하류 셀이 1개이면 추가함 그이상이면 추가하지 안음

1163 if self._wsinfo.mostDownStreamWSCount == 1:

1164 names = "MD"

1165 self.Name.append(names)

1166 self.ColX.append(str(x))

1167 self.RowY.append(str(y))

1168 # New Project 일때 프로그램 최하류 정보를 Dll에 넣음

1169

1170 for id in range(self._wsinfo.mostDownStreamWSCount):

1171 self.SetMostDownStream(self._StreamWSID[id])

1172

1173 elif self._WatchPointCount > 1:

1174 for flowitem in self._xmltodict["GRMProject"]["WatchPoints"]:

1175 self.ColX.append(str(flowitem["ColX"]))

1176 self.RowY.append(str(flowitem["RowY"]))

1177 self.Name.append(flowitem["Name"])

1178

1179 elif self._WatchPointCount == 1:

1180 self.ColX.append(str(self._xmltodict["GRMProject"]["WatchPoints"]["ColX"]))

1181 self.RowY.append(str(self._xmltodict["GRMProject"]["WatchPoints"]["RowY"]))

1182 self.Name.append(str(self._xmltodict["GRMProject"]["WatchPoints"]["Name"]))

1183

1184 def Watchpoint_Table_Insert(self):

1185 if len(self.Name) > 0:

1186 for i in range(0, len(self.Name)):

1187 # 사용자에게 CVID 표출 안함

1188 self.tbList.setItem(i, 0, QTableWidgetItem(self.Name[i]))

1189 self.tbList.setItem(i, 1, QTableWidgetItem(self.ColX[i]))

1190 self.tbList.setItem(i, 2, QTableWidgetItem(self.RowY[i]))

1191

1192 # 색상 변경 Picker -- 2017/09/07 조가 주석달음

1193 def color_picker(self, bttom): # , type

1194 color = QColorDialog.getColor()

1195 bttom.setStyleSheet("background-color:" + str(color.name()) + ";")

1196

1197 self.post_grid_remove2()

1198 self.watchpoint()

1199 self.click_FlowContorGird()

1200

1201 # watchpoint RubberBand 제거

1202 def post_grid_remove2(self):

1203 for v in self.canvasRubberBand:

1204 # for v in self.mapcanvas.scene().items():

1205 if issubclass(type(v), QgsRubberBand) == True:

1206 self.mapcanvas.scene().removeItem(v)

1207

1208 def watchpoint(self):

1209 if self.chkWatch_Point.isChecked():

1210 self.watchpoint_paint()

1211 else:

1212 # 지우기

1213 self.post_grid_remove2()

1214 if self.chkFlowContorGird.isChecked():

1215 self.FlowContorGird_paint()

1216

1217 def watchpoint_paint(self):

1218 try:

1219 if len(self.ColX) > 0 and len(self.RowY) > 0:

1220 if self.tbList.rowCount() > 0:

1221 for i in range(0, self.tbList.rowCount()):

1222 x = self.tbList.item(i, 1).text()

1223 y = self.tbList.item(i, 2).text()

1224 self.row_cols_grid(int(x), int(y), "watchpoint")

1225

1226 else:

1227 for i in range(0, len(self.ColX)):

1228 self.row_cols_grid(

1229 int(self.ColX[i]), int(self.RowY[i]), "watchpoint"

1230 )

1231 except Exception as e:

1232 MsError(e)

1233

1234 # 1. row/cols로 마커

1235 def row_cols_grid(self, row, column, type):

1236 if str(row) != "" and str(column) != "":

1237 row = int(row)

1238 column = int(column)

1239 if row < 0 or column < 0 or self._height <= column or self._width <= row:

1240 row = "out of extent"

1241 column = "out of extent"

1242 MsInfo("{0}, {1}".format(str(row), str(column)))

1243 else:

1244 if type == "watchpoint":

1245 Cell_X_Center2 = self._xmin + self._xsize / 2 + self._xsize * (row)

1246 Cell_Y_Center2 = (

1247 self._ymax - self._ysize / 2 - self._ysize * (column)

1248 )

1249 if (

1250 Cell_X_Center2 <= self._xmax

1251 or self._xmin <= Cell_X_Center2

1252 or Cell_Y_Center2 <= self._ymax

1253 or self._ymin <= Cell_Y_Center2

1254 ):

1255 self.draw_grid2(

1256 Cell_X_Center2, Cell_Y_Center2, self.btnColorPicker

1257 )

1258

1259 else:

1260 self.lblColRow.setText(

1261 "xCol, yRow:" + str(row) + " , " + str(column)

1262 )

1263 self.tool.Cell_X_Center = (

1264 self._xmin + self._xsize / 2 + self._xsize * (row)

1265 )

1266 self.tool.Cell_Y_Center = (

1267 self._ymax - self._ysize / 2 - self._ysize * (column)

1268 )

1269 if (

1270 self.tool.Cell_X_Center <= self._xmax

1271 or self.xmin <= self.tool.Cell_X_Center

1272 or self.tool.Cell_Y_Center <= self._ymax

1273 or self._ymin <= self.tool.Cell_Y_Center

1274 ):

1275 oldExtent = self.mapcanvas.extent()

1276

1277 x1n = self.tool.Cell_X_Center - oldExtent.width() / 2.0

1278 x2n = self.tool.Cell_X_Center + oldExtent.width() / 2.0

1279 y1n = self.tool.Cell_Y_Center - oldExtent.height() / 2.0

1280 y2n = self.tool.Cell_Y_Center + oldExtent.height() / 2.0

1281

1282 self.mapcanvas.setExtent(QgsRectangle(x1n, y2n, x2n, y1n))

1283 self.draw_grid(self.tool.Cell_X_Center, self.tool.Cell_Y_Center)

1284 else:

1285 MsError("There is a problem with the text value.")

1286 return

1287

1288 # Watch point 그림을 Rubberbanc로 처리 함

1289 def draw_grid2(self, x, y, btn):

1290 r = QgsRubberBand(self.mapcanvas, True)

1291 size = self._xsize / 2

1292

1293 points = [

1294 [

1295 QgsPointXY(x - size, y + size),

1296 QgsPointXY(x - size, y - size),

1297 QgsPointXY(x + size, y - size),

1298 QgsPointXY(x + size, y + size),

1299 ]

1300 ]

1301

1302 r.setToGeometry(QgsGeometry.fromPolygonXY(points), None)

1303 r.setColor(QColor(btn.palette().button().color()))

1304 r.setWidth(2)

1305

1306 self.canvasRubberBand.append(r)

1307

1308 def click_FlowContorGird(self):

1309 if self.chkFlowContorGird.isChecked():

1310 self.FlowContorGird_paint()

1311 else:

1312 # 지우기

1313 self.post_grid_remove2()

1314 if self.chkWatch_Point.isChecked():

1315 self.watchpoint_paint()

1316

1317 def FlowContorGird_paint(self):

1318 counts = self.tlbFlowControl.rowCount()

1319 for i in range(0, counts):

1320 xvalue = (

1321 self._xmin

1322 + self._xsize / 2

1323 + self._xsize * (int(self.tlbFlowControl.item(i, 1).text()))

1324 )

1325 yvalue = (

1326 self._ymax

1327 - self._ysize / 2

1328 - self._ysize * (int(self.tlbFlowControl.item(i, 2).text()))

1329 )

1330 self.draw_grid2(xvalue, yvalue, self.btnColorPicker_3)

1331

1332 # 그리드 라인 함수

1333 def show_hide_grid_line(self):

1334 if self.show_grid_line.isChecked():

1335 self.add_grid_layer()

1336 else:

1337 self.remove_grid_layer()

1338

1339 def remove_grid_layer(self):

1340 self.grid_line.setOpacity(0)

1341 self.mapcanvas.refresh()

1342

1343 # 플로우 디렉션

1344 def show_hide_flow_direction(self):

1345 if self.show_flow_direction.isChecked():

1346 self.show_flow_directions()

1347 else:

1348 self.hide_flow_direction()

1349

1350 def add_grid_layer(self):

1351 names = [layer.name() for layer in QgsProject.instance().mapLayers().values()]

1352 if names.count("grid_line") > 0:

1353 self.grid_line.setOpacity(1)

1354 self.mapcanvas.refresh()

1355 if names.count("flow_layer") > 0:

1356 # self.mapcanvas.setLayers([self.flow_direction_layer,self.grid_line,self.layer])

1357 self.mapcanvas.setLayers(

1358 [

1359 self.flow_direction,

1360 self.grid_line,

1361 self.layer,

1362 self.Wsid_label_shape,

1363 ]

1364 )

1365 else:

1366 self.grid_line = get_point_layer(self.layer, self.mapcanvas)

1367 QgsProject.instance().addMapLayer(self.grid_line, False)

1368 self.layer.extent().combineExtentWith(self.grid_line.extent())

1369 self.mapcanvas.setExtent(self.mapcanvas.extent())

1370

1371 # ========= 2017/11/10 : 기본적으로 Grid line 단일 체크시 Grid line 만 표현,flow direction 체크 시 flow direction 함께 표시

1372 self.mapcanvas.setLayers(

1373 [self.grid_line, self.layer, self.Wsid_label_shape]

1374 )

1375

1376 if self.flow_direction:

1377 self.mapcanvas.setLayers(

1378 [

1379 self.flow_direction,

1380 self.grid_line,

1381 self.layer,

1382 self.Wsid_label_shape,

1383 ]

1384 )

1385

1386 def show_flow_directions(self):

1387 names = [layer.name() for layer in QgsProject.instance().mapLayers().values()]

1388 if names.count("flow_layer") > 0:

1389 self.flow_direction.setOpacity(1)

1390 self.mapcanvas.refresh()

1391 else:

1392 FD = self._xmltodict["GRMProject"]["ProjectSettings"]["FlowDirectionFile"]

1393 ST = self._xmltodict["GRMProject"]["ProjectSettings"]["StreamFile"]

1394 self.layer2 = QgsRasterLayer(FD, "FD", "gdal")

1395 self.layer3 = QgsRasterLayer(ST, "ST", "gdal")

1396

1397 strFDType = self._xmltodict["GRMProject"]["ProjectSettings"][

1398 "FlowDirectionType"

1399 ]

1400 self.flow_direction = get_flow_layer(

1401 self.layer2, self.mapcanvas, self.layer3, strFDType, self.GridCellSize

1402 )

1403

1404 # 신규 소스

1405 QgsProject.instance().addMapLayer(self.flow_direction, False)

1406 self.layer.extent().combineExtentWith(self.flow_direction.extent())

1407

1408 # ========= 2017/11/10 : 기본적으로 flow direction 단일 체크시 다음 flow direction 만 표현,Grid line 체크 시 grid line 함께 표시

1409 self.mapcanvas.setLayers(

1410 [self.flow_direction, self.layer, self.Wsid_label_shape]

1411 )

1412 if names.count("grid_line") > 0:

1413 self.mapcanvas.setLayers(

1414 [

1415 self.grid_line,

1416 self.flow_direction,

1417 self.layer,

1418 self.Wsid_label_shape,

1419 ]

1420 )

1421 # ========= 2017/11/10 : 기본적으로 flow direction 단일 체크시 다음 flow direction 만 표현,Grid line 체크 시 grid line 함께 표시

1422

1423 # Qdilog 창에 Qtablewidget 셋팅

1424 def aboutApp(self):

1425 website = "http://code.google.com/p/comictagger"

1426 msgBox = QMessageBox()

1427 msgBox.setWindowTitle(self.tr("Move to grid"))

1428 msgBox.setTextFormat(Qt.RichText)

1429

1430 msgBox.setText("<pre></pre>")

1431 self.addGroupWidget(msgBox)

1432 ret = msgBox.exec_()

1433

1434 # Create TableWidget

1435 def addGroupWidget(self, parentItem):

1436 # 라디오 버튼, move to grid, xCol No, yRow No

1437 self.rdo_xColyRowNo = QRadioButton("xCol No, yRow No", parentItem)

1438 self.rdo_xy = QRadioButton("x, y", parentItem)

1439

1440 # 텍스트 박스

1441 self.txt_xColyRowNo_1 = QLineEdit(parentItem)

1442 self.txt_xColyRowNo_2 = QLineEdit(parentItem)

1443 self.txt_xy1 = QLineEdit(parentItem)

1444 self.txt_xy2 = QLineEdit(parentItem)

1445 self.btn_Cancel = QPushButton(parentItem)

1446 self.btn_Cancel.setText("Cancel")

1447

1448 self.btn_OK = QPushButton(parentItem)

1449 self.btn_OK.setText("OK")

1450 # 위치 정의 setGeometry(x,y,w,h)

1451 layout = parentItem.layout()

1452

1453 layout.addWidget(self.rdo_xColyRowNo, 0, 0)

1454 layout.addWidget(self.rdo_xy, 1, 0)

1455 layout.addWidget(self.txt_xColyRowNo_1, 0, 1)

1456 layout.addWidget(self.txt_xColyRowNo_2, 0, 2)

1457 layout.addWidget(self.txt_xy1, 1, 1)

1458 layout.addWidget(self.txt_xy2, 1, 2)

1459

1460 layout.addWidget(self.btn_Cancel, 2, 2)

1461 layout.addWidget(self.btn_OK, 2, 1)

1462

1463 self.txt_xColyRowNo_1.setMaximumWidth(100)

1464 self.txt_xColyRowNo_2.setMaximumWidth(100)

1465 self.txt_xy1.setFixedWidth(100)

1466 self.txt_xy2.setFixedWidth(100)

1467

1468 # 버튼별 이벤트

1469 # 1. rdo_xColyRowNo가 체크 시 그 외 비활성화

1470 self.rdo_xColyRowNo.setChecked(True)

1471 self.rdo_xy.setChecked(False)

1472 self.txt_xy1.setDisabled(True)

1473 self.txt_xy2.setDisabled(True)

1474 # 라디오 버튼 이벤트, 함수는 나중에 수정 바람... 2017/10/19 Cho

1475 self.rdo_xColyRowNo.clicked.connect(self.disableFunction)

1476 self.rdo_xy.clicked.connect(self.disableFunction)

1477 self.btn_OK.clicked.connect(self.OK_Click)

1478 self.btn_Cancel.clicked.connect(lambda: self.Cancel_Click(parentItem))

1479

1480 def Cancel_Click(self, parentItem):

1481 parentItem.close()

1482

1483 # 폼 종료

1484 def Close_Form(self):

1485 self.close()

1486

1487 def closeEvent(self, event):

1488 self._wsinfo.disconnect_dll()

1489 del self._wsinfo

1490 self.Clear_Canvas()

1491 self.closeDialogEvent.emit()

1492

1493 def SaveProject(self, flag=False):

1494 self.InputDictionary()

1495 DictoXml = unparse(self._xmltodict)

1496 fw = open(self.ProjectFile, "w+")

1497 fw.write(DictoXml)

1498 fw.close()

1499

1500 # 2020-02-10 박: XML 체크할때 Landcover 데이터를 배열에 받아서 반환 함

1501 _XmlCheck.Check_Gmp_xml(self.ProjectFile)

1502 self._LandCoverCount = _XmlCheck._LandCoverCount

1503 self._GreenAmptCount = _XmlCheck._GreenAmptCount

1504 self._SoilDepthCount = _XmlCheck._SoilDepthCount

1505 self._WatchPointCount = _XmlCheck._WatchPointCount

1506 self._SubWatershedCount = _XmlCheck._SubWatershedCount

1507 self._FlowControlCount = _XmlCheck._FlowControlCount

1508 self._ChannelSettingsCount = _XmlCheck._ChannelSettingsCount

1509 if flag:

1510 MsInfo("[" + self.ProjectFile + "]" + " was saved. ")

1511

1512 def InputDictionary(self):

1513 try:

1514 # =========================simulation tab ===================================

1515 self._xmltodict["GRMProject"]["ProjectSettings"][

1516 "ComputationalTimeStep_min"

1517 ] = self.spTimeStep_min.text()

1518 if self.chkStartingTime.isChecked():

1519 DateTime = self.dateTimeEdit.dateTime().toString("yyyy-MM-dd hh:mm")

1520 self._xmltodict["GRMProject"]["ProjectSettings"][

1521 "SimulationStartingTime"

1522 ] = DateTime

1523 else:

1524 self._xmltodict["GRMProject"]["ProjectSettings"][

1525 "SimulationStartingTime"

1526 ] = "0"

1527

1528 if self.chkParallel.isChecked():

1529 self._xmltodict["GRMProject"]["ProjectSettings"][

1530 "MaxDegreeOfParallelism"

1531 ] = self.spTimeStep_min_2.text()

1532

1533 else:

1534 self._xmltodict["GRMProject"]["ProjectSettings"][

1535 "MaxDegreeOfParallelism"

1536 ] = "-1"

1537

1538 if self.chkPrintAveValue.isChecked():

1539 self._xmltodict["GRMProject"]["ProjectSettings"][

1540 "AveValueTimeInterval_min"

1541 ] = self.spbAveValueTimeInterval_min.text()

1542 else:

1543 self._xmltodict["GRMProject"]["ProjectSettings"][

1544 "AveValueTimeInterval_min"

1545 ] = ""

1546

1547 self._xmltodict["GRMProject"]["ProjectSettings"][

1548 "OutputTimeStep_min"

1549 ] = self.txtOutput_time_step.text()

1550 self._xmltodict["GRMProject"]["ProjectSettings"][

1551 "SimulationDuration_hr"

1552 ] = self.txtSimulation_duration.text()

1553 self._xmltodict["GRMProject"]["ProjectSettings"][

1554 "OutputTimeStep_min"

1555 ] = self.txtOutput_time_step.text()

1556

1557 projectTagDic = {

1558 "SimulateInfiltration": self.chkInfiltration,

1559 "SimulateSubsurfaceFlow": self.chkSubsurfaceFlow,

1560 "SimulateBaseFlow": self.chkBaseFlow,

1561 "SimulateInterception": self.chkInterception,

1562 "SimulateEvapotranspiration": self.chkEvapotranspiration,

1563 "SimulateSnowMelt": self.chkSnowMelt,

1564 "SimulateFlowControl": self.chkFlowControl,

1565 "MakeIMGFile": self.chkmakeimage,

1566 "MakeASCFile": self.chkmakeASC,

1567 "MakeSoilSaturationDistFile": self.chksoiSaturation,

1568 "MakeRfDistFile": self.chkrfDistFile,

1569 "MakeRFaccDistFile": self.chkrfaacDistfile,

1570 "MakeFlowDistFile": self.chkdischarge,

1571 "PrintAveValue": self.chkPrintAveValue,

1572 "WriteLog": self.chklog,

1573 "IsFixedTimeStep": self.chkfixeTimeStep,

1574 }

1575

1576 for k in projectTagDic.keys():

1577 self._xmltodict["GRMProject"]["ProjectSettings"][k] = str(

1578 projectTagDic[k].isChecked()

1579 ).lower() #'true' or 'false'

1580

1581 self._xmltodict["GRMProject"]["ProjectSettings"][

1582 "PrintOption"

1583 ] = self.cmbPrint.currentText()

1584

1585 # =========================simulation tab end ===============================================

1586

1587 # =========================Watch Point tab===================================================

1588 # GRM._WatchPointCount

1589 # if self._WatchPointCount > 0:

1590 try:

1591 # 2021.12.07 동 : watchpoint, subwatershed 태그는 Set_ProjectDataInit 함수에서 초기값 세팅을 안해주기 때문에

1592 # 프로젝트 오픈후 처음으로 run dialog를 실행 시켰을 때 self._WatchPointCount..등 값이 무조건 0 값으로 표기됨.

1593 # 그래서 값이 중복되서 저장되는 현상이 있어 keyerror가 발생하지 않는한, 무조건 적으로 지우도록 변경

1594 del self._xmltodict["GRMProject"]["WatchPoints"]

1595 except KeyError:

1596 pass

1597 self._WatchPointCount = self.tbList.rowCount()

1598

1599 DictoXml = unparse(self._xmltodict)

1600 ET.register_namespace("", "http://tempuri.org/GRMProject.xsd")

1601 xmltree = ET.ElementTree(ET.fromstring(DictoXml))

1602 root = xmltree.getroot()

1603

1604 wcount = self.tbList.rowCount()

1605 self._WatchPointCount = wcount

1606 for row in range(0, wcount):

1607 child = ET.Element("WatchPoints")

1608 root.append(child)

1609

1610 WathchName = ET.Element("Name")

1611 WathchName.text = self.tbList.item(row, 0).text()

1612 child.append(WathchName)

1613

1614 WathchColX = ET.Element("ColX")

1615 WathchColX.text = self.tbList.item(row, 1).text()

1616 child.append(WathchColX)

1617

1618 WathchRowY = ET.Element("RowY")

1619 WathchRowY.text = self.tbList.item(row, 2).text()

1620 child.append(WathchRowY)

1621 xmltree_string = ET.tostring(xmltree.getroot())

1622 docs = dict(parse(xmltree_string))

1623 self._xmltodict.clear()

1624 self._xmltodict.update(docs)

1625

1626 # =========================Wahch Point tab end===============================================

1627

1628 # =========================Channel CS tab====================================================

1629 # 2020-04-28 박: 이부분이 따로 떨어져서 xml 생성됨 그래서 주석 처리로 변경 하고 XML 부분 수정으로 소스 수정

1630 if self._ChannelSettingsCount > 0:

1631 del self._xmltodict["GRMProject"]["ChannelSettings"]

1632

1633 DictoXml = unparse(self._xmltodict)

1634 ET.register_namespace("", "http://tempuri.org/GRMProject.xsd")

1635 xmltree = ET.ElementTree(ET.fromstring(DictoXml))

1636 root = xmltree.getroot()

1637 self._ChannelSettingsCount = len(self._StreamWSID)

1638

1639 for index in range(0, self._ChannelSettingsCount):

1640 child = ET.Element("ChannelSettings")

1641 root.append(child)

1642

1643 WSID = ET.Element("WSID")

1644 WSID.text = str(self._StreamWSID[index])

1645 child.append(WSID)

1646

1647 CrossSectionType = ET.Element("CrossSectionType")

1648 if self.CrossSectionType[index] == "CSCOMPOUND":

1649 CrossSectionType.text = "CSCompound"

1650 elif self.CrossSectionType[index] == "CSSINGLE":

1651 CrossSectionType.text = "CSSingle"

1652 else:

1653 CrossSectionType.text = "CSSingle"

1654 child.append(CrossSectionType)

1655

1656 SingleCSChannelWidthType = ET.Element("SingleCSChannelWidthType")

1657 if self.SingleCSChannelWidthType[index].upper() == "CWGENERATION":

1658 SingleCSChannelWidthType.text = "CWGeneration"

1659 elif self.SingleCSChannelWidthType[index].upper() == "CWEQUATION":

1660 SingleCSChannelWidthType.text = "CWEquation"

1661 else:

1662 SingleCSChannelWidthType.text = "CWGeneration"

1663

1664 child.append(SingleCSChannelWidthType)

1665

1666 ChannelWidthEQc = ET.Element("ChannelWidthEQc")

1667 ChannelWidthEQc.text = str(self.ChannelWidthEQc[index])

1668 child.append(ChannelWidthEQc)

1669

1670 ChannelWidthEQd = ET.Element("ChannelWidthEQd")

1671 ChannelWidthEQd.text = str(self.ChannelWidthEQd[index])

1672 child.append(ChannelWidthEQd)

1673

1674 ChannelWidthEQe = ET.Element("ChannelWidthEQe")

1675 ChannelWidthEQe.text = str(self.ChannelWidthEQe[index])

1676 child.append(ChannelWidthEQe)

1677

1678 ChannelWidthMostDownStream = ET.Element("ChannelWidthMostDownStream")

1679 ChannelWidthMostDownStream.text = str(

1680 self.ChannelWidthMostDownStream[index]

1681 )

1682 child.append(ChannelWidthMostDownStream)

1683

1684 LowerRegionHeight = ET.Element("LowerRegionHeight")

1685 LowerRegionHeight.text = str(self.LowerRegionHeight[index])

1686 child.append(LowerRegionHeight)

1687

1688 LowerRegionBaseWidth = ET.Element("LowerRegionBaseWidth")

1689 LowerRegionBaseWidth.text = str(self.LowerRegionBaseWidth[index])

1690 child.append(LowerRegionBaseWidth)

1691

1692 UpperRegionBaseWidth = ET.Element("UpperRegionBaseWidth")

1693 UpperRegionBaseWidth.text = str(self.UpperRegionBaseWidth[index])

1694 child.append(UpperRegionBaseWidth)

1695

1696 CompoundCSChannelWidthLimit = ET.Element("CompoundCSChannelWidthLimit")

1697 CompoundCSChannelWidthLimit.text = str(

1698 self.CompoundCSChannelWidthLimit[index]

1699 )

1700 child.append(CompoundCSChannelWidthLimit)

1701

1702 BankSideSlopeRight = ET.Element("BankSideSlopeRight")

1703 BankSideSlopeRight.text = str(self.BankSideSlopeRight[index])

1704 child.append(BankSideSlopeRight)

1705

1706 BankSideSlopeLeft = ET.Element("BankSideSlopeLeft")

1707 BankSideSlopeLeft.text = str(self.BankSideSlopeLeft[index])

1708 child.append(BankSideSlopeLeft)

1709

1710 xmltree_string = ET.tostring(xmltree.getroot())

1711 docs = dict(parse(xmltree_string))

1712 self._xmltodict.clear()

1713 self._xmltodict.update(docs)

1714

1715 # =========================Channel CS tab end================================================

1716 # =========================Flow Control Tab==================================================

1717 self.UpdateFlowControl()

1718

1719 # =========================Flow Control Tab end ==================================================

1720 # ========================= Watershed tab ========================================================

1721 # if self._SubWatershedCount>0:

1722 try:

1723 del self._xmltodict["GRMProject"]["SubWatershedSettings"]

1724 except KeyError:

1725 pass

1726

1727 DictoXml = unparse(self._xmltodict)

1728 ET.register_namespace("", "http://tempuri.org/GRMProject.xsd")

1729 xmltree = ET.ElementTree(ET.fromstring(DictoXml))

1730 root = xmltree.getroot()

1731 self._SubWatershedCount = self.cb_selectws.count()

1732 scount = self.cb_selectws.count()

1733

1734 for row in range(0, scount):

1735 selectWS = self.cb_selectws.itemText(row)

1736

1737 child = ET.Element("SubWatershedSettings")

1738 root.append(child)

1739

1740 ID = ET.Element("ID")

1741 ID.text = selectWS

1742 child.append(ID)

1743

1744 IniSaturation = ET.Element("IniSaturation")

1745 IniSaturation.text = ex_to_float(

1746 self._wsinfo.subwatershedPars(int(selectWS)).iniSaturation

1747 )

1748 child.append(IniSaturation)

1749

1750 MinSlopeOF = ET.Element("MinSlopeOF")

1751 MinSlopeOF.text = ex_to_float(

1752 self._wsinfo.subwatershedPars(int(selectWS)).minSlopeOF

1753 )

1754 child.append(MinSlopeOF)

1755

1756 UnsaturatedKType = ET.Element("UnsaturatedKType")

1757 UnsaturatedKType_int = str(

1758 self._wsinfo.subwatershedPars(int(selectWS)).unSatKType

1759 )

1760 UnsturatedType = "Linear" # 2021.12.06 동 : 1 or default 값은 Linear

1761 if UnsaturatedKType_int == "0":

1762 UnsturatedType = "Constant"

1763 elif UnsaturatedKType_int == "2":

1764 UnsturatedType = "Exponential"

1765

1766 UnsaturatedKType.text = UnsturatedType

1767 child.append(UnsaturatedKType)

1768

1769 CoefUnsaturatedK = ET.Element("CoefUnsaturatedK")

1770 CoefUnsaturatedK.text = ex_to_float(

1771 self._wsinfo.subwatershedPars(int(selectWS)).coefUnsaturatedK

1772 )

1773 child.append(CoefUnsaturatedK)

1774

1775 MinSlopeChBed = ET.Element("MinSlopeChBed")

1776 MinSlopeChBed.text = ex_to_float(

1777 self._wsinfo.subwatershedPars(int(selectWS)).minSlopeChBed

1778 )

1779 child.append(MinSlopeChBed)

1780

1781 MinChBaseWidth = ET.Element("MinChBaseWidth")

1782 MinChBaseWidth.text = ex_to_float(

1783 self._wsinfo.subwatershedPars(int(selectWS)).minChBaseWidth

1784 )

1785 child.append(MinChBaseWidth)

1786

1787 ChRoughness = ET.Element("ChRoughness")

1788 ChRoughness.text = ex_to_float(

1789 self._wsinfo.subwatershedPars(int(selectWS)).chRoughness

1790 )

1791 child.append(ChRoughness)

1792

1793 DryStreamOrder = ET.Element("DryStreamOrder")

1794 DryStreamOrder.text = str(

1795 self._wsinfo.subwatershedPars(int(selectWS)).dryStreamOrder

1796 )

1797 child.append(DryStreamOrder)

1798

1799 IniFlow = ET.Element("IniFlow")

1800 IniFlow.text = "0"

1801 if self._wsinfo.subwatershedPars(int(selectWS)).iniFlow is not None:

1802 IniFlow.text = ex_to_float(

1803 self._wsinfo.subwatershedPars(int(selectWS)).iniFlow

1804 )

1805 child.append(IniFlow)

1806

1807 CalCoefLCRoughness = ET.Element("CalCoefLCRoughness")

1808 CalCoefLCRoughness.text = ex_to_float(

1809 self._wsinfo.subwatershedPars(int(selectWS)).ccLCRoughness

1810 )

1811 child.append(CalCoefLCRoughness)

1812

1813 CalCoefPorosity = ET.Element("CalCoefPorosity")

1814 CalCoefPorosity.text = ex_to_float(

1815 self._wsinfo.subwatershedPars(int(selectWS)).ccPorosity

1816 )

1817 child.append(CalCoefPorosity)

1818

1819 CalCoefWFSuctionHead = ET.Element("CalCoefWFSuctionHead")

1820 CalCoefWFSuctionHead.text = ex_to_float(

1821 self._wsinfo.subwatershedPars(int(selectWS)).ccWFSuctionHead

1822 )

1823 child.append(CalCoefWFSuctionHead)

1824

1825 CalCoefHydraulicK = ET.Element("CalCoefHydraulicK")

1826 CalCoefHydraulicK.text = ex_to_float(

1827 self._wsinfo.subwatershedPars(int(selectWS)).ccHydraulicK

1828 )

1829 child.append(CalCoefHydraulicK)

1830

1831 CalCoefSoilDepth = ET.Element("CalCoefSoilDepth")

1832 CalCoefSoilDepth.text = ex_to_float(

1833 self._wsinfo.subwatershedPars(int(selectWS)).ccSoilDepth

1834 )

1835 child.append(CalCoefSoilDepth)

1836

1837 InterceptionMethod = ET.Element("InterceptionMethod")

1838 InterceptionMethod_int = int(

1839 self._wsinfo.subwatershedPars(int(selectWS)).interceptMethod

1840 )

1841 InterceptionMethodType = EnumInterceptionMethod(

1842 InterceptionMethod_int

1843 ).name

1844 InterceptionMethod.text = InterceptionMethodType

1845 child.append(InterceptionMethod)

1846

1847 PETMethod = ET.Element("PETMethod")

1848 PETMethod_int = int(

1849 self._wsinfo.subwatershedPars(int(selectWS)).potentialETMethod

1850 )

1851 PETMethodType = EnumPETMethod(PETMethod_int).name

1852 PETMethod.text = PETMethodType

1853 child.append(PETMethod)

1854

1855 ETCoef = ET.Element("ETCoef")

1856 ETCoef.text = ex_to_float(

1857 self._wsinfo.subwatershedPars(int(selectWS)).etCoeff

1858 )

1859 child.append(ETCoef)

1860

1861 SnowmeltMethod = ET.Element("SnowmeltMethod")

1862 SnowmeltMethod_int = int(

1863 self._wsinfo.subwatershedPars(int(selectWS)).snowMeltMethod

1864 )

1865 SnowmeltMethodType = EnumSnowMeltMethod(SnowmeltMethod_int).name

1866 SnowmeltMethod.text = SnowmeltMethodType

1867 child.append(SnowmeltMethod)

1868

1869 TempSnowRain = ET.Element("TempSnowRain")

1870 TempSnowRain.text = ex_to_float(

1871 self._wsinfo.subwatershedPars(int(selectWS)).tempSnowRain

1872 )

1873 child.append(TempSnowRain)

1874

1875 SnowmeltingTemp = ET.Element("SnowmeltingTemp")

1876 SnowmeltingTemp.text = ex_to_float(

1877 self._wsinfo.subwatershedPars(int(selectWS)).smeltingTemp

1878 )

1879 child.append(SnowmeltingTemp)

1880

1881 SnowCovRatio = ET.Element("SnowCovRatio")

1882 SnowCovRatio.text = ex_to_float(

1883 self._wsinfo.subwatershedPars(int(selectWS)).snowCovRatio

1884 )

1885 child.append(SnowCovRatio)

1886

1887 SnowmeltCoef = ET.Element("SnowmeltCoef")

1888 SnowmeltCoef.text = ex_to_float(

1889 self._wsinfo.subwatershedPars(int(selectWS)).smeltCoef

1890 )

1891 child.append(SnowmeltCoef)

1892

1893 UserSet = ET.Element("UserSet")

1894 UserSet_value = str(

1895 self._wsinfo.subwatershedPars(int(selectWS)).userSet

1896 )

1897 UserSet.text = "False"

1898 if UserSet_value == "1":

1899 UserSet.text = "True"

1900

1901 child.append(UserSet)

1902

1903 xmltree_string = ET.tostring(xmltree.getroot())

1904 docs = dict(parse(xmltree_string))

1905 self._xmltodict.clear()

1906 self._xmltodict.update(docs)

1907

1908 except Exception as e:

1909 MsError(e)

1910

1911 def Clear_Canvas(self):

1912 try:

1913 # 레이어가 자꾸 잡혀 있어서 프로세스가 사용중으로 나옴 그래서 레이어 삭제 기능 추가해서 넣음

1914 layers = self.mapcanvas.layers()

1915 for l in layers:

1916 QgsProject.instance().removeMapLayer(l.id())

1917 self.mapcanvas.clearCache()

1918 # self.AddLayerQGIS()

1919

1920 except Exception as e:

1921 pass

1922

1923 def AddLayerQGIS(self):

1924 # dictionary 값을 받아서 레이어 목록을 Qgis 에 올림

1925 proTag = [

1926 "DomainFile",

1927 "SlopeFile",

1928 "FlowDirectionFile",

1929 "FlowAccumFile" "StreamFile",

1930 "LandCoverFile",

1931 "SoilDepthFile",

1932 "SoilTextureFile",

1933 ]

1934

1935 for t in proTag:

1936 if self._xmltodict["GRMProject"]["ProjectSettings"][t] is not None:

1937 self.AddlayerQGIS(self._xmltodict["GRMProject"]["ProjectSettings"][t])

1938

1939 # gis에 올리기

1940 def AddlayerQGIS(self, path):

1941 try:

1942 if os.path.isfile(path):

1943 fileInfo = QFileInfo(path)

1944 baseName = fileInfo.baseName()

1945 layer = QgsRasterLayer(path, baseName, "gdal")

1946 QgsProject.instance().addMapLayer(layer)

1947 except Exception as e:

1948 MsInfo(e)

1949

1950 def OK_Click(self):

1951 self.post_grid_remove()

1952 self.rdo_selection()

1953 self.mapcanvas.refresh()

1954 self.scale_changed_mapcanvas()

1955 self.tool.scale_changed_disconnect()

1956

1957 # scale에 따라 Marker 크기 변화 -- Canvastool class 별개 함수

1958 def scale_changed_mapcanvas(self):

1959 try:

1960 # connect 중복 연결 방지

1961 self.mapcanvas.scaleChanged.disconnect(self.scale_change_vertexMarker)

1962 except TypeError:

1963 pass

1964 self.mapcanvas.scaleChanged.connect(self.scale_change_vertexMarker)

1965

1966 def scale_change_vertexMarker(self):

1967 self.post_grid_remove()

1968 try:

1969 if (

1970 self.tool.Cell_X_Center is not None

1971 or self.tool.Cell_Y_Center is not None

1972 ):

1973 self.draw_grid(self.tool.Cell_X_Center, self.tool.Cell_Y_Center)

1974 except AttributeError:

1975 pass

1976

1977 # ================== 2017/11/6 조

1978 def post_grid_remove(self):

1979 for v in self.mapcanvas.scene().items():

1980 if issubclass(type(v), QgsVertexMarker):

1981 self.mapcanvas.scene().removeItem(v)

1982

1983 def rdo_selection(self):

1984 # col, row 입력

1985 if self.rdo_xColyRowNo.isChecked():

1986 self.tool._FXCOL = int(self.txt_xColyRowNo_2.text())

1987 self.tool._FYROW = int(self.txt_xColyRowNo_1.text())

1988 self.tool._XCOL = int(self.txt_xColyRowNo_2.text())

1989 self.tool._YROW = int(self.txt_xColyRowNo_1.text())

1990

1991 gird = self.row_cols_grid(

1992 self.txt_xColyRowNo_1.text(), self.txt_xColyRowNo_2.text(), None

1993 )

1994 # xy 입력

1995 elif self.rdo_xy.isChecked():

1996 self.xy_grid(self.layer, self.txt_xy1.text(), self.txt_xy2.text())

1997 x = self.txt_xy1.text()

1998 y = self.txt_xy2.text()

1999

2000 def identify(self):

2001 # 캔버스 휠까지 처리 됨

2002 self.mapcanvas.setCursor(QtGui.QCursor(Qt.ArrowCursor))

2003

2004 self.tool.scale_changed()

2005 self.mapcanvas.setMapTool(self.tool)

2006

2007 def disableFunction(self):

2008 flag = self.rdo_xColyRowNo.isChecked()

2009 self.txt_xColyRowNo_1.setDisabled(not flag)

2010 self.txt_xColyRowNo_2.setDisabled(not flag)

2011 self.txt_xy1.setDisabled(flag)

2012 self.txt_xy2.setDisabled(flag)

2013

2014 # grid 그리기

2015 def draw_grid(self, x, y):

2016 marker = QgsVertexMarker(self.mapcanvas)

2017 marker.setCenter(QgsPointXY(float(x), float(y)))

2018

2019 marker.setColor(QColor(255, 0, 0))

2020 scale = self.mapcanvas.scale()

2021 # 사이즈 조절함. 가능한 맞게 조정함

2022 map_width = (

2023 self.mapcanvas.extent().xMaximum() - self.mapcanvas.extent().xMinimum()

2024 )

2025 size = (self._xsize / 150.0) * 100000 / map_width

2026 marker.setIconSize(size)

2027 marker.setIconType(QgsVertexMarker.ICON_BOX)

2028 marker.setPenWidth(1)

2029 return marker

2030

2031 def hide_flow_direction(self):

2032 self.flow_direction.setOpacity(0)

2033 self.mapcanvas.refresh()

2034

2035 # ----------------- Channel CS 탭 텍스트 박스 셋팅 -----------------------------

2036 def Set_ChannelCS_tab_default(self):

2037 CrossSectionType = self.CrossSectionType[0].upper()

2038 SingleCSChannelWidthType = self.SingleCSChannelWidthType[0].upper()

2039

2040 if CrossSectionType == "CSSINGLE":

2041 self.chk_compound.setChecked(False)

2042 elif CrossSectionType == "CSCOMPOUND":

2043 self.chk_compound.setChecked(True)

2044

2045 if SingleCSChannelWidthType == "CWGENERATION":

2046 self.rdo_generateCh.setChecked(True)

2047 elif SingleCSChannelWidthType == "CWEQUATION":

2048 self.rdo_useCh.setChecked(True)

2049 else:

2050 self.rdo_generateCh.setChecked(True)

2051

2052 self.txt_c.setText(self.ChannelWidthEQc[0])

2053 self.txt_d.setText(self.ChannelWidthEQd[0])

2054 self.txt_e.setText(self.ChannelWidthEQe[0])

2055 self.txt_douwnstream.setText(self.ChannelWidthMostDownStream[0])

2056 self.txtLower_Region_Height.setText(self.LowerRegionHeight[0])

2057 self.txtLower_Region_Base_Width.setText(self.LowerRegionBaseWidth[0])

2058 self.txtUpper_Region_Base_Width.setText(self.UpperRegionBaseWidth[0])

2059 self.txtCompound_CSChannel_Width_Limit.setText(

2060 self.CompoundCSChannelWidthLimit[0]

2061 )

2062 self.txtRight_bank.setText(self.BankSideSlopeRight[0])

2063 self.txtLeft_bank.setText(self.BankSideSlopeLeft[0])

2064

2065 self.txt_douwnstream.setDisabled(True)

2066 self.ChannelCS_rdo_able()

2067

2068 self.chk_compound.clicked.connect(self.ChannelCS_rdo_able)

2069

2070 self.rdo_useCh.clicked.connect(self.ChannelCS_rdo_able)

2071 self.rdo_generateCh.clicked.connect(self.ChannelCS_rdo_able)

2072 self.lisw_WSID.clicked.connect(self.ListView_WSID)

2073 self.lisw_WSID.currentItemChanged.connect(self.key_events)

2074

2075 self.btn_Apply_WSID_value.clicked.connect(self.set_WSID_value_change)

2076

2077 def key_events(self):

2078 try:

2079 index = self.lisw_WSID.currentRow()

2080 CrossSectionType = self.CrossSectionType[index].upper()

2081 SingleCSChannelWidthType = self.SingleCSChannelWidthType[index].upper()

2082 if SingleCSChannelWidthType == "CWGENERATION":

2083 self.rdo_generateCh.setChecked(True)

2084 elif SingleCSChannelWidthType == "CWEQUATION":

2085 self.rdo_useCh.setChecked(True)

2086 else:

2087 self.rdo_generateCh.setChecked(True)

2088 if CrossSectionType == "CSSINGLE":

2089 self.chk_compound.setChecked(False)

2090 elif CrossSectionType == "CSCOMPOUND":

2091 self.chk_compound.setChecked(True)

2092 else:

2093 self.chk_compound.setChecked(False)

2094

2095 self.txt_c.setText(self.ChannelWidthEQc[index])

2096 self.txt_d.setText(self.ChannelWidthEQd[index])

2097 self.txt_e.setText(self.ChannelWidthEQe[index])

2098 self.txt_douwnstream.setText(self.ChannelWidthMostDownStream[index])

2099 self.txtLower_Region_Height.setText(self.LowerRegionHeight[index])

2100 self.txtLower_Region_Base_Width.setText(self.LowerRegionBaseWidth[index])

2101 self.txtUpper_Region_Base_Width.setText(self.UpperRegionBaseWidth[index])

2102 self.txtCompound_CSChannel_Width_Limit.setText(

2103 self.CompoundCSChannelWidthLimit[index]

2104 )

2105 self.txtRight_bank.setText(self.BankSideSlopeRight[index])

2106 self.txtLeft_bank.setText(self.BankSideSlopeLeft[index])

2107

2108 self.txt_douwnstream.setDisabled(True)

2109 self.ChannelCS_rdo_able()

2110

2111 except Exception as e:

2112 MsError(e)

2113

2114 # 2020-07-09 박: WSID 별 값수정 후 적용 하기 버튼 이벤트

2115 def set_WSID_value_change(self):

2116 try:

2117 if self.lisw_WSID.currentItem():

2118 select_item = self.lisw_WSID.currentItem().text()

2119

2120 # 2020-07-16 박:기능 변경

2121 for i in range(self._ChannelSettingsCount):

2122 if str(self._StreamWSID[i]) == str(select_item):

2123 self.ChannelWidthEQc[i] = self.txt_c.text()

2124 self.ChannelWidthEQd[i] = self.txt_d.text()

2125 self.ChannelWidthEQe[i] = self.txt_e.text()

2126 self.ChannelWidthMostDownStream[i] = self.txt_douwnstream.text()

2127 self.LowerRegionHeight[i] = self.txtLower_Region_Height.text()

2128 self.LowerRegionBaseWidth[

2129 i

2130 ] = self.txtLower_Region_Base_Width.text()

2131 self.UpperRegionBaseWidth[

2132 i

2133 ] = self.txtUpper_Region_Base_Width.text()

2134 self.CompoundCSChannelWidthLimit[

2135 i

2136 ] = self.txtCompound_CSChannel_Width_Limit.text()

2137 self.BankSideSlopeRight[i] = self.txtRight_bank.text()

2138 self.BankSideSlopeLeft[i] = self.txtLeft_bank.text()

2139

2140 if self.rdo_generateCh.isChecked():

2141 self.SingleCSChannelWidthType[i] = "CWGENERATION"

2142 elif self.rdo_useCh.isChecked():

2143 self.SingleCSChannelWidthType[i] = "CWEQUATION"

2144

2145 self.CrossSectionType[i] = "CSSingle"

2146 if self.chk_compound.isChecked():

2147 self.CrossSectionType[i] = "CSCOMPOUND"

2148

2149 MsInfo("Channel setting was updated.")

2150

2151 else:

2152 MsInfo("Select WSID ")

2153 except Exception as e:

2154 MsError(e)

2155

2156 def ListView_WSID(self, index):

2157 try:

2158 CrossSectionType = self.CrossSectionType[index.row()].upper()

2159 SingleCSChannelWidthType = self.SingleCSChannelWidthType[

2160 index.row()

2161 ].upper()

2162 if SingleCSChannelWidthType == "CWGENERATION":

2163 self.rdo_generateCh.setChecked(True)

2164 elif SingleCSChannelWidthType == "CWEQUATION":

2165 self.rdo_useCh.setChecked(True)

2166 else:

2167 self.rdo_generateCh.setChecked(True)

2168 if CrossSectionType == "CSSINGLE":

2169 self.chk_compound.setChecked(False)

2170 elif CrossSectionType == "CSCOMPOUND":

2171 self.chk_compound.setChecked(True)

2172 else:

2173 self.chk_compound.setChecked(False)

2174

2175 self.txt_c.setText(self.ChannelWidthEQc[index.row()])

2176 self.txt_d.setText(self.ChannelWidthEQd[index.row()])

2177 self.txt_e.setText(self.ChannelWidthEQe[index.row()])

2178 self.txt_douwnstream.setText(self.ChannelWidthMostDownStream[index.row()])

2179 self.txtLower_Region_Height.setText(self.LowerRegionHeight[index.row()])

2180 self.txtLower_Region_Base_Width.setText(

2181 self.LowerRegionBaseWidth[index.row()]

2182 )

2183 self.txtUpper_Region_Base_Width.setText(

2184 self.UpperRegionBaseWidth[index.row()]

2185 )

2186 self.txtCompound_CSChannel_Width_Limit.setText(

2187 self.CompoundCSChannelWidthLimit[index.row()]

2188 )

2189 self.txtRight_bank.setText(self.BankSideSlopeRight[index.row()])

2190 self.txtLeft_bank.setText(self.BankSideSlopeLeft[index.row()])

2191

2192 self.txt_douwnstream.setDisabled(True)

2193 self.ChannelCS_rdo_able()

2194

2195 except Exception as e:

2196 MsError(e)

2197

2198 # Channel CS --2017/09/08 조

2199 # 라디오 버튼 클릭 시 활성/비활성 함수

2200 def ChannelCS_rdo_able(self):

2201 # 활성 상태

2202 self.row = self.lisw_WSID.currentRow()

2203

2204 # Use channel width equation 활성 상태인 경우

2205 if self.rdo_useCh.isChecked():

2206 # 2020-04-28 박: 라디오 이벤트로 배열값 변경 처리

2207 self.txt_douwnstream.setDisabled(True)

2208 self.txt_c.setDisabled(False)

2209 self.txt_d.setDisabled(False)

2210 self.txt_e.setDisabled(False)

2211

2212 # Use channel width equation 비활성 상태인 경우

2213 elif self.rdo_generateCh.isChecked():

2214 self.txt_douwnstream.setDisabled(False)

2215 self.txt_c.setDisabled(True)

2216 self.txt_d.setDisabled(True)

2217 self.txt_e.setDisabled(True)

2218

2219 # single cross section 라디오 버튼이 비활성 상태 일 때

2220 if self.chk_compound.isChecked():

2221 self.groupBox_6.setDisabled(False)

2222 else:

2223 self.groupBox_6.setDisabled(True)

2224

2225 # ----------------- 2017-10-24_오전 박 Watershed Parmeters 탭 텍스트 박스 셋팅 -----------------------------

2226 def Set_Watershed_Parameter_tab_default(self):

2227 # Select watershed 콥보 박스 셋팅

2228 self.Set_Watershed_combo()

2229

2230 # 함수로 빼야함 급해서 그냥 넣음

2231 combolist = ["Constant", "Linear", "Exponential"]

2232 # combolist = ('Linear','Exponential','Constant')

2233 self.cmbUnsturatedType.addItems(combolist)

2234 self.cmbUnsturatedType.currentIndexChanged.connect(self.chage_UnsturatedType)

2235

2236 for interception_method in EnumInterceptionMethod:

2237 self.cmbInterceptionMethodType.addItem(

2238 interception_method.name, interception_method.value

2239 )

2240

2241 self.cmbInterceptionMethodType.setCurrentIndex(

2242 self.cmbInterceptionMethodType.findText("None")

2243 )

2244

2245 for PET_method in EnumPETMethod:

2246 self.cmbPETMethodType.addItem(PET_method.name, PET_method.value)

2247

2248 self.cmbPETMethodType.setCurrentIndex(self.cmbPETMethodType.findText("None"))

2249

2250 for snowmelt_method in EnumSnowMeltMethod:

2251 self.cmbSnowmeltMethodType.addItem(

2252 snowmelt_method.name, snowmelt_method.value

2253 )

2254

2255 self.cmbSnowmeltMethodType.setCurrentIndex(

2256 self.cmbSnowmeltMethodType.findText("None")

2257 )

2258

2259 ## 최하류 셀값 설정정

2260 self.Set_MostDownStream()

2261 self.cb_selectws.currentIndexChanged.connect(self.SelectWsCombobox)

2262

2263 # 2020-05-19 박:콤보 박스 셋팅후 각각의 상류 하류 유역 정보가 설정 되지 않아서 호출

2264 self.SelectWsCombobox()

2265

2266 self.btnApplyWS.clicked.connect(self.UserSet_Add)

2267 self.btnRemoveWS.clicked.connect(self.UserSet_remove)

2268 self.SetWatershedstream()

2269 # 2020-05-19 박:콤보 박스 셋팅후 각각의 상류 하류 유역 정보가 설정 되지 않아서 호출

2270 self.SelectWsCombobox()

2271

2272 # 콤보 박스에 유역 설정 하기

2273

2274 def Set_Watershed_combo(self):

2275 WS_list = []

2276 wscount = self._wsinfo.WScount

2277 AllItem = self._wsinfo.WSIDsAll

2278 for i in range(wscount):

2279 WS_list.append(str(AllItem[i]))

2280 WS_list.sort()

2281

2282 self.cb_selectws.clear()

2283 self.cb_selectws.addItems(WS_list)

2284

2285 def Set_MostDownStream(self):

2286 if self._SubWatershedCount == 0:

2287 templist = []

2288 if len(self._StreamWSID) > 0:

2289 for id in range(len(self._StreamWSID)):

2290 if str(self._StreamWSID[id]) not in templist:

2291 self.SetMostDownStream(self._StreamWSID[id])

2292 templist.append(str(self._StreamWSID[id]))

2293

2294 def chage_UnsturatedType(self):

2295 self.selectText = self.cmbUnsturatedType.currentText()

2296

2297 value = "0.1"

2298 if self.selectText == "Linear":

2299 value = "0.2"

2300 elif self.selectText == "Exponential":

2301 value = "6.4"

2302

2303 self.txtCoefUnsatruatedk.setText(value)

2304 self.txtCoefUnsatruatedk.setEnabled(True)

2305

2306 # 콤보박스 선택시 하류 유역과 상류 유역의 콤보박스에 값 셋팅

2307 def SelectWsCombobox(self):

2308 self.project_use_flag = False

2309 # 2018-01-29 박: Watershed parmeter 함수 호출

2310 # 하류 유역 정보 셋팅

2311 selectWS = self.cb_selectws.currentText()

2312 DownSW = []

2313 Dllresult_Down = self._wsinfo.downStreamWSIDs(int(selectWS))

2314 Dllresult_Down_count = self._wsinfo.downStreamWSCount(int(selectWS))

2315

2316 for i in range(Dllresult_Down_count):

2317 DownSW.append(Dllresult_Down[i])

2318

2319 if len(DownSW) > 0:

2320 self.lisw_DownWS.clear()

2321 for i in range(len(DownSW)):

2322 if DownSW[i] > 0:

2323 item = QListWidgetItem(str(DownSW[i]))

2324 self.lisw_DownWS.addItem(item)

2325 else:

2326 self.lisw_DownWS.clear()

2327

2328 # 상류 유역 정보 셋팅

2329 UPSW = []

2330 Dllresult_UP = self._wsinfo.upStreamWSIDs(int(selectWS))

2331 Dllresult_UP_count = self._wsinfo.upStreamWSCount(int(selectWS))

2332 for i in range(Dllresult_UP_count):

2333 UPSW.append(Dllresult_UP[i])

2334

2335 # UPSW.extend(Dllresult_UP)

2336 if len(UPSW) > 0:

2337 self.lisw_UpWS.clear()

2338 for s in range(len(UPSW)):

2339 if UPSW[s] > 0:

2340 item1 = QListWidgetItem(str(UPSW[s]))

2341 self.lisw_UpWS.addItem(item1)

2342 else:

2343 self.lisw_UpWS.clear()

2344

2345 try:

2346 # global self._wsinfo

2347 # 콤보박스에서 받은 내용을 텍스트 박스에 넣는 방법

2348 sws_dict = self._wsinfo.subwatershedPars(int(selectWS))

2349

2350 iniSaturation = str(ex_to_float(sws_dict.iniSaturation))

2351 minSlopeOF = str(ex_to_float(sws_dict.minSlopeOF))

2352 minSlopeChBed = str(ex_to_float(sws_dict.minSlopeChBed))

2353

2354 # 2018-03-12 박: 화면 수정

2355 UKType = int(sws_dict.unSatKType)

2356 coefUK = str(ex_to_float(sws_dict.coefUnsaturatedK))

2357 interceptMethodType = int(sws_dict.interceptMethod)

2358 potentialETMethodType = int(sws_dict.potentialETMethod)

2359 snowMeltMethodType = int(sws_dict.snowMeltMethod)

2360

2361 minChBaseWidth = str(ex_to_float(sws_dict.minChBaseWidth))

2362 chRoughness = str(ex_to_float(sws_dict.chRoughness))

2363 dryStreamOrder = str(sws_dict.dryStreamOrder)

2364 ccLCRoughness = str(ex_to_float(sws_dict.ccLCRoughness))

2365 ccSoilDepth = str(ex_to_float(sws_dict.ccSoilDepth))

2366 ccPorosity = str(ex_to_float(sws_dict.ccPorosity))

2367 ccWFSuctionHead = str(ex_to_float(sws_dict.ccWFSuctionHead))

2368 ccHydraulicK = str(ex_to_float(sws_dict.ccHydraulicK))

2369 iniFlow = str(ex_to_float(sws_dict.iniFlow))

2370 if iniFlow.upper() == "NONE":

2371 iniFlow = "0"

2372 etCoeff = str(ex_to_float(sws_dict.etCoeff))

2373 TempSnowRain = str(ex_to_float(sws_dict.tempSnowRain))

2374 smeltingTemp = str(ex_to_float(sws_dict.smeltingTemp))

2375 snowCovRatio = str(ex_to_float(sws_dict.snowCovRatio))

2376 smeltCoef = str(ex_to_float(sws_dict.smeltCoef))

2377

2378 self.txtIniSaturation.setText(iniSaturation)

2379 self.txtMinSlopeOF.setText(minSlopeOF)

2380 self.txtMinSlopeChBed.setText(minSlopeChBed)

2381 self.txtMinChBaseWidth.setText(str(minChBaseWidth))

2382 self.txtIniFlow.setText(str(iniFlow))

2383 self.txtChRoughness.setText(chRoughness)

2384 self.txtDryStreamOrder.setText(dryStreamOrder)

2385 self.txtCalCoefLCRoughness.setText(ccLCRoughness)

2386 self.txtCalCoefSoilDepth.setText(ccSoilDepth)

2387 self.txtCalCoefPorosity.setText(ccPorosity)

2388 self.txtCalCoefWFSuctionHead.setText(ccWFSuctionHead)

2389 self.txtCalCoefHydraulicK.setText(ccHydraulicK)

2390 self.txtETCoef.setText(etCoeff)

2391 self.txtTempSnowRain.setText(TempSnowRain)

2392 self.txtSnowmeltingTemp.setText(smeltingTemp)

2393 self.txtSnowCovRatio.setText(snowCovRatio)

2394 self.txtSnowmeltCoef.setText(smeltCoef)

2395

2396 self.txtCoefUnsatruatedk.setDisabled(bool(UKType < 0 or UKType > 2))

2397 UKType = UKType if 0 <= UKType and UKType < 3 else 1

2398 self.cmbUnsturatedType.setCurrentIndex(UKType)

2399 interceptMethod_index = self.cmbInterceptionMethodType.findData(

2400 interceptMethodType

2401 )

2402 self.cmbInterceptionMethodType.setCurrentIndex(interceptMethod_index)

2403 potentialETMethodType_index = self.cmbPETMethodType.findData(

2404 potentialETMethodType

2405 )

2406 self.cmbPETMethodType.setCurrentIndex(potentialETMethodType_index)

2407 snowMeltMethodType_index = self.cmbSnowmeltMethodType.findData(

2408 snowMeltMethodType

2409 )

2410 self.cmbSnowmeltMethodType.setCurrentIndex(snowMeltMethodType_index)

2411

2412 self.txtCoefUnsatruatedk.setText(coefUK)

2413

2414 # 예외가 발생했을때 예외 값을 셋팅

2415 except Exception as e:

2416 self.txtIniSaturation.setText("0.9")

2417 self.txtMinSlopeOF.setText("0.0001")

2418 self.txtMinSlopeChBed.setText("0.0001")

2419

2420 intAll = float(self.GridCellSize)

2421 if intAll > 0:

2422 cal_MinChBaseWidth = intAll / 10

2423 self.txtMinChBaseWidth.setText(str(cal_MinChBaseWidth))

2424 self.txtIniFlow.setText("0")

2425

2426 self.cmbUnsturatedType.setCurrentIndex(0)

2427 self.txtCoefUnsatruatedk.setText("0.2")

2428

2429 self.txtChRoughness.setText("0.045")

2430 self.txtDryStreamOrder.setText("0")

2431 self.txtCalCoefLCRoughness.setText("1")

2432 self.txtCalCoefSoilDepth.setText("1")

2433 self.txtCalCoefPorosity.setText("1")

2434 self.txtCalCoefWFSuctionHead.setText("1")

2435 self.txtCalCoefHydraulicK.setText("1")

2436 InterceptionMethod_None_index = self.cmbInterceptionMethodType.findData(10)

2437 self.cmbInterceptionMethodType.setCurrentIndex(

2438 InterceptionMethod_None_index

2439 )

2440 PETMethod_None_index = self.cmbPETMethodType.findData(10)

2441 self.cmbPETMethodType.setCurrentIndex(PETMethod_None_index)

2442 self.txtETCoef.setText("1")

2443 SnowmeltMethod_None_index = self.cmbSnowmeltMethodType.findData(10)

2444 self.cmbSnowmeltMethodType.setCurrentIndex(SnowmeltMethod_None_index)

2445 self.txtTempSnowRain.setText("1")

2446 self.txtSnowmeltingTemp.setText("1")

2447 self.txtSnowCovRatio.setText("1")

2448 self.txtSnowmeltCoef.setText("1")

2449 item1 = QListWidgetItem(str(self._StreamWSID))

2450 self.lisw_UserSet.addItem(item1)

2451

2452 def UserSet_Add(self):

2453 id = int(self.cb_selectws.currentText())

2454 items = self.lisw_UserSet.findItems(str(id), Qt.MatchExactly)

2455 if len(items) == 0:

2456 item1 = QListWidgetItem(str(id))

2457 self.lisw_UserSet.addItem(item1)

2458

2459 IniSaturation = self.txtIniSaturation.text()

2460 MinSlopeOF = self.txtMinSlopeOF.text()

2461 MinSlopeChBed = self.txtMinSlopeChBed.text()

2462 IniFlow = self.txtIniFlow.text()

2463

2464 UnsaturatedKType_int = self.cmbUnsturatedType.currentIndex()

2465

2466 MinChBaseWidth = self.txtMinChBaseWidth.text()

2467 CoefUnsatruatedk = self.txtCoefUnsatruatedk.text()

2468 ChRoughness = self.txtChRoughness.text()

2469 DryStreamOrder = self.txtDryStreamOrder.text()

2470 CalCoefLCRoughness = self.txtCalCoefLCRoughness.text()

2471 CalCoefSoilDepth = self.txtCalCoefSoilDepth.text()

2472 CalCoefPorosity = self.txtCalCoefPorosity.text()

2473 CalCoefWFSuctionHead = self.txtCalCoefWFSuctionHead.text()

2474 CalCoefHydraulicK = self.txtCalCoefHydraulicK.text()

2475

2476 if self.chkInterception.isChecked():

2477 interceptMethod = self.cmbInterceptionMethodType.currentData()

2478 else:

2479 interceptMethod = self.cmbInterceptionMethodType.itemData(

2480 self.cmbInterceptionMethodType.findText("None")

2481 )

2482

2483 if self.chkEvapotranspiration.isChecked():

2484 potentialETMethod = self.cmbPETMethodType.currentData()

2485 etCoeff = self.txtETCoef.text()

2486 else:

2487 potentialETMethod = self.cmbPETMethodType.itemData(

2488 self.cmbPETMethodType.findText("None")

2489 )

2490 etCoeff = "0"

2491

2492 if self.chkSnowMelt.isChecked():

2493 snowMeltMethod = self.cmbSnowmeltMethodType.currentData()

2494 tempSnowRain = self.txtTempSnowRain.text()

2495 smeltingTemp = self.txtSnowmeltingTemp.text()

2496 snowCovRatio = self.txtSnowCovRatio.text()

2497 smeltCoef = self.txtSnowmeltCoef.text()

2498 else:

2499 snowMeltMethod = self.cmbSnowmeltMethodType.itemData(

2500 self.cmbSnowmeltMethodType.findText("None")

2501 )

2502 tempSnowRain = "0"

2503 smeltingTemp = "0"

2504 snowCovRatio = "0"

2505 smeltCoef = "0"

2506

2507 try:

2508 self._wsinfo.setOneSWSParsAndUpdateAllSWSUsingNetwork(

2509 id,

2510 float(IniSaturation),

2511 float(MinSlopeOF),

2512 int(UnsaturatedKType_int),

2513 float(CoefUnsatruatedk),

2514 float(MinSlopeChBed),

2515 float(MinChBaseWidth),

2516 float(ChRoughness),

2517 int(DryStreamOrder),

2518 float(CalCoefLCRoughness),

2519 float(CalCoefPorosity),

2520 float(CalCoefWFSuctionHead),

2521 float(CalCoefHydraulicK),

2522 float(CalCoefSoilDepth),

2523 int(interceptMethod),

2524 int(potentialETMethod),

2525 float(etCoeff),

2526 int(snowMeltMethod),

2527 float(tempSnowRain),

2528 float(smeltingTemp),

2529 float(snowCovRatio),

2530 float(smeltCoef),

2531 float(IniFlow),

2532 )

2533 MsInfo("Apply parameter was completed")

2534 except Exception as e:

2535 MsError(f"Apply parameter was not completed! {e}")

2536

2537 # 사용자 정의 제거 함수

2538 def UserSet_remove(self):

2539 id = self.cb_selectws.currentText()

2540 comboindex = self.cb_selectws.currentIndex()

2541

2542 if id in self._StreamWSID:

2543 MsError("Most downstream watershed parameters can not be removed.")

2544

2545 else:

2546 result = self._wsinfo.removeUserParametersSetting(int(id))

2547 items = self.lisw_UserSet.findItems(id, Qt.MatchFixedString)

2548

2549 if result and items:

2550 index = self.lisw_UserSet.row(items[0])

2551 self.lisw_UserSet.takeItem(index)

2552 MsInfo("Remove parameter was completed")

2553

2554 # 변경된 값을 다시 표출하기.

2555 self.SelectWsCombobox()

2556

2557 def SetWatershedstream(self):

2558 self.ID = []

2559 self.IniSaturation = []

2560 self.MinSlopeOF = []

2561 self.MinSlopeChBed = []

2562 self.MinChBaseWidth = []

2563 self.ChRoughness = []

2564 self.DryStreamOrder = []

2565 self.IniFlow = []

2566 self.CalCoefLCRoughness = []

2567 self.CalCoefPorosity = []

2568 self.CalCoefWFSuctionHead = []

2569 self.CalCoefHydraulicK = []

2570 self.CalCoefSoilDepth = []

2571 self.UserSet = []

2572 self.UnsaturatedKType = []

2573 self.CoefUnsaturatedK = []

2574 InterceptionMethod = []

2575 PETMethod = []

2576 ETCoef = []

2577 SnowmeltMethod = []

2578 TempSnowRain = []

2579 SnowmeltingTemp = []

2580 SnowCovRatio = []

2581 SnowmeltCoef = []

2582 doc = ET.parse(self.ProjectFile)

2583 root = doc.getroot()

2584 # 최하류 유역 Id 값

2585 try:

2586 if self._SubWatershedCount == 0:

2587 intAll = float(self.GridCellSize)

2588 cal_MinChBaseWidth = 0

2589

2590 if intAll > 0:

2591 cal_MinChBaseWidth = intAll / 10

2592

2593 for id in self._StreamWSID:

2594 self._wsinfo.setOneSWSParsAndUpdateAllSWSUsingNetwork(

2595 int(id),

2596 0.9,

2597 0.0001,

2598 1,

2599 0.2,

2600 0.0001,

2601 float(cal_MinChBaseWidth),

2602 0.045,

2603 0,

2604 1,

2605 1,

2606 1,

2607 1,

2608 1,

2609 1,

2610 2,

2611 1,

2612 1,

2613 0,

2614 1,

2615 1,

2616 1,

2617 0,

2618 )

2619

2620 item1 = QListWidgetItem(str(id))

2621 self.lisw_UserSet.addItem(item1)

2622

2623 return

2624

2625 xmltoDict = self._xmltodict["GRMProject"]["SubWatershedSettings"]

2626 if self._SubWatershedCount == 1:

2627 xmltoDict = [xmltoDict]

2628

2629 for i, watershed in enumerate(xmltoDict):

2630 self.ID.append(str(watershed["ID"]))

2631 self.IniSaturation.append(watershed["IniSaturation"])

2632 self.MinSlopeOF.append(watershed["MinSlopeOF"])

2633 self.MinSlopeChBed.append(watershed["MinSlopeChBed"])

2634 self.MinChBaseWidth.append(watershed["MinChBaseWidth"])

2635 self.ChRoughness.append(watershed["ChRoughness"])

2636 self.DryStreamOrder.append(watershed["DryStreamOrder"])

2637 self.IniFlow.append(watershed["IniFlow"])

2638

2639 self.CoefUnsaturatedK.append(watershed["CoefUnsaturatedK"])

2640 self.CalCoefLCRoughness.append(watershed["CalCoefLCRoughness"])

2641 self.CalCoefPorosity.append(watershed["CalCoefPorosity"])

2642 self.CalCoefWFSuctionHead.append(watershed["CalCoefWFSuctionHead"])

2643 self.CalCoefHydraulicK.append(watershed["CalCoefHydraulicK"])

2644 self.CalCoefSoilDepth.append(watershed["CalCoefSoilDepth"])

2645 InterceptionMethod.append(watershed["InterceptionMethod"])

2646 PETMethod.append(watershed["PETMethod"])

2647 ETCoef.append(watershed["ETCoef"])

2648 SnowmeltMethod.append(watershed["SnowmeltMethod"])

2649 TempSnowRain.append(watershed["TempSnowRain"])

2650 SnowmeltingTemp.append(watershed["SnowmeltingTemp"])

2651 SnowCovRatio.append(watershed["SnowCovRatio"])

2652 SnowmeltCoef.append(watershed["SnowmeltCoef"])

2653 usersetString = watershed["UserSet"]

2654 self.UserSet.append(usersetString)

2655

2656 self.UnsaturatedKType.append(watershed["UnsaturatedKType"])

2657 UnsaturatedKType_int = 0

2658 # 2020-05-19 박: 기능 추가

2659 UnsaturatedKType = self.UnsaturatedKType[i]

2660 if UnsaturatedKType == "Constant":

2661 UnsaturatedKType_int = 0

2662 elif UnsaturatedKType == "Linear":

2663 UnsaturatedKType_int = 1

2664 elif UnsaturatedKType == "Exponential":

2665 UnsaturatedKType_int = 2

2666

2667 # 2022.02.09 동 : Userset은 UI에서 사용자가 값을 변경하거나, mostdownstream 값일 경우에 True 값이 적용됨.

2668 # Open project시, gmp 파일에 있는 값을 그대로 UI에 출력해야 하나, False인 값들은 dll에서 받아오는 값과 동일해야 정상.

2669 # 아니라면 데이터 파일을 의심하거나, gmp 파일의 오류를 의심해야함.

2670 if (

2671 usersetString.upper() == "TRUE"

2672 or str(self.ID[i]) in self._StreamWSID

2673 ):

2674 self._wsinfo.setOneSWSParsAndUpdateAllSWSUsingNetwork(

2675 int(self.ID[i]),

2676 float(self.IniSaturation[i]),

2677 float(self.MinSlopeOF[i]),

2678 int(UnsaturatedKType_int),

2679 float(self.CoefUnsaturatedK[i]),

2680 float(self.MinSlopeChBed[i]),

2681 float(self.MinChBaseWidth[i]),

2682 float(self.ChRoughness[i]),

2683 int(self.DryStreamOrder[i]),

2684 float(self.CalCoefLCRoughness[i]),

2685 float(self.CalCoefPorosity[i]),

2686 float(self.CalCoefWFSuctionHead[i]),

2687 float(self.CalCoefHydraulicK[i]),

2688 float(self.CalCoefSoilDepth[i]),

2689 int(EnumInterceptionMethod[InterceptionMethod[i]].value),

2690 int(EnumPETMethod[PETMethod[i]].value),

2691 float(ETCoef[i]),

2692 int(EnumSnowMeltMethod[SnowmeltMethod[i]].value),

2693 float(TempSnowRain[i]),

2694 float(SnowmeltingTemp[i]),

2695 float(SnowCovRatio[i]),

2696 float(SnowmeltCoef[i]),

2697 float(self.IniFlow[i]),

2698 )

2699

2700 item1 = QListWidgetItem(str(self.ID[i]))

2701 self.lisw_UserSet.addItem(item1)

2702

2703 except Exception as esd:

2704 MsError(esd)

2705

2706 def SetMostDownStream_combobox(self):

2707 count = self.cb_selectws.count()

2708 for i in range(0, count):

2709 selectWS = self.cb_selectws.itemText(i)

2710

2711 # 2018-07-24 박: 기존 소스

2712 # 목록중에 최하류 셀값 자동으로 선택하게 하는 기능

2713 # 그래서 리스트 목록중에 0번째 있는 목록을 자동으로 선택하게 하였음

2714 if str(selectWS) == str(self._StreamWSID[0]):

2715 self.cb_selectws.setCurrentIndex(i)

2716 return

2717

2718 # ============================ Flow Control 탭 시작 ===============================================

2719 def Set_FlowControl_tab_default(self):

2720 try:

2721 # 테이블 셀값을 변경 불가능 하게 설정

2722 self.tlbFlowControl.setEditTriggers(QAbstractItemView.NoEditTriggers)

2723 # 테이블에 초기 셋팅

2724 self.FlowControlTableSetting()

2725 # 테이블에 값 셋팅후 화면에 점 표시

2726 self.FlowContorGird_paint()

2727 self.btnFlowControl_AddCell.clicked.connect(self.FlowControlAddCell)

2728 self.btnFWCEdit.clicked.connect(self.FlowControlEdit)

2729 self.tlbFlowControl.itemClicked.connect(self.tlbFlowControl_clik_enent)

2730 self.btnFlowRemove.clicked.connect(self.RemoveTalbeRow)

2731 # self.btnfcgotogrid.clicked.connect(self.btnFCGotoGrid)

2732 self.btnfcgotogrid.clicked.connect(

2733 lambda: self.btnGotoGrid(self.tlbFlowControl)

2734 )

2735

2736 except Exception as e:

2737 MsError(e)

2738

2739 # Flow control 테이블 셋팅

2740 # 프로젝트 파일에서 데이터 값이 있으면 테이블에 값을 셋팅

2741 def FlowControlTableSetting(self):

2742 try:

2743 self.tlbFlowControl.setColumnCount(len(self.flowEle))

2744 self.tlbFlowControl.setHorizontalHeaderLabels(self.flowEle)

2745 self.tlbFlowControl.verticalHeader().hide()

2746 pro_file = self.ProjectFile

2747

2748 if self._Flowcontrolgrid_flag == False:

2749 self._FlowControlCount = self._FlowControlCount

2750

2751 if self._FlowControlCount < 1:

2752 return

2753

2754 flowGrid = self._xmltodict["GRMProject"]["FlowControlGrid"]

2755 if self._FlowControlCount == 1:

2756 flowGrid = [flowGrid]

2757

2758 for i, flowItem in enumerate(flowGrid):

2759 self.tlbFlowControl.insertRow(i)

2760 for j, t in enumerate(self.flowEle):

2761 s = ""

2762 if (t in flowItem) and (

2763 flowItem[t] != "ReservoirOperation" or j != 5

2764 ):

2765 s = flowItem[t]

2766 self.tlbFlowControl.setItem(i, j, QTableWidgetItem(s))

2767

2768 except Exception as e:

2769 MsError(e)

2770

2771 # 사용자 추가 입력창 화면

2772 def FlowControlAddCell(self):

2773 if self.tool._FXCOL == 0 and self.tool._FYROW == 0:

2774 self._FXCOL = 0

2775 self._FYROW = 0

2776 MsInfo(" No cells selected. ")

2777 else:

2778 self._FXCOL = self.tool._FXCOL

2779 self._FYROW = self.tool._FYROW

2780 self._AddFlowcontrol_Edit_or_Insert_type = "Insert"

2781 results = AddFlowControl(

2782 self.ProjectFile,

2783 self._AddFlowcontrol_Edit_or_Insert_type,

2784 _DataTimeFormat=self.dataTimeFormat,

2785 )

2786 results.exec_()

2787

2788 self._AddFlowcontrolFilePath = results._AddFlowcontrolFilePath

2789 self._AddFlowcontrolType = results._AddFlowcontrolType

2790 self._AddFlowcontrolTimeInterval = results._AddFlowcontrolTimeInterval

2791 self._AddFlowcontrolName = results._AddFlowcontrolName

2792 self._AddFlowcontrol_Edit_or_Insert_type = (

2793 results._AddFlowcontrol_Edit_or_Insert_type

2794 )

2795 self._AddFlowcontrol_IniStorage = results._AddFlowcontrol_IniStorage

2796 self._AddFlowcontrol_MaxStorage = results._AddFlowcontrol_MaxStorage

2797 self._AddNomalHighStorage = results._AddNomalHighStorage

2798 self._AddRestrictedStorage = results._AddRestrictedStorage

2799 self._AddRetiPeriodSt = results._AddRetiPeriodSt

2800 self._AddRetiPeriodEd = results._AddRetiPeriodEd

2801 self._AddFlowcontrol_ROType = results._AddFlowcontrol_ROType

2802 self._AddFlowcontrol_AutoROMmaxOutflow_CMS = (

2803 results._AddFlowcontrol_AutoROMmaxOutflow_CMS

2804 )

2805 self._AddFlowcontrol_ROConstQ = results._AddFlowcontrol_ROConstQ

2806 self._AddFlowcontrol_ROConstQDuration = (

2807 results._AddFlowcontrol_ROConstQDuration

2808 )

2809 self._EditFlowFlowDataFile = results._EditFlowFlowDataFile

2810

2811 if self._Flowcontrolgrid_flag:

2812 if self._AddFlowcontrol_Edit_or_Insert_type == "Insert":

2813 self.ADDFlowData()

2814 self._Flowcontrolgrid_flag_Insert = False

2815

2816 def ADDFlowData(self):

2817 try:

2818 counts = self.tlbFlowControl.rowCount()

2819 if self._FXCOL != 0 and self._FYROW != 0:

2820 self.tlbFlowControl.insertRow(counts)

2821 self.tlbFlowControl.setItem(

2822 counts, 0, QTableWidgetItem(self._AddFlowcontrolName)

2823 )

2824 self.tlbFlowControl.setItem(

2825 counts, 1, QTableWidgetItem(str(self._FYROW))

2826 )

2827 self.tlbFlowControl.setItem(

2828 counts, 2, QTableWidgetItem(str(self._FXCOL))

2829 )

2830

2831 self._FXCOL = 0

2832 self._FYROW = 0

2833 self.tlbFlowControl.setItem(

2834 counts, 3, QTableWidgetItem(self._AddFlowcontrolTimeInterval)

2835 )

2836 self.tlbFlowControl.setItem(

2837 counts, 4, QTableWidgetItem(self._AddFlowcontrolType)

2838 )

2839 self.tlbFlowControl.setItem(

2840 counts, 5, QTableWidgetItem(self._AddFlowcontrolFilePath)

2841 )

2842 self.tlbFlowControl.setItem(

2843 counts, 6, QTableWidgetItem(self._AddFlowcontrol_IniStorage)

2844 )

2845 self.tlbFlowControl.setItem(

2846 counts, 7, QTableWidgetItem(self._AddFlowcontrol_MaxStorage)

2847 )

2848 self.tlbFlowControl.setItem(

2849 counts, 8, QTableWidgetItem(self._AddNomalHighStorage)

2850 )

2851 self.tlbFlowControl.setItem(

2852 counts, 9, QTableWidgetItem(self._AddRestrictedStorage)

2853 )

2854 self.tlbFlowControl.setItem(

2855 counts, 10, QTableWidgetItem(self._AddRetiPeriodSt)

2856 )

2857 self.tlbFlowControl.setItem(

2858 counts, 11, QTableWidgetItem(self._AddRetiPeriodEd)

2859 )

2860 self.tlbFlowControl.setItem(

2861 counts, 12, QTableWidgetItem(self._AddFlowcontrol_ROType)

2862 )

2863 self.tlbFlowControl.setItem(

2864 counts,

2865 13,

2866 QTableWidgetItem(self._AddFlowcontrol_AutoROMmaxOutflow_CMS),

2867 )

2868 self.tlbFlowControl.setItem(

2869 counts, 14, QTableWidgetItem(self._AddFlowcontrol_ROConstQ)

2870 )

2871 self.tlbFlowControl.setItem(

2872 counts, 15, QTableWidgetItem(self._AddFlowcontrol_ROConstQDuration)

2873 )

2874

2875 self._Flowcontrolgrid_flag = True

2876 self.UpdateFlowControl()

2877

2878 # 테이블에 값 셋팅후 화면에 점 표시

2879 if self.chkFlowContorGird.isChecked():

2880 self.FlowContorGird_paint()

2881 except Exception as e:

2882 MsError(e)

2883

2884 def FlowControlEdit(self):

2885 self._FlowControlTable = self.tlbFlowControl

2886 row = self.tlbFlowControl.currentRow()

2887 self._EditFlowCurrentRow = row

2888 if row > -1:

2889 self._EditFlowName = self.tlbFlowControl.item(row, 0).text()

2890 self._EditFlowColX = self.tlbFlowControl.item(row, 1).text()

2891 self._EditFlowRowY = self.tlbFlowControl.item(row, 2).text()

2892 self._EditFlowDT = self.tlbFlowControl.item(row, 3).text()

2893 self._EditFlowControlType = self.tlbFlowControl.item(row, 4).text()

2894 self._EditFlowFlowDataFile = self.tlbFlowControl.item(row, 5).text()

2895 self._EditFlowIniStorage = self.tlbFlowControl.item(row, 6).text()

2896 self._EditFlowMaxStorage = self.tlbFlowControl.item(row, 7).text()

2897 self._EditNomalHighStorage = self.tlbFlowControl.item(row, 8).text()

2898 self._EditRestrictedStorage = self.tlbFlowControl.item(row, 9).text()

2899 self._EditRetiPeriodSt = self.tlbFlowControl.item(row, 10).text()

2900 self._EditRetiPeriodEd = self.tlbFlowControl.item(row, 11).text()

2901 self._EditFlowROType = self.tlbFlowControl.item(row, 12).text()

2902 self._EditFlowAutoROMmaxOutflow_CMS = self.tlbFlowControl.item(

2903 row, 13

2904 ).text()

2905 self._EditFlowROConstQ = self.tlbFlowControl.item(row, 14).text()

2906 self._EditFlowROConstQDuration = self.tlbFlowControl.item(row, 15).text()

2907

2908 self.flowEle

2909 self._AddFlowcontrol_Edit_or_Insert_type = "Edit"

2910 self._FlowControlCount = self._FlowControlCount

2911 results = AddFlowControl(

2912 self.ProjectFile,

2913 self._AddFlowcontrol_Edit_or_Insert_type,

2914 self._EditFlowName,

2915 self._EditFlowDT,

2916 self._EditFlowControlType,

2917 self._EditFlowFlowDataFile,

2918 self._EditFlowIniStorage,

2919 self._EditFlowMaxStorage,

2920 self._EditNomalHighStorage,

2921 self._EditRestrictedStorage,

2922 self._EditRetiPeriodSt,

2923 self._EditRetiPeriodEd,

2924 self._EditFlowROType,

2925 self._EditFlowAutoROMmaxOutflow_CMS,

2926 self._EditFlowROConstQ,

2927 self._EditFlowROConstQDuration,

2928 self.dataTimeFormat,

2929 )

2930 results.exec_()

2931

2932 self._FlowControlTable.setItem(

2933 row, 0, QTableWidgetItem(results._EditFlowName)

2934 )

2935 self._FlowControlTable.setItem(

2936 row, 3, QTableWidgetItem(results._EditFlowDT)

2937 )

2938 self._FlowControlTable.setItem(

2939 row, 4, QTableWidgetItem(results._EditFlowControlType)

2940 )

2941 self._FlowControlTable.setItem(

2942 row, 5, QTableWidgetItem(results._EditFlowFlowDataFile)

2943 )

2944 self._FlowControlTable.setItem(

2945 row, 6, QTableWidgetItem(results._EditFlowIniStorage)

2946 )

2947 self._FlowControlTable.setItem(

2948 row, 7, QTableWidgetItem(results._EditFlowMaxStorage)

2949 )

2950 self._FlowControlTable.setItem(

2951 row, 8, QTableWidgetItem(results._EditNomalHighStorage)

2952 )

2953 self._FlowControlTable.setItem(

2954 row, 9, QTableWidgetItem(results._EditRestrictedStorage)

2955 )

2956 self._FlowControlTable.setItem(

2957 row, 10, QTableWidgetItem(results._EditRetiPeriodSt)

2958 )

2959 self._FlowControlTable.setItem(

2960 row, 11, QTableWidgetItem(results._EditRetiPeriodEd)

2961 )

2962 self._FlowControlTable.setItem(

2963 row, 12, QTableWidgetItem(results._EditFlowROType)

2964 )

2965 self._FlowControlTable.setItem(

2966 row, 13, QTableWidgetItem(results._EditFlowAutoROMmaxOutflow_CMS)

2967 )

2968 self._FlowControlTable.setItem(

2969 row, 14, QTableWidgetItem(results._EditFlowROConstQ)

2970 )

2971 self._FlowControlTable.setItem(

2972 row, 15, QTableWidgetItem(results._EditFlowROConstQDuration)

2973 )

2974

2975 self.UpdateFlowControl()

2976

2977 else:

2978 MsInfo("Check! select row ")

2979

2980 def UpdateFlowControl(self):

2981 # 딕셔너리 삭제

2982 if self._FlowControlCount > 0:

2983 del self._xmltodict["GRMProject"]["FlowControlGrid"]

2984 DictoXml = unparse(self._xmltodict)

2985

2986 ET.register_namespace("", "http://tempuri.org/GRMProject.xsd")

2987 xmltree = ET.ElementTree(ET.fromstring(DictoXml))

2988 root = xmltree.getroot()

2989 count = self.tlbFlowControl.rowCount()

2990 self._FlowControlCount = count

2991

2992 for row in range(0, self._FlowControlCount):

2993 child = ET.Element("FlowControlGrid")

2994 root.append(child)

2995

2996 for i in range(len(self.flowEle)):

2997 element = ET.Element(self.flowEle[i])

2998 item = self.tlbFlowControl.item(row, i)

2999 element.text = item.text() if item else ""

3000 child.append(element)

3001

3002 xmltree_string = ET.tostring(xmltree.getroot())

3003 docs = dict(parse(xmltree_string))

3004 self._xmltodict.clear()

3005 self._xmltodict.update(docs)

3006

3007 def tlbFlowControl_clik_enent(self):

3008 global _ClickX, _ClickY

3009 row = self.tlbFlowControl.currentRow()

3010 _ClickX = self.tlbFlowControl.item(row, 1).text()

3011 _ClickY = self.tlbFlowControl.item(row, 2).text()

3012

3013 def RemoveTalbeRow(self):

3014 row = self.tlbFlowControl.currentIndex().row()

3015 # 선택된 Row 가 있을때

3016 if row > -1:

3017 mess = "Are you sure you want to delete the selected items?"

3018 result = QMessageBox.question(

3019 None, "Flow Control Grid", mess, QMessageBox.Yes, QMessageBox.No

3020 )

3021 if result == QMessageBox.Yes:

3022 # 사용자가 한번이라도 수정한 사항이 있으면 플래그값 True 로 변경하여 사용자 수정

3023 _Flowcontrolgrid_flag = True

3024 self.tlbFlowControl.removeRow(row)

3025

3026 self.UpdateFlowControl()

3027 # 테이블에 값 셋팅후 화면에 점 표시

3028

3029 self.post_grid_remove2()

3030 self.FlowContorGird_paint()

3031 if self.chkWatch_Point.isChecked():

3032 self.watchpoint_paint()

3033

3034 # 2. xy좌표로

3035 def xy_grid(self, layer, xcoord, ycoord):

3036 try:

3037 xc = float(xcoord)

3038 yc = float(ycoord)

3039 row = int(((self._ymax - yc) / self._ysize))

3040 column = int(((xc - self._xmin) / self._xsize))

3041 self.lblColRow.setText("xCol, yRow:" + str(column) + " , " + str(row))

3042 if row < 0 or column < 0 or self._height <= column or self._width <= row:

3043 row = "out of extent"

3044 column = "out of extent"

3045 MsInfo("{0}, {1}".format(str(column), str(row)))

3046 else:

3047 self.tool.Cell_X_Center = (

3048 self._xmin + self._xsize / 2 + self._xsize * (column)

3049 )

3050 self.tool.Cell_Y_Center = (

3051 self._ymax - self._ysize / 2 - self._ysize * (row)

3052 ) # (extent.yMinimum())

3053 if (

3054 self.tool.Cell_X_Center <= self._xmax

3055 or self._xmin <= self.tool.Cell_X_Center

3056 or self.tool.Cell_Y_Center <= self._ymax

3057 or self._ymin <= self.tool.Cell_Y_Center

3058 ):

3059 self.draw_grid(self.tool.Cell_X_Center, self.tool.Cell_Y_Center)

3060 except Exception as e:

3061 MsError(e)

3062

3063

3064 class CanvasTool(QgsMapTool):

3065 def __init__(self, canvas):

3066 QgsMapTool.__init__(self, canvas)

3067 self.canvas = canvas

3068 self.layer = self.canvas.layers()[0]

3069 self._wsinfo = _get_set_control.get_wsinfo()

3070 self._GreenAmptCount = _get_set_control.get_GreenAmptCount()

3071 self._xmltodict = _get_set_control.get_xmltodict()

3072 self._SoilDepthCount = _get_set_control.get_SoilDepthCount()

3073 self._LandCoverCount = _get_set_control.get_LandCoverCount()

3074 self._FYROW = 0

3075 self._YROW = 0

3076 self._FXCOL = 0

3077 self._XCOL = 0

3078

3079 self._width = self.layer.width()

3080 self._height = self.layer.height()

3081 self._xsize = self.layer.rasterUnitsPerPixelX()

3082 self._ysize = self.layer.rasterUnitsPerPixelY()

3083 self._extent = self.layer.extent()

3084 self._ymax = self._extent.yMaximum()

3085 self._ymin = self._extent.yMinimum()

3086 self._xmax = self._extent.xMaximum()

3087 self._xmin = self._extent.xMinimum()

3088 self.Cell_X_Center = 0

3089 self.Cell_Y_Center = 0

3090

3091 def scale_changed(self):

3092 self.canvas.scaleChanged.connect(self.scale_change_marker)

3093

3094 def scale_changed_disconnect(self):

3095 try:

3096 self.canvas.scaleChanged.disconnect(self.scale_change_marker)

3097 except:

3098 pass

3099

3100 # canvas scale이 변화할 때 marker를 새로 그림

3101 def scale_change_marker(self):

3102 if self.Cell_X_Center != 0 and self.Cell_Y_Center != 0:

3103 self.post_vertex_remove()

3104 self.create_vertex(self.Cell_X_Center, self.Cell_Y_Center)

3105

3106 # 이전에 생성한 vertexMaker제거 함

3107 def post_vertex_remove(self):

3108 for v in self.canvas.scene().items():

3109 if issubclass(type(v), QgsVertexMarker):

3110 self.canvas.scene().removeItem(v)

3111

3112 def create_vertex(self, x, y):

3113 marker = QgsVertexMarker(self.canvas)

3114 marker.setCenter(QgsPointXY(x, y))

3115 marker.setColor(QColor(255, 0, 0))

3116 width_Map = self.canvas.extent().xMaximum() - self.canvas.extent().xMinimum()

3117 Size_Marker = (self._xsize / 150.0) * 100000 / width_Map

3118 marker.setIconSize(Size_Marker)

3119 marker.setIconType(QgsVertexMarker.ICON_BOX)

3120 marker.setPenWidth(1)

3121

3122 def getCVID(self, Rt, Ct):

3123 cvid_v = 0

3124 for c in range(self._width):

3125 for r in range(Ct):

3126 xxx = c * self._xsize + self._xmin

3127 yyy = self._ymax - r * self._ysize

3128 ident = self.layer.dataProvider().identify(

3129 QgsPointXY(xxx, yyy), QgsRaster.IdentifyFormatValue

3130 )

3131

3132 # 2020-01-28 박: 변경은 했으나 맞는지 확인이 안됨

3133 if ident.results()[1] != None and ident.results()[1] > 0:

3134 cvid_v = cvid_v + 1

3135

3136 cvid = 0

3137 for cs in range(Rt + 1):

3138 for rs in range(Ct, Ct + 1):

3139 xxx = cs * self._xsize + self._xmin

3140 yyy = self._ymax - rs * self._ysize

3141 ident = self.layer.dataProvider().identify(

3142 QgsPointXY(xxx, yyy), QgsRaster.IdentifyFormatValue

3143 )

3144

3145 # 2020-01-28 박: 변경은 했으나 맞는지 확인이 안됨

3146 if ident.results()[1] != None and ident.results()[1] > 0:

3147 cvid = cvid + 1

3148 return cvid_v + cvid

3149

3150 # 캔버스 클릭 이벤트 좌표 출력

3151 def canvasPressEvent(self, event):

3152 xx = event.pos().x()

3153 yy = event.pos().y()

3154

3155 point = self.canvas.getCoordinateTransform().toMapCoordinates(xx, yy)

3156 if self.layer is not None:

3157 row, column = self.Point_To_RowColumn(point)

3158 _CVID = "Cvid: " + str(self.getCVID(row, column))

3159 self._XCOL = column

3160 self._YROW = row

3161

3162 self._FYROW = self._YROW

3163 self._FXCOL = self._XCOL

3164 text = "xCol, yRow: " + str(row) + " , " + str(column)

3165

3166 # 2020-01-28 박: 텍스트 박스 객체 넘기는게 되는지 모르겠음

3167 _get_set_control.GlobalLabel_SetText(text)

3168

3169 self.Input_Cell_Value(row, column)

3170 if row < 0 or column < 0 or self._height <= column or self._width <= row:

3171 row = "out of extent"

3172 column = "out of extent"

3173

3174 else:

3175 self.Cell_X_Center = (

3176 self._extent.xMinimum() + self._xsize / 2 + self._xsize * (row)

3177 )

3178 self.Cell_Y_Center = (

3179 self._ymax - self._ysize / 2 - self._ysize * (column)

3180 )

3181

3182 FAc_ident = self.layer.dataProvider().identify(

3183 QgsPointXY(self.Cell_X_Center, self.Cell_Y_Center),

3184 QgsRaster.IdentifyFormatValue,

3185 )

3186 cw_text = self.channel_width_cal(FAc_ident.results()[1])

3187

3188 self._Cnavas_Click_X = self.Cell_X_Center

3189 self._Cnavas_Click_Y = self.Cell_Y_Center

3190 if (

3191 self.Cell_X_Center <= self._xmax

3192 or self._xmin <= self.Cell_X_Center

3193 or self.Cell_Y_Center <= self._ymax

3194 or self._ymin <= self.Cell_Y_Center

3195 ):

3196 self.post_vertex_remove()

3197 self.create_vertex(self.Cell_X_Center, self.Cell_Y_Center)

3198

3199 else:

3200 row = "no raster"

3201 column = "no raster"

3202 MsInfo("{0}, {1}".format(str(row), str(column)))

3203

3204 def Input_Cell_Value(self, x, y):

3205 # Cell Info Flow 그룹 박스 데이터 내용

3206 CellCount = self._wsinfo.cellCountInWatershed

3207 CellType_Result = self._wsinfo.cellFlowTypeACell(x, y)

3208 Stream_Result = self._wsinfo.streamValue(x, y)

3209 FD_Result = self._wsinfo.flowDirection(x, y)

3210 FA_Result = self._wsinfo.flowAccumulation(x, y)

3211 Slop_Result = self._wsinfo.slope(x, y)

3212 watershed = self._wsinfo.watershedID(x, y)

3213

3214 _get_set_control.GlobalControl_SetValue(

3215 str(CellCount),

3216 str(CellType_Result.decode("utf-8")),

3217 str(Stream_Result),

3218 FD_Result.decode("utf-8"),

3219 str(FA_Result),

3220 str(Slop_Result),

3221 str(watershed),

3222 )

3223

3224 Texture_Result = self._wsinfo.soilTextureValue(x, y)

3225

3226 # Cell Info Depth 그룹 박스 테이터 내용

3227 Depth_Result = self._wsinfo.soilDepthValue(x, y)

3228

3229 # Cell Info Landcover 그룹 박스 테이터 내용

3230 Landcover_Result = self._wsinfo.landCoverValue(x, y)

3231

3232 # 메모리에서 불러오는 것으로 변경 해야함 우선은 진행

3233 if self._GreenAmptCount > 1:

3234 for GreenAmpt in self._xmltodict["GRMProject"]["GreenAmptParameter"]:

3235 GridValue = GreenAmpt["GridValue"]

3236 if str(Texture_Result) == GridValue:

3237 GRMCode = GreenAmpt["GRMCode"]

3238 Porosity = GreenAmpt["Porosity"]

3239 EffectivePorosity = GreenAmpt["EffectivePorosity"]

3240 WFSoilSuctionHead = GreenAmpt["WFSoilSuctionHead"]

3241 HydraulicConductivity = GreenAmpt["HydraulicConductivity"]

3242 _get_set_control.GlobalControl_texture_SetValue(

3243 GridValue,

3244 GRMCode,

3245 Porosity,

3246 EffectivePorosity,

3247 WFSoilSuctionHead,

3248 HydraulicConductivity,

3249 )

3250 break

3251 elif Texture_Result is None or Texture_Result == "":

3252 break

3253 elif self._GreenAmptCount == 1:

3254 GridValue = self._xmltodict["GRMProject"]["GreenAmptParameter"]["GridValue"]

3255 if str(Texture_Result) == GridValue:

3256 GRMCode = self._xmltodict["GRMProject"]["GreenAmptParameter"]["GRMCode"]

3257 Porosity = self._xmltodict["GRMProject"]["GreenAmptParameter"][

3258 "Porosity"

3259 ]

3260 EffectivePorosity = self._xmltodict["GRMProject"]["GreenAmptParameter"][

3261 "EffectivePorosity"

3262 ]

3263 WFSoilSuctionHead = self._xmltodict["GRMProject"]["GreenAmptParameter"][

3264 "WFSoilSuctionHead"

3265 ]

3266 HydraulicConductivity = self._xmltodict["GRMProject"][

3267 "GreenAmptParameter"

3268 ]["HydraulicConductivity"]

3269 _get_set_control.GlobalControl_texture_SetValue(

3270 GridValue,

3271 GRMCode,

3272 Porosity,

3273 EffectivePorosity,

3274 WFSoilSuctionHead,

3275 HydraulicConductivity,

3276 )

3277

3278 if self._SoilDepthCount > 1:

3279 for SoilDepth in self._xmltodict["GRMProject"]["SoilDepth"]:

3280 GridValue = SoilDepth["GridValue"]

3281 if str(Depth_Result) == GridValue:

3282 GRMCode = SoilDepth["GRMCode"]

3283 # 2020-05-27 박: 변경됨

3284 SoilDepth = SoilDepth["SoilDepth_cm"]

3285 _get_set_control.GlobalControl_Depth_SetValue(

3286 GridValue, GRMCode, SoilDepth

3287 )

3288 break

3289 elif Depth_Result is None or Depth_Result == "":

3290 break

3291

3292 elif self._SoilDepthCount == 1:

3293 GridValue = self._xmltodict["GRMProject"]["SoilDepth"]["GridValue"]

3294 if str(Depth_Result) == GridValue:

3295 GRMCode = self._xmltodict["GRMProject"]["SoilDepth"]["GRMCode"]

3296 SoilDepth = self._xmltodict["GRMProject"]["SoilDepth"]["SoilDepth_cm"]

3297 _get_set_control.GlobalControl_Depth_SetValue(

3298 GridValue, GRMCode, SoilDepth

3299 )

3300

3301 if self._LandCoverCount > 1:

3302 for LandCover in self._xmltodict["GRMProject"]["LandCover"]:

3303 GridValue = LandCover["GridValue"]

3304 if str(Landcover_Result) == GridValue:

3305 GRMCode = LandCover["GRMCode"]

3306 RoughnessCoefficient = LandCover["RoughnessCoefficient"]

3307 ImperviousRatio = LandCover["ImperviousRatio"]

3308 CanopyRatio = LandCover["CanopyRatio"]

3309 InterceptionMaxWaterCanopy_mm = LandCover[

3310 "InterceptionMaxWaterCanopy_mm"

3311 ]

3312 _get_set_control.GlobalControl_Landcover_SetValue(

3313 GridValue,

3314 GRMCode,

3315 RoughnessCoefficient,

3316 ImperviousRatio,

3317 CanopyRatio,

3318 InterceptionMaxWaterCanopy_mm,

3319 )

3320 break

3321 elif Landcover_Result is None or Landcover_Result == "":

3322 break

3323

3324 elif self._LandCoverCount == 1:

3325 GridValue = self._xmltodict["GRMProject"]["LandCover"]["GridValue"]

3326 if str(Depth_Result) == GridValue:

3327 GRMCode = self._xmltodict["GRMProject"]["LandCover"]["GRMCode"]

3328 RoughnessCoefficient = self._xmltodict["GRMProject"]["LandCover"][

3329 "RoughnessCoefficient"

3330 ]

3331 ImperviousRatio = self._xmltodict["GRMProject"]["LandCover"][

3332 "ImperviousRatio"

3333 ]

3334 CanopyRatio = self._xmltodict["GRMProject"]["LandCover"]["CanopyRatio"]

3335 InterceptionMaxWaterCanopy_mm = self._xmltodict["GRMProject"][

3336 "LandCover"

3337 ]["InterceptionMaxWaterCanopy_mm"]

3338 _get_set_control.GlobalControl_Landcover_SetValue(

3339 GridValue,

3340 GRMCode,

3341 RoughnessCoefficient,

3342 ImperviousRatio,

3343 CanopyRatio,

3344 InterceptionMaxWaterCanopy_mm,

3345 )

3346

3347 def Point_To_RowColumn(self, point):

3348 column = int(((self._ymax - point.y()) / self._ysize))

3349 row = int(((point.x() - self._xmin) / self._xsize))

3350 return row, column

3351

3352 def canvasMoveEvent(self, event):

3353 x = event.pos().x()

3354 y = event.pos().y()

3355 point = self.canvas.getCoordinateTransform().toMapCoordinates(x, y)

3356

3357 def canvasReleaseEvent(self, event):

3358 # Get the click

3359 x = event.pos().x()

3360 y = event.pos().y()

3361 point = self.canvas.getCoordinateTransform().toMapCoordinates(x, y)

3362

3363 def activate(self):

3364 pass

3365

3366 def deactivate(self):

3367 pass

3368

3369 def isZoomTool(self):

3370 return False

3371

3372 def isTransient(self):

3373 return False

3374

3375 def isEditTool(self):

3376 return True

3377

3378 # canvas event

3379 def ZoomtoExtent(self):

3380 self.canvas.zoomToFullExtent()

3381 self.canvas.refresh()

3382

3383 def ZoomtoNextExtent(self):

3384 self.canvas.zoomToNextExtent()

3385 self.canvas.refresh()

3386

3387 def ZoomtoPrevious(self):

3388 self.canvas.zoomToPreviousExtent()

3389 self.canvas.refresh()

3390

3391 def canvas_zoomIn(self):

3392 actionZoomIn = QAction(self)

3393 self.toolZoomIn = QgsMapToolZoom(self.canvas, False) # false = in

3394 self.toolZoomIn.setAction(actionZoomIn)

3395 self.canvas.setMapTool(self.toolZoomIn)

3396 self.canvas.refresh()

3397

3398 def canvas_zoomOut(self):

3399 actionZoomOut = QAction(self)

3400 self.toolZoomOut = QgsMapToolZoom(self.canvas, True) # True = out

3401 self.toolZoomOut.setAction(actionZoomOut)

3402 self.canvas.setMapTool(self.toolZoomOut)

3403 self.canvas.refresh()

3404

3405 def canvas_pan(self):

3406 actionPan = QAction(self)

3407 self.toolPan = QgsMapToolPan(self.canvas)

3408 self.toolPan.setAction(actionPan)

3409 self.canvas.setMapTool(self.toolPan)

3410

3411 #

3412 # #2017/11/23----------------------

3413 def channel_width_cal(self, FAcvalue):

3414 # mw에서는 line edit 값을 바꿀 수 있고 그에 따라 결과 값이 바뀜. 일단 여기는 이렇세 처리함

3415 c = float(1.698)

3416 d = float(0.318)

3417 e = float(0.5)

3418

3419 # FAc 는 cell 값, Slope는 gmp의 MinSlopeChBed 값임

3420 slope = float(0.0005)

3421

3422 width = (

3423 c

3424 * pow((FAcvalue * (self._xsize * self._xsize / 1000000)), d)

3425 / pow(slope, e)

3426 )

3427 try:

3428 User_Cw = "%.3f" % width

3429 except Exception as e:

3430 return "0"

3431 return str(User_Cw)