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

83_get_set_control = set_Controls()

84_XmlCheck = xmls()

85

86

87 class GRMDialog(QtWidgets.QMainWindow, Ui_MainWindow):

88 closeDialogEvent = pyqtSignal()

89

90 def __init__(

91 self,

92 _xmltodict={},

93 _WatchPointCount=0,

94 _SubWatershedCount=0,

95 _GreenAmptCount=0,

96 _SoilDepthCount=0,

97 _LandCoverCount=0,

98 _FlowControlCount=0,

99 _ChannelSettingsCount=0,

100 parent=None,

101 ):

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

103 self.setupUi(self)

104 self._StreamWSID = []

105 self._wsinfo = None

106 self._Flowcontrolgrid_flag = False

107

108 self._xmltodict = _xmltodict

109 self._WatchPointCount = _WatchPointCount

110 self._SubWatershedCount = _SubWatershedCount

111 self._GreenAmptCount = _GreenAmptCount

112 self._SoilDepthCount = _SoilDepthCount

113 self._LandCoverCount = _LandCoverCount

114 self._FlowControlCount = _FlowControlCount

115 self._ChannelSettingsCount = _ChannelSettingsCount

116 self._Flowcontrolgrid_flag = True

117

118 self.canvasRubberBand = []

119

120 # 2019-12-20 박: 동희 개발 2줄 탭

121 self.qTabBar()

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

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

124

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

126 self.Set_ProjectDataInit()

127

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

129 self.setStyleSheet(css_sheet)

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

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

132

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

134 self.Set_Canvas_Tool_Icon()

135

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

137 self.Set_Canvas_Layer_default()

138

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

140 self.Set_simulation_tab_default()

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

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

143 self.chkWatch_Point.setChecked(True)

144 self.chkFlowContorGird.setChecked(True)

145

146 self.watchpoint()

147

148 self.click_FlowContorGird()

149

150 # WatchPoint 탭 기능 기본값 셋팅

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

152 self.Set_Wathpoint_tab_default()

153

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

155 self.Set_ChannelCS_tab_default()

156

157 # Watershed 탭 기능 기본값 셋팅

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

159 self.Set_Watershed_Parameter_tab_default()

160

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

162 self.Set_FlowControl_tab_default()

163

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

165 self.dockDisableButton()

166

167 _get_set_control.GlobalLabel(self.lblColRow)

168

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

170 _get_set_control.GlobalControl(

171 self.txtCellCount,

172 self.txtCelltype,

173 self.txtStreamValue,

174 self.txtFD,

175 self.txtFA,

176 self.txtSlope,

177 self.txtWatershedID,

178 )

179

180 # Cell info Land cover

181 _get_set_control.GlobalControl_Landcover(

182 self.txtLandGridValue,

183 self.txtLandType,

184 self.txtRoughness,

185 self.txtratio,

186 self.txtCanopyRatio,

187 self.txtInterceptionMaxWaterCanopy,

188 )

189

190 # Cell info Depth

191 _get_set_control.GlobalControl_Depth(

192 self.txtDepthValue, self.txtSoilDepthClass, self.txtSoilDepth

193 )

194

195 # Cell info Texture

196 _get_set_control.GlobalControl_texture(

197 self.txtTextureGridValue,

198 self.txtSoilTexture,

199 self.txtPorosity,

200 self.txtEffectivePorosity,

201 self.txtSuctionhead,

202 self.txtcondcutivity,

203 )

204

205 _get_set_control.set_GreenAmptCount(self._GreenAmptCount)

206 _get_set_control.set_SoilDepthCount(self._SoilDepthCount)

207 _get_set_control.set_LandCoverCount(self._LandCoverCount)

208 _get_set_control.set_xmltodict(self._xmltodict)

209

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

211

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

213 self.Set_Cavas_tool_btn()

214

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

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

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

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

219

220 def Click_StartSimulation(self):

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

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

223 self.SaveProject(False)

224

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

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

227

228 result = Execute(arg)

229

230 msg = "Simulation completed"

231 if result != 1:

232 msg = "Simulation was stopped."

233

234 MsInfo(msg)

235

236 def qTabBar(self):

237 self.firstTab = QTabBar()

238 self.secondTab = QTabBar()

239 layout = QGridLayout()

240 baseLayout = self.centralwidget.layout()

241

242 self.firstTab.addTab("")

243 self.firstTab.addTab("Simulation")

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

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

246

247 self.secondTab.addTab("")

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

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

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

251

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

253 self.secondTab.setExpanding(False)

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

255 self.firstTab.setStyleSheet(style)

256 self.secondTab.setStyleSheet(style)

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

258

259 # layout 세팅

260 # r, c, rspan, cspan

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

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

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

264 layout.setSpacing(0)

265 self.gridLayout_10.setSpacing(0)

266 self.centralwidget.setLayout(layout)

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

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

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

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

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

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

273

274 self.firstTab.setCurrentIndex(1)

275

276 def Set_ProjectDataInit(self):

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

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

279 self.grid_line = {}

280

281 # direction 그리때 사용 변수

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

283 self.flow_direction = {}

284

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

286

287 # 프로젝트 파일 경로 변수 셋팅

288 self.ProjectFile = project_settings["ProjectFile"]

289

290 # watershed Layer file 경로 변수

291 self.LayerPath = project_settings["DomainFile"]

292

293 # simulation Tab 변수

294 self.ComputationalTimeStep = project_settings["ComputationalTimeStep"]

295 self.MaxDegreeOfParallelism = project_settings["MaxDegreeOfParallelism"]

296 self.SimulationDuration = project_settings["SimulationDuration"]

297 self.OutputTimeStep = project_settings["OutputTimeStep"]

298 self.SimulateInfiltration = project_settings["SimulateInfiltration"]

299 self.SimulateSubsurfaceFlow = project_settings["SimulateSubsurfaceFlow"]

300 self.SimulateBaseFlow = project_settings["SimulateBaseFlow"]

301 self.SimulateInterception = project_settings["SimulateInterception"]

302 self.SimulateEvapotranspiration = project_settings["SimulateEvapotranspiration"]

303 self.SimulateSnowMelt = project_settings["SimulateSnowMelt"]

304 self.SimulateFlowControl = project_settings["SimulateFlowControl"]

305 self.IsFixedTimeStep = project_settings["IsFixedTimeStep"]

306 self.SimulationStartingTime = project_settings["SimulationStartingTime"]

307 self.WatershedFile = project_settings["DomainFile"]

308 self.SlopeFile = project_settings["SlopeFile"]

309 self.FlowDirectionFile = project_settings["FlowDirectionFile"]

310 self.FlowAccumFile = project_settings["FlowAccumFile"]

311 self.StreamFile = project_settings["StreamFile"]

312 self.ChannelWidthFile = project_settings["ChannelWidthFile"]

313 self.LandCoverFile = project_settings["LandCoverFile"]

314 self.SoilTextureFile = project_settings["SoilTextureFile"]

315 self.SoilDepthFile = project_settings["SoilDepthFile"]

316 self.InitialChannelFlowFile = project_settings["InitialChannelFlowFile"]

317 self.InitialSoilSaturationRatioFile = project_settings[

318 "InitialSoilSaturationRatioFile"

319 ]

320 self.MakeIMGFile = project_settings["MakeIMGFile"]

321 self.MakeASCFile = project_settings["MakeASCFile"]

322 self.MakeSoilSaturationDistFile = project_settings["MakeSoilSaturationDistFile"]

323 self.MakeRfDistFile = project_settings["MakeRfDistFile"]

324 self.MakeRFaccDistFile = project_settings["MakeRFaccDistFile"]

325 self.MakeFlowDistFile = project_settings["MakeFlowDistFile"]

326 self.PrintOption = project_settings["PrintOption"]

327 self.PrintAveValue = project_settings["PrintAveValue"]

328 self.AveValueTimeInterval_min = project_settings["AveValueTimeInterval_min"]

329 self.WriteLog = project_settings["WriteLog"]

330

331 if self.InitialChannelFlowFile is None:

332 self.InitialChannelFlowFile = ""

333 if self.InitialSoilSaturationRatioFile is None:

334 self.InitialSoilSaturationRatioFile = ""

335 if self.ChannelWidthFile is None:

336 self.ChannelWidthFile = ""

337

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

339 FDType = project_settings["FlowDirectionType"]

340

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

342 self._wsinfo = grmWSinfo(

343 FDType,

344 self.WatershedFile,

345 self.SlopeFile,

346 self.FlowDirectionFile,

347 self.FlowAccumFile,

348 self.StreamFile,

349 self.LandCoverFile,

350 self.SoilTextureFile,

351 self.SoilDepthFile,

352 self.InitialSoilSaturationRatioFile,

353 self.InitialChannelFlowFile,

354 self.ChannelWidthFile,

355 )

356 _get_set_control.set_wsinfo(self._wsinfo)

357 self.GridCellSize = self._wsinfo.cellSize

358

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

360 try:

361 self._StreamWSID = []

362 WSIDs = []

363 WSIDs = self._wsinfo.mostDownStreamWSIDs

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

365 if WSIDs[i] is not None:

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

367 except Exception as e:

368 MsInfo(e)

369

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

371 self.Set_Wathpoint_default_value()

372

373 # ChannelWidth tab 변수

374 self.WSID = []

375 self.CrossSectionType = []

376 self.SingleCSChannelWidthType = []

377 self.ChannelWidthEQc = []

378 self.ChannelWidthEQd = []

379 self.ChannelWidthEQe = []

380 self.ChannelWidthMostDownStream = []

381 self.LowerRegionHeight = []

382 self.LowerRegionBaseWidth = []

383 self.UpperRegionBaseWidth = []

384 self.CompoundCSChannelWidthLimit = []

385 self.BankSideSlopeRight = []

386 self.BankSideSlopeLeft = []

387

388 channelDic = {

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

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

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

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

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

394 "ChannelWidthMostDownStream": [

395 str(self.GridCellSize),

396 self.ChannelWidthMostDownStream,

397 ],

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

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

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

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

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

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

404 }

405

406 if self._ChannelSettingsCount == 0:

407 self.lisw_WSID.clear()

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

409 self._ChannelSettingsCount = len(self._StreamWSID)

410 if self._ChannelSettingsCount > 0:

411 DictoXml = unparse(self._xmltodict)

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

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

414 root = xmltree.getroot()

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

416 child = ET.Element("ChannelSettings")

417 root.append(child)

418

419 ChannelWSID = ET.Element("WSID")

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

421 child.append(ChannelWSID)

422

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

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

425 self.lisw_WSID.addItem(item1)

426

427 for k in channelDic.keys():

428 ele = ET.Element(k)

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

430 child.append(ele)

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

432

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

434 docs = dict(parse(xmltree_string))

435 self._xmltodict.clear()

436 self._xmltodict.update(docs)

437

438 elif self._ChannelSettingsCount == 1:

439 self.lisw_WSID.clear()

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

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

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

443 self.lisw_WSID.addItem(item1)

444

445 for k in channelDic:

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

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

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

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

450

451 self._ChannelSettingsCount = 1

452

453 elif self._ChannelSettingsCount > 1:

454 self.lisw_WSID.clear()

455 i = 0

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

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

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

459 self.lisw_WSID.addItem(item1)

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

461 self.SingleCSChannelWidthType.append(

462 str(flowitem["SingleCSChannelWidthType"])

463 )

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

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

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

467

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

469 if str(DSValue).strip():

470 self.ChannelWidthMostDownStream.append(DSValue)

471 else:

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

473

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

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

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

477 self.CompoundCSChannelWidthLimit.append(

478 str(flowitem["CompoundCSChannelWidthLimit"])

479 )

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

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

482 i = i + 1

483 self._ChannelSettingsCount = i

484

485 self.flowEle = [

486 "Name",

487 "ColX",

488 "RowY",

489 "DT",

490 "ControlType",

491 "FlowDataFile",

492 "IniStorage",

493 "MaxStorage",

494 "NormalHighStorage",

495 "RestrictedStorage",

496 "RestrictedPeriod_Start",

497 "RestrictedPeriod_End",

498 "ROType",

499 "AutoROMmaxOutflow_CMS",

500 "ROConstQ",

501 "ROConstQDuration",

502 ]

503

504 def SetMostDownStream(self, id):

505 try:

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

507 if self.GridCellSize is None:

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

509 Allsize = self.GridCellSize

510

511 IniSaturation = "0.9"

512 MinSlopeOF = "0.0001"

513 MinSlopeChBed = "0.0001"

514 intAll = float(Allsize)

515 # if intAll > 0:

516 # MinChBaseWidth = intAll / 10

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

518 IniFlow = "0"

519 ChRoughness = "0.045"

520 DryStreamOrder = "0"

521 CalCoefLCRoughness = "1"

522 CalCoefSoilDepth = "1"

523 CalCoefPorosity = "1"

524 CalCoefWFSuctionHead = "1"

525 CalCoefHydraulicK = "1"

526 UnsturatedType = 1

527 CoefUnsatruatedk = "0.2"

528 interceptMethod = 1

529 potentialETMethod = 1

530 etCoeff = "1"

531 snowMeltMethod = 1

532 tempSnowRain = "1"

533 smeltingTemp = "1"

534 snowCovRatio = "1"

535 smeltCoef = "1"

536 self._wsinfo.setOneSWSParsAndUpdateAllSWSUsingNetwork(

537 int(id), # int wsid,

538 float(IniSaturation), # double iniSat,

539 float(MinSlopeOF), # double minSlopeLandSurface,

540 int(UnsturatedType), # int unSKType,

541 float(CoefUnsatruatedk), # double coefUnsK,

542 float(MinSlopeChBed), # double minSlopeChannel,

543 float(MinChBaseWidth), # double minChannelBaseWidth,

544 float(ChRoughness), # double roughnessChannel,

545 int(DryStreamOrder), # int dryStreamOrder,

546 float(CalCoefLCRoughness), # double ccLCRoughness,

547 float(CalCoefSoilDepth), # double ccSoilDepth,

548 float(CalCoefPorosity), # double ccPorosity,

549 float(CalCoefWFSuctionHead), # double ccWFSuctionHead,

550 float(CalCoefHydraulicK), # double ccSoilHydraulicCond,

551 int(interceptMethod),

552 int(potentialETMethod),

553 float(etCoeff),

554 int(snowMeltMethod),

555 float(tempSnowRain),

556 float(smeltingTemp),

557 float(snowCovRatio),

558 float(smeltCoef),

559 0,

560 ) # double iniFlow = 0)

561 except Exception as e:

562 MsError(e)

563

564 def dockDisableButton(self):

565 dockList = self.stackedWidget.findChildren(QDockWidget)

566 for dock in dockList:

567 dock.setFeatures(QDockWidget.NoDockWidgetFeatures)

568

569 def connectionTabBar(self, type):

570 f = self.firstTab.currentIndex()

571 s = self.secondTab.currentIndex()

572 index = 0

573

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

575 self.firstTab.setCurrentIndex(0)

576 self.secondTab.setCurrentIndex(s)

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

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

579 self.secondTab.setCurrentIndex(0)

580 self.firstTab.setCurrentIndex(f)

581 index = f - 1

582

583 self.stackedWidget.setCurrentIndex(index)

584

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

586 def Set_Canvas_Tool_Icon(self):

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

588 ZoomExtent = root + "\ZoomExtent.png"

589 Zoomin = root + "\ZoomIn.png"

590 ZoomOut = root + "\ZoomOut.png"

591 Pan = root + "\Pan.png"

592 Zoomnext = root + "\Zoomnext.png"

593 ZoomPrevious = root + "\ZoomPrevious.png"

594 SelectGrid = root + "\SelectGrid.png"

595 MoveTo = root + "\MoveTo.png"

596

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

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

599

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

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

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

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

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

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

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

607

608 # 캔버스 툴 기능 연동

609 def Set_Cavas_tool_btn(self):

610 self.tool = CanvasTool(self.mapcanvas)

611

612 # ZoomExtent

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

614

615 # Zoom Next

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

617

618 # Zoom Previous

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

620

621 # Zoom In

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

623

624 # Zoom Out

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

626

627 # Pan

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

629

630 # Moveto

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

632

633 # # Selectgrid

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

635

636 # Watch_Point 기본 설정은 체크

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

638

639 # chkFC

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

641

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

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

644

645 # 캔버스에 Flow direction

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

647

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

649 def Set_Canvas_Layer_default(self):

650 # canvase 레이어 올리기

651 if self.LayerPath is not None:

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

653 ".ASC", "_temp_convert_file.SHP"

654 )

655 flag_WSID_Shape = AscToShape(self.LayerPath, convert_shape_path)

656 Wsid_shape_style_path_ori = (

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

658 )

659

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

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

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

663 self.Wsid_label_shape.loadNamedStyle(Wsid_shape_style_path_ori)

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

665 _layer = self.layer

666 self.Set_Global_CanvaseValue()

667

668 """#2017.11..1 원 :

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

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

671

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

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

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

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

676

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

678 def Set_Global_CanvaseValue(self):

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

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

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

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

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

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

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

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

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

688

689 # def 연동 함수

690 def Open_ViewResult(self):

691 self.disCharge = self._xmltodict["GRMProject"]["ProjectSettings"]["ProjectFile"]

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

693 self.disCharge = self.disCharge.replace(

694 disCharge_path + ".gmp", disCharge_path + "Discharge.out"

695 )

696 Opewn_ViewFile(self.disCharge)

697

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

699 def Set_simulation_tab_default(self):

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

701 combolist = (

702 "All",

703 "DischargeFile",

704 "DischargeAndFcFile",

705 "AverageFile",

706 "DischargeFileQ",

707 "AverageFileQ",

708 "AllQ",

709 )

710 self.cmbPrint.addItems(combolist)

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

712 if index >= 0:

713 self.cmbPrint.setCurrentIndex(index)

714

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

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

717

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

719 self.Check_Parallel()

720

721 self.chkAveValueTimeInterval_min.stateChanged.connect(self.Check_Ave_Value_Time)

722 self.Check_Ave_Value_Time()

723

724 self.chkInterception.stateChanged.connect(

725 lambda state: self.check_simulate_option(

726 state,

727 [self.groupSimulateInterception, self.txtInterceptionMaxWaterCanopy],

728 )

729 )

730 self.check_simulate_option(

731 self.chkInterception.isChecked(),

732 [self.groupSimulateInterception, self.txtInterceptionMaxWaterCanopy],

733 )

734

735 self.chkEvapotranspiration.stateChanged.connect(

736 lambda state: self.check_simulate_option(

737 state, [self.groupSimulateEvapotranspiration]

738 )

739 )

740 self.check_simulate_option(

741 self.chkEvapotranspiration.isChecked(),

742 [self.groupSimulateEvapotranspiration],

743 )

744

745 self.chkSnowMelt.stateChanged.connect(

746 lambda state: self.check_simulate_option(

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

748 )

749 )

750 self.check_simulate_option(

751 self.chkSnowMelt.isChecked(),

752 [self.groupSimulateSnowMelt, self.txtCanopyRatio],

753 )

754

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

756 self.Check_Flow(False)

757

758 self.chkmakeimage.setChecked(False)

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

760 self.chkmakeimage.setChecked(True)

761

762 self.chkmakeASC.setChecked(False)

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

764 self.chkmakeASC.setChecked(True)

765

766 self.chksoiSaturation.setChecked(False)

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

768 self.chksoiSaturation.setChecked(True)

769

770 self.chkrfDistFile.setChecked(False)

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

772 self.chkrfDistFile.setChecked(True)

773

774 self.chkrfaacDistfile.setChecked(False)

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

776 self.chkrfaacDistfile.setChecked(True)

777

778 self.chkdischarge.setChecked(False)

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

780 self.chkdischarge.setChecked(True)

781

782 self.chkPrintAveValue.setChecked(False)

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

784 self.chkPrintAveValue.setChecked(True)

785

786 self.chklog.setChecked(False)

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

788 self.chklog.setChecked(True)

789

790 if self.SimulationStartingTime == "0":

791 now = QDateTime.currentDateTime()

792 self.dateTimeEdit.setDateTime(now)

793 self.chkStartingTime.setChecked(False)

794 self.dateTimeEdit.setEnabled(False)

795 self.dataTimeFormat = False

796 else:

797 self.chkStartingTime.setChecked(True)

798 self.dateTimeEdit.setEnabled(True)

799 dateTime = QDateTime.fromString(

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

801 )

802 self.dateTimeEdit.setDateTime(dateTime)

803 self.dataTimeFormat = True

804

805 self.chkParallel.setChecked(False)

806 if int(self.MaxDegreeOfParallelism) > 0:

807 self.chkParallel.setChecked(True)

808

809 self.chkAveValueTimeInterval_min.setChecked(False)

810 if self.AveValueTimeInterval_min:

811 self.chkAveValueTimeInterval_min.setChecked(True)

812

813 if self.ComputationalTimeStep is not None:

814 intvalue = int(self.ComputationalTimeStep)

815 self.spTimeStep_min.setValue(intvalue)

816 else:

817 if self._xsize <= 200:

818 value = 3

819 elif self._xsize > 200:

820 value = 5

821 self.spTimeStep_min.setValue(value)

822

823 if self.MaxDegreeOfParallelism is not None:

824 intvalue = int(self.MaxDegreeOfParallelism)

825 self.spTimeStep_min_2.setValue(intvalue)

826

827 if self.AveValueTimeInterval_min:

828 self.spbAveValueTimeInterval_min.setValue(

829 int(self.AveValueTimeInterval_min)

830 )

831

832 if self.OutputTimeStep is not None and self.OutputTimeStep != "":

833 self.txtOutput_time_step.setText(str(self.OutputTimeStep))

834

835 self.txtSimulation_duration.setText("")

836 if self.SimulationDuration is not None:

837 self.txtSimulation_duration.setText(self.SimulationDuration)

838

839 if self.OutputTimeStep is not None:

840 self.txtOutput_time_step.setText(self.OutputTimeStep)

841

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

843 self.chkInfiltration.setChecked(True)

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

845 self.chkInfiltration.setChecked(False)

846

847 self.chkSubsurfaceFlow.setChecked(True)

848 if (

849 self.SimulateSubsurfaceFlow

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

851 ):

852 self.chkSubsurfaceFlow.setChecked(False)

853

854 self.chkBaseFlow.setChecked(True)

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

856 self.chkBaseFlow.setChecked(False)

857

858 self.chkInterception.setChecked(True)

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

860 self.chkInterception.setChecked(False)

861

862 self.chkEvapotranspiration.setChecked(True)

863 if (

864 self.SimulateEvapotranspiration

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

866 ):

867 self.chkEvapotranspiration.setChecked(False)

868

869 self.chkSnowMelt.setChecked(True)

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

871 self.chkSnowMelt.setChecked(False)

872

873 if self.SimulateFlowControl is not None:

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

875 self.chkFlowControl.setChecked(True)

876

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

878

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

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

881 self.MakeASC_IMAGE()

882

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

884 self.chkfixeTimeStep.setChecked(True)

885

886 def printcombo(self):

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

888 self.chkmakeimage.setEnabled(True)

889 self.chkmakeASC.setEnabled(True)

890 self.MakeASC_IMAGE()

891 else:

892 self.chkmakeimage.setEnabled(False)

893 self.chkmakeASC.setEnabled(False)

894 self.chksoiSaturation.setEnabled(False)

895 self.chkrfDistFile.setEnabled(False)

896 self.chkrfaacDistfile.setEnabled(False)

897 self.chkdischarge.setEnabled(False)

898

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

900 for q_widget in q_widget_list:

901 q_widget.setEnabled(state)

902

903 def SPvaluechange(self):

904 value = self.spTimeStep_min_2.text()

905 if value == "0":

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

907

908 def Check_Parallel(self):

909 flag = self.chkParallel.isChecked()

910 self.spTimeStep_min_2.setEnabled(flag)

911

912 def Check_Ave_Value_Time(self):

913 flag = self.chkAveValueTimeInterval_min.isChecked()

914 self.spbAveValueTimeInterval_min.setEnabled(flag)

915

916 def Check_Flow(self, flag):

917 self.chkAutoROM.setEnabled(flag)

918 self.chkAutoROM.setChecked(False)

919

920 def Check_StartingTime(self):

921 flag = self.chkStartingTime.isChecked()

922 self.dateTimeEdit.setEnabled(flag)

923 self.dataTimeFormat = flag

924

925 def MakeASC_IMAGE(self):

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

927 self.chksoiSaturation.setEnabled(flag)

928 self.chkrfDistFile.setEnabled(flag)

929 self.chkrfaacDistfile.setEnabled(flag)

930 self.chkdischarge.setEnabled(flag)

931

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

933 def Set_Wathpoint_tab_default(self):

934 try:

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

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

937

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

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

940

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

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

943

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

945 self.tbList.setEditTriggers(QAbstractItemView.NoEditTriggers)

946

947 # color picker 이벤트

948 self.btnColorPicker.clicked.connect(

949 lambda: self.color_picker(self.btnColorPicker)

950 )

951 self.btnColorPicker_3.clicked.connect(

952 lambda: self.color_picker(self.btnColorPicker_3)

953 )

954

955 # 2017/11/22-------------------

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

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

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

959

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

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

962

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

964

965 # 최하류 셀 넣기

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

967

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

969 self.Watchpoint_TableCreate(len(self.Name))

970 self.Watchpoint_Table_Insert()

971 except Exception as wa:

972 MsError(wa)

973

974 def MoveUp(self):

975 row = self.tbList.currentRow()

976 column = self.tbList.currentColumn()

977 if row > 0:

978 self.tbList.insertRow(row - 1)

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

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

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

982 self.tbList.removeRow(row + 1)

983

984 def MoveDown(self):

985 row = self.tbList.currentRow()

986 column = self.tbList.currentColumn()

987 if row >= 0:

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

989 self.tbList.insertRow(row + 2)

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

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

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

993 self.tbList.removeRow(row)

994

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

996 rowCount = self.tbList.rowCount()

997 self.RetBool = True

998 for row in range(0, rowCount):

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

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

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

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

1003 self.RetBool = False

1004 return self.RetBool

1005

1006 def ReMove(self):

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

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

1009 result = QMessageBox.question(

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

1011 )

1012 if result == QMessageBox.Yes:

1013 self.tbList.removeRow(row)

1014

1015 self.post_grid_remove2()

1016 if self.chkFlowContorGird.isChecked():

1017 self.FlowContorGird_paint()

1018 if self.chkWatch_Point.isChecked():

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

1020 self.watchpoint_paint()

1021

1022 def btnGotoGrid(self, tbl):

1023 row = tbl.currentRow()

1024 if row > -1:

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

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

1027

1028 self.post_grid_remove()

1029 self.mapcanvas.refresh()

1030 self.scale_changed_mapcanvas()

1031 self.row_cols_grid(ColX, RowY, None)

1032 self.tool.scale_changed_disconnect()

1033 else:

1034 MsInfo("Check! select row")

1035

1036 def CheckTableValue(self, x, y):

1037 rowCount = self.tbList.rowCount()

1038 self.RetBool = True

1039 for row in range(0, rowCount):

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

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

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

1043 self.RetBool = False

1044 return self.RetBool

1045

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

1047 def Edit(self):

1048 # 현재 선택된 Row

1049 row = self.tbList.currentRow()

1050

1051 if row > -1:

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

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

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

1055 text, ok = QInputDialog.getText(

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

1057 )

1058 if ok:

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

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

1061 else:

1062 MsInfo("check! select Row")

1063

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

1065 def Add_Selected_Cell(self):

1066 try:

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

1068 rowCount = self.tbList.rowCount()

1069 if rowCount > 0:

1070 text, ok = QInputDialog.getText(

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

1072 )

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

1074 if self.check_add_watchpoint(

1075 self.tool._YROW, self.tool._XCOL, text

1076 ):

1077 self.tbList.insertRow(rowCount)

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

1079 self.tbList.setItem(

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

1081 )

1082 self.tbList.setItem(

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

1084 )

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

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

1087 if self.chkWatch_Point.isChecked():

1088 self.row_cols_grid(

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

1090 )

1091 else:

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

1093 else:

1094 MsInfo(" Name is required. ")

1095 else:

1096 text, ok = QInputDialog.getText(

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

1098 )

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

1100 self.tbList.insertRow(0)

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

1102 self.tbList.setItem(

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

1104 )

1105 self.tbList.setItem(

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

1107 )

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

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

1110 if self.chkWatch_Point.isChecked():

1111 self.row_cols_grid(

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

1113 )

1114 else:

1115 MsInfo(" Name is required. ")

1116 except Exception as e:

1117 MsError(e)

1118

1119 def Add_MostDown_Stream(self):

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

1121 x = self._wsinfo.facMaxCellxCol

1122 y = self._wsinfo.facMaxCellyRow

1123

1124 rowCount = self.tbList.rowCount()

1125 if self.CheckTableValue(x, y):

1126 self.tbList.insertRow(rowCount)

1127 text, ok = QInputDialog.getText(

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

1129 )

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

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

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

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

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

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

1136 else:

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

1138 else:

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

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

1141 MsInfo(

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

1143 + "\r\n"

1144 + " Add most down stream cells manually. "

1145 )

1146

1147 def Watchpoint_TableCreate(self, Row):

1148 self.tbList.setColumnCount(3)

1149 self.tbList.setRowCount(Row)

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

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

1152 self.tbList.setColumnWidth(0, 176)

1153

1154 # watchpoint datault 값을 변수에 저장

1155 def Set_Wathpoint_default_value(self):

1156 self.Name = []

1157 self.ColX = []

1158 self.RowY = []

1159 if self._WatchPointCount == 0:

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

1161

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

1163 x = self._wsinfo.facMaxCellxCol

1164 y = self._wsinfo.facMaxCellyRow

1165

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

1167 if self._wsinfo.mostDownStreamWSCount == 1:

1168 names = "MD"

1169 self.Name.append(names)

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

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

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

1173

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

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

1176

1177 elif self._WatchPointCount > 1:

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

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

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

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

1182

1183 elif self._WatchPointCount == 1:

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

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

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

1187

1188 def Watchpoint_Table_Insert(self):

1189 if len(self.Name) > 0:

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

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

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

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

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

1195

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

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

1198 color = QColorDialog.getColor()

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

1200

1201 self.post_grid_remove2()

1202 self.watchpoint()

1203 self.click_FlowContorGird()

1204

1205 # watchpoint RubberBand 제거

1206 def post_grid_remove2(self):

1207 for v in self.canvasRubberBand:

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

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

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

1211

1212 def watchpoint(self):

1213 if self.chkWatch_Point.isChecked():

1214 self.watchpoint_paint()

1215 else:

1216 # 지우기

1217 self.post_grid_remove2()

1218 if self.chkFlowContorGird.isChecked():

1219 self.FlowContorGird_paint()

1220

1221 def watchpoint_paint(self):

1222 try:

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

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

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

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

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

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

1229

1230 else:

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

1232 self.row_cols_grid(

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

1234 )

1235 except Exception as e:

1236 MsError(e)

1237

1238 # 1. row/cols로 마커

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

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

1241 row = int(row)

1242 column = int(column)

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

1244 row = "out of extent"

1245 column = "out of extent"

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

1247 else:

1248 if type == "watchpoint":

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

1250 Cell_Y_Center2 = (

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

1252 )

1253 if (

1254 Cell_X_Center2 <= self._xmax

1255 or self._xmin <= Cell_X_Center2

1256 or Cell_Y_Center2 <= self._ymax

1257 or self._ymin <= Cell_Y_Center2

1258 ):

1259 self.draw_grid2(

1260 Cell_X_Center2, Cell_Y_Center2, self.btnColorPicker

1261 )

1262

1263 else:

1264 self.lblColRow.setText(

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

1266 )

1267 self.tool.Cell_X_Center = (

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

1269 )

1270 self.tool.Cell_Y_Center = (

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

1272 )

1273 if (

1274 self.tool.Cell_X_Center <= self._xmax

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

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

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

1278 ):

1279 oldExtent = self.mapcanvas.extent()

1280

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

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

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

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

1285

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

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

1288 else:

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

1290 return

1291

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

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

1294 r = QgsRubberBand(self.mapcanvas, True)

1295 size = self._xsize / 2

1296

1297 points = [

1298 [

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

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

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

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

1303 ]

1304 ]

1305

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

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

1308 r.setWidth(2)

1309

1310 self.canvasRubberBand.append(r)

1311

1312 def click_FlowContorGird(self):

1313 if self.chkFlowContorGird.isChecked():

1314 self.FlowContorGird_paint()

1315 else:

1316 # 지우기

1317 self.post_grid_remove2()

1318 if self.chkWatch_Point.isChecked():

1319 self.watchpoint_paint()

1320

1321 def FlowContorGird_paint(self):

1322 counts = self.tlbFlowControl.rowCount()

1323 for i in range(0, counts):

1324 xvalue = (

1325 self._xmin

1326 + self._xsize / 2

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

1328 )

1329 yvalue = (

1330 self._ymax

1331 - self._ysize / 2

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

1333 )

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

1335

1336 # 그리드 라인 함수

1337 def show_hide_grid_line(self):

1338 if self.show_grid_line.isChecked():

1339 self.add_grid_layer()

1340 else:

1341 self.remove_grid_layer()

1342

1343 def remove_grid_layer(self):

1344 self.grid_line.setOpacity(0)

1345 self.mapcanvas.refresh()

1346

1347 # 플로우 디렉션

1348 def show_hide_flow_direction(self):

1349 if self.show_flow_direction.isChecked():

1350 self.show_flow_directions()

1351 else:

1352 self.hide_flow_direction()

1353

1354 def add_grid_layer(self):

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

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

1357 self.grid_line.setOpacity(1)

1358 self.mapcanvas.refresh()

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

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

1361 self.mapcanvas.setLayers(

1362 [

1363 self.flow_direction,

1364 self.grid_line,

1365 self.layer,

1366 self.Wsid_label_shape,

1367 ]

1368 )

1369 else:

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

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

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

1373 self.mapcanvas.setExtent(self.mapcanvas.extent())

1374

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

1376 self.mapcanvas.setLayers(

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

1378 )

1379

1380 if self.flow_direction:

1381 self.mapcanvas.setLayers(

1382 [

1383 self.flow_direction,

1384 self.grid_line,

1385 self.layer,

1386 self.Wsid_label_shape,

1387 ]

1388 )

1389

1390 def show_flow_directions(self):

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

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

1393 self.flow_direction.setOpacity(1)

1394 self.mapcanvas.refresh()

1395 else:

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

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

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

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

1400

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

1402 "FlowDirectionType"

1403 ]

1404 self.flow_direction = get_flow_layer(

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

1406 )

1407

1408 # 신규 소스

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

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

1411

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

1413 self.mapcanvas.setLayers(

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

1415 )

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

1417 self.mapcanvas.setLayers(

1418 [

1419 self.grid_line,

1420 self.flow_direction,

1421 self.layer,

1422 self.Wsid_label_shape,

1423 ]

1424 )

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

1426

1427 # Qdilog 창에 Qtablewidget 셋팅

1428 def aboutApp(self):

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

1430 msgBox = QMessageBox()

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

1432 msgBox.setTextFormat(Qt.RichText)

1433

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

1435 self.addGroupWidget(msgBox)

1436 ret = msgBox.exec_()

1437

1438 # Create TableWidget

1439 def addGroupWidget(self, parentItem):

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

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

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

1443

1444 # 텍스트 박스

1445 self.txt_xColyRowNo_1 = QLineEdit(parentItem)

1446 self.txt_xColyRowNo_2 = QLineEdit(parentItem)

1447 self.txt_xy1 = QLineEdit(parentItem)

1448 self.txt_xy2 = QLineEdit(parentItem)

1449 self.btn_Cancel = QPushButton(parentItem)

1450 self.btn_Cancel.setText("Cancel")

1451

1452 self.btn_OK = QPushButton(parentItem)

1453 self.btn_OK.setText("OK")

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

1455 layout = parentItem.layout()

1456

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

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

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

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

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

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

1463

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

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

1466

1467 self.txt_xColyRowNo_1.setMaximumWidth(100)

1468 self.txt_xColyRowNo_2.setMaximumWidth(100)

1469 self.txt_xy1.setFixedWidth(100)

1470 self.txt_xy2.setFixedWidth(100)

1471

1472 # 버튼별 이벤트

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

1474 self.rdo_xColyRowNo.setChecked(True)

1475 self.rdo_xy.setChecked(False)

1476 self.txt_xy1.setDisabled(True)

1477 self.txt_xy2.setDisabled(True)

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

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

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

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

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

1483

1484 def Cancel_Click(self, parentItem):

1485 parentItem.close()

1486

1487 # 폼 종료

1488 def Close_Form(self):

1489 self.close()

1490

1491 def closeEvent(self, event):

1492 del self._wsinfo

1493 self.Clear_Canvas()

1494 self.closeDialogEvent.emit()

1495

1496 def SaveProject(self, flag=False):

1497 self.InputDictionary()

1498 DictoXml = unparse(self._xmltodict)

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

1500 fw.write(DictoXml)

1501 fw.close()

1502

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

1504 _XmlCheck.Check_Gmp_xml(self.ProjectFile)

1505 self._LandCoverCount = _XmlCheck._LandCoverCount

1506 self._GreenAmptCount = _XmlCheck._GreenAmptCount

1507 self._SoilDepthCount = _XmlCheck._SoilDepthCount

1508 self._WatchPointCount = _XmlCheck._WatchPointCount

1509 self._SubWatershedCount = _XmlCheck._SubWatershedCount

1510 self._FlowControlCount = _XmlCheck._FlowControlCount

1511 self._ChannelSettingsCount = _XmlCheck._ChannelSettingsCount

1512 if flag:

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

1514

1515 def InputDictionary(self):

1516 try:

1517 # =========================simulation tab ===================================

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

1519 "ComputationalTimeStep"

1520 ] = self.spTimeStep_min.text()

1521 if self.chkStartingTime.isChecked():

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

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

1524 "SimulationStartingTime"

1525 ] = DateTime

1526 else:

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

1528 "SimulationStartingTime"

1529 ] = "0"

1530

1531 if self.chkParallel.isChecked():

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

1533 "MaxDegreeOfParallelism"

1534 ] = self.spTimeStep_min_2.text()

1535

1536 else:

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

1538 "MaxDegreeOfParallelism"

1539 ] = "-1"

1540

1541 if self.chkAveValueTimeInterval_min.isChecked():

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

1543 "AveValueTimeInterval_min"

1544 ] = self.spbAveValueTimeInterval_min.text()

1545 else:

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

1547 "AveValueTimeInterval_min"

1548 ] = ""

1549

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

1551 "OutputTimeStep"

1552 ] = self.txtOutput_time_step.text()

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

1554 "SimulationDuration"

1555 ] = self.txtSimulation_duration.text()

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

1557 "OutputTimeStep"

1558 ] = self.txtOutput_time_step.text()

1559

1560 projectTagDic = {

1561 "SimulateInfiltration": self.chkInfiltration,

1562 "SimulateSubsurfaceFlow": self.chkSubsurfaceFlow,

1563 "SimulateBaseFlow": self.chkBaseFlow,

1564 "SimulateInterception": self.chkInterception,

1565 "SimulateEvapotranspiration": self.chkEvapotranspiration,

1566 "SimulateSnowMelt": self.chkSnowMelt,

1567 "SimulateFlowControl": self.chkFlowControl,

1568 "MakeIMGFile": self.chkmakeimage,

1569 "MakeASCFile": self.chkmakeASC,

1570 "MakeSoilSaturationDistFile": self.chksoiSaturation,

1571 "MakeRfDistFile": self.chkrfDistFile,

1572 "MakeRFaccDistFile": self.chkrfaacDistfile,

1573 "MakeFlowDistFile": self.chkdischarge,

1574 "PrintAveValue": self.chkPrintAveValue,

1575 "WriteLog": self.chklog,

1576 "IsFixedTimeStep": self.chkfixeTimeStep,

1577 }

1578

1579 for k in projectTagDic.keys():

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

1581 projectTagDic[k].isChecked()

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

1583

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

1585 "PrintOption"

1586 ] = self.cmbPrint.currentText()

1587

1588 # =========================simulation tab end ===============================================

1589

1590 # =========================Watch Point tab===================================================

1591 # GRM._WatchPointCount

1592 # if self._WatchPointCount > 0:

1593 try:

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

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

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

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

1598 except KeyError:

1599 pass

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

1601

1602 DictoXml = unparse(self._xmltodict)

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

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

1605 root = xmltree.getroot()

1606

1607 wcount = self.tbList.rowCount()

1608 self._WatchPointCount = wcount

1609 for row in range(0, wcount):

1610 child = ET.Element("WatchPoints")

1611 root.append(child)

1612

1613 WathchName = ET.Element("Name")

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

1615 child.append(WathchName)

1616

1617 WathchColX = ET.Element("ColX")

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

1619 child.append(WathchColX)

1620

1621 WathchRowY = ET.Element("RowY")

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

1623 child.append(WathchRowY)

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

1625 docs = dict(parse(xmltree_string))

1626 self._xmltodict.clear()

1627 self._xmltodict.update(docs)

1628

1629 # =========================Wahch Point tab end===============================================

1630

1631 # =========================Channel CS tab====================================================

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

1633 if self._ChannelSettingsCount > 0:

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

1635

1636 DictoXml = unparse(self._xmltodict)

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

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

1639 root = xmltree.getroot()

1640 self._ChannelSettingsCount = len(self._StreamWSID)

1641

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

1643 child = ET.Element("ChannelSettings")

1644 root.append(child)

1645

1646 WSID = ET.Element("WSID")

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

1648 child.append(WSID)

1649

1650 CrossSectionType = ET.Element("CrossSectionType")

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

1652 CrossSectionType.text = "CSCompound"

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

1654 CrossSectionType.text = "CSSingle"

1655 else:

1656 CrossSectionType.text = "CSSingle"

1657 child.append(CrossSectionType)

1658

1659 SingleCSChannelWidthType = ET.Element("SingleCSChannelWidthType")

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

1661 SingleCSChannelWidthType.text = "CWGeneration"

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

1663 SingleCSChannelWidthType.text = "CWEquation"

1664 else:

1665 SingleCSChannelWidthType.text = "CWGeneration"

1666

1667 child.append(SingleCSChannelWidthType)

1668

1669 ChannelWidthEQc = ET.Element("ChannelWidthEQc")

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

1671 child.append(ChannelWidthEQc)

1672

1673 ChannelWidthEQd = ET.Element("ChannelWidthEQd")

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

1675 child.append(ChannelWidthEQd)

1676

1677 ChannelWidthEQe = ET.Element("ChannelWidthEQe")

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

1679 child.append(ChannelWidthEQe)

1680

1681 ChannelWidthMostDownStream = ET.Element("ChannelWidthMostDownStream")

1682 ChannelWidthMostDownStream.text = str(

1683 self.ChannelWidthMostDownStream[index]

1684 )

1685 child.append(ChannelWidthMostDownStream)

1686

1687 LowerRegionHeight = ET.Element("LowerRegionHeight")

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

1689 child.append(LowerRegionHeight)

1690

1691 LowerRegionBaseWidth = ET.Element("LowerRegionBaseWidth")

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

1693 child.append(LowerRegionBaseWidth)

1694

1695 UpperRegionBaseWidth = ET.Element("UpperRegionBaseWidth")

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

1697 child.append(UpperRegionBaseWidth)

1698

1699 CompoundCSChannelWidthLimit = ET.Element("CompoundCSChannelWidthLimit")

1700 CompoundCSChannelWidthLimit.text = str(

1701 self.CompoundCSChannelWidthLimit[index]

1702 )

1703 child.append(CompoundCSChannelWidthLimit)

1704

1705 BankSideSlopeRight = ET.Element("BankSideSlopeRight")

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

1707 child.append(BankSideSlopeRight)

1708

1709 BankSideSlopeLeft = ET.Element("BankSideSlopeLeft")

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

1711 child.append(BankSideSlopeLeft)

1712

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

1714 docs = dict(parse(xmltree_string))

1715 self._xmltodict.clear()

1716 self._xmltodict.update(docs)

1717

1718 # =========================Channel CS tab end================================================

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

1720 self.UpdateFlowControl()

1721

1722 # =========================Flow Control Tab end ==================================================

1723 # ========================= Watershed tab ========================================================

1724 # if self._SubWatershedCount>0:

1725 try:

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

1727 except KeyError:

1728 pass

1729

1730 DictoXml = unparse(self._xmltodict)

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

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

1733 root = xmltree.getroot()

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

1735 scount = self.cb_selectws.count()

1736

1737 for row in range(0, scount):

1738 selectWS = self.cb_selectws.itemText(row)

1739

1740 child = ET.Element("SubWatershedSettings")

1741 root.append(child)

1742

1743 ID = ET.Element("ID")

1744 ID.text = selectWS

1745 child.append(ID)

1746

1747 IniSaturation = ET.Element("IniSaturation")

1748 IniSaturation.text = str(

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

1750 )

1751 child.append(IniSaturation)

1752

1753 MinSlopeOF = ET.Element("MinSlopeOF")

1754 MinSlopeOF.text = str(

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

1756 )

1757 child.append(MinSlopeOF)

1758

1759 UnsaturatedKType = ET.Element("UnsaturatedKType")

1760 UnsaturatedKType_int = str(

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

1762 )

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

1764 if UnsaturatedKType_int == "0":

1765 UnsturatedType = "Constant"

1766 elif UnsaturatedKType_int == "2":

1767 UnsturatedType = "Exponential"

1768

1769 UnsaturatedKType.text = UnsturatedType

1770 child.append(UnsaturatedKType)

1771

1772 CoefUnsaturatedK = ET.Element("CoefUnsaturatedK")

1773 CoefUnsaturatedK.text = str(

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

1775 )

1776 child.append(CoefUnsaturatedK)

1777

1778 MinSlopeChBed = ET.Element("MinSlopeChBed")

1779 MinSlopeChBed.text = str(

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

1781 )

1782 child.append(MinSlopeChBed)

1783

1784 MinChBaseWidth = ET.Element("MinChBaseWidth")

1785 MinChBaseWidth.text = str(

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

1787 )

1788 child.append(MinChBaseWidth)

1789

1790 ChRoughness = ET.Element("ChRoughness")

1791 ChRoughness.text = str(

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

1793 )

1794 child.append(ChRoughness)

1795

1796 DryStreamOrder = ET.Element("DryStreamOrder")

1797 DryStreamOrder.text = str(

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

1799 )

1800 child.append(DryStreamOrder)

1801

1802 IniFlow = ET.Element("IniFlow")

1803 IniFlow.text = "0"

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

1805 IniFlow.text = str(

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

1807 )

1808 child.append(IniFlow)

1809

1810 CalCoefLCRoughness = ET.Element("CalCoefLCRoughness")

1811 CalCoefLCRoughness.text = str(

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

1813 )

1814 child.append(CalCoefLCRoughness)

1815

1816 CalCoefPorosity = ET.Element("CalCoefPorosity")

1817 CalCoefPorosity.text = str(

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

1819 )

1820 child.append(CalCoefPorosity)

1821

1822 CalCoefWFSuctionHead = ET.Element("CalCoefWFSuctionHead")

1823 CalCoefWFSuctionHead.text = str(

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

1825 )

1826 child.append(CalCoefWFSuctionHead)

1827

1828 CalCoefHydraulicK = ET.Element("CalCoefHydraulicK")

1829 CalCoefHydraulicK.text = str(

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

1831 )

1832 child.append(CalCoefHydraulicK)

1833

1834 CalCoefSoilDepth = ET.Element("CalCoefSoilDepth")

1835 CalCoefSoilDepth.text = str(

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

1837 )

1838 child.append(CalCoefSoilDepth)

1839

1840 InterceptionMethod = ET.Element("InterceptionMethod")

1841 InterceptionMethod_int = int(

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

1843 )

1844 InterceptionMethodType = EnumInterceptionMethod(

1845 InterceptionMethod_int

1846 ).name

1847 InterceptionMethod.text = InterceptionMethodType

1848 child.append(InterceptionMethod)

1849

1850 PETMethod = ET.Element("PETMethod")

1851 PETMethod_int = int(

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

1853 )

1854 PETMethodType = EnumPETMethod(PETMethod_int).name

1855 PETMethod.text = PETMethodType

1856 child.append(PETMethod)

1857

1858 ETCoef = ET.Element("ETCoef")

1859 ETCoef.text = str(self._wsinfo.subwatershedPars(int(selectWS)).etCoeff)

1860 child.append(ETCoef)

1861

1862 SnowmeltMethod = ET.Element("SnowmeltMethod")

1863 SnowmeltMethod_int = int(

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

1865 )

1866 SnowmeltMethodType = EnumSnowMeltMethod(SnowmeltMethod_int).name

1867 SnowmeltMethod.text = SnowmeltMethodType

1868 child.append(SnowmeltMethod)

1869

1870 TempSnowRain = ET.Element("TempSnowRain")

1871 TempSnowRain.text = str(

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

1873 )

1874 child.append(TempSnowRain)

1875

1876 SnowmeltingTemp = ET.Element("SnowmeltingTemp")

1877 SnowmeltingTemp.text = str(

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

1879 )

1880 child.append(SnowmeltingTemp)

1881

1882 SnowCovRatio = ET.Element("SnowCovRatio")

1883 SnowCovRatio.text = str(

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

1885 )

1886 child.append(SnowCovRatio)

1887

1888 SnowmeltCoef = ET.Element("SnowmeltCoef")

1889 SnowmeltCoef.text = str(

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

1891 )

1892 child.append(SnowmeltCoef)

1893

1894 UserSet = ET.Element("UserSet")

1895 UserSet_value = str(

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

1897 )

1898 UserSet.text = "False"

1899 if UserSet_value == "1":

1900 UserSet.text = "True"

1901

1902 child.append(UserSet)

1903

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

1905 docs = dict(parse(xmltree_string))

1906 self._xmltodict.clear()

1907 self._xmltodict.update(docs)

1908

1909 except Exception as e:

1910 MsError(e)

1911

1912 def Clear_Canvas(self):

1913 try:

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

1915 layers = self.mapcanvas.layers()

1916 for l in layers:

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

1918 self.mapcanvas.clearCache()

1919 # self.AddLayerQGIS()

1920

1921 except Exception as e:

1922 pass

1923

1924 def AddLayerQGIS(self):

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

1926 proTag = [

1927 "DomainFile",

1928 "SlopeFile",

1929 "FlowDirectionFile",

1930 "FlowAccumFile" "StreamFile",

1931 "LandCoverFile",

1932 "SoilDepthFile",

1933 "SoilTextureFile",

1934 ]

1935

1936 for t in proTag:

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

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

1939

1940 # gis에 올리기

1941 def AddlayerQGIS(self, path):

1942 try:

1943 if os.path.isfile(path):

1944 fileInfo = QFileInfo(path)

1945 baseName = fileInfo.baseName()

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

1947 QgsProject.instance().addMapLayer(layer)

1948 except Exception as e:

1949 MsInfo(e)

1950

1951 def OK_Click(self):

1952 self.post_grid_remove()

1953 self.rdo_selection()

1954 self.mapcanvas.refresh()

1955 self.scale_changed_mapcanvas()

1956 self.tool.scale_changed_disconnect()

1957

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

1959 def scale_changed_mapcanvas(self):

1960 try:

1961 # connect 중복 연결 방지

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

1963 except TypeError:

1964 pass

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

1966

1967 def scale_change_vertexMarker(self):

1968 self.post_grid_remove()

1969 try:

1970 if (

1971 self.tool.Cell_X_Center is not None

1972 or self.tool.Cell_Y_Center is not None

1973 ):

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

1975 except AttributeError:

1976 pass

1977

1978 # ================== 2017/11/6 조

1979 def post_grid_remove(self):

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

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

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

1983

1984 def rdo_selection(self):

1985 # col, row 입력

1986 if self.rdo_xColyRowNo.isChecked():

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

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

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

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

1991

1992 gird = self.row_cols_grid(

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

1994 )

1995 # xy 입력

1996 elif self.rdo_xy.isChecked():

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

1998 x = self.txt_xy1.text()

1999 y = self.txt_xy2.text()

2000

2001 def identify(self):

2002 # 캔버스 휠까지 처리 됨

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

2004

2005 self.tool.scale_changed()

2006 self.mapcanvas.setMapTool(self.tool)

2007

2008 def disableFunction(self):

2009 flag = self.rdo_xColyRowNo.isChecked()

2010 self.txt_xColyRowNo_1.setDisabled(not flag)

2011 self.txt_xColyRowNo_2.setDisabled(not flag)

2012 self.txt_xy1.setDisabled(flag)

2013 self.txt_xy2.setDisabled(flag)

2014

2015 # grid 그리기

2016 def draw_grid(self, x, y):

2017 marker = QgsVertexMarker(self.mapcanvas)

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

2019

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

2021 scale = self.mapcanvas.scale()

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

2023 map_width = (

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

2025 )

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

2027 marker.setIconSize(size)

2028 marker.setIconType(QgsVertexMarker.ICON_BOX)

2029 marker.setPenWidth(1)

2030 return marker

2031

2032 def hide_flow_direction(self):

2033 self.flow_direction.setOpacity(0)

2034 self.mapcanvas.refresh()

2035

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

2037 def Set_ChannelCS_tab_default(self):

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

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

2040

2041 if CrossSectionType == "CSSINGLE":

2042 self.chk_compound.setChecked(False)

2043 elif CrossSectionType == "CSCOMPOUND":

2044 self.chk_compound.setChecked(True)

2045

2046 if SingleCSChannelWidthType == "CWGENERATION":

2047 self.rdo_generateCh.setChecked(True)

2048 elif SingleCSChannelWidthType == "CWEQUATION":

2049 self.rdo_useCh.setChecked(True)

2050 else:

2051 self.rdo_generateCh.setChecked(True)

2052

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

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

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

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

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

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

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

2060 self.txtCompound_CSChannel_Width_Limit.setText(

2061 self.CompoundCSChannelWidthLimit[0]

2062 )

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

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

2065

2066 self.txt_douwnstream.setDisabled(True)

2067 self.ChannelCS_rdo_able()

2068

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

2070

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

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

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

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

2075

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

2077

2078 def key_events(self):

2079 try:

2080 index = self.lisw_WSID.currentRow()

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

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

2083 if SingleCSChannelWidthType == "CWGENERATION":

2084 self.rdo_generateCh.setChecked(True)

2085 elif SingleCSChannelWidthType == "CWEQUATION":

2086 self.rdo_useCh.setChecked(True)

2087 else:

2088 self.rdo_generateCh.setChecked(True)

2089 if CrossSectionType == "CSSINGLE":

2090 self.chk_compound.setChecked(False)

2091 elif CrossSectionType == "CSCOMPOUND":

2092 self.chk_compound.setChecked(True)

2093 else:

2094 self.chk_compound.setChecked(False)

2095

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

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

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

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

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

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

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

2103 self.txtCompound_CSChannel_Width_Limit.setText(

2104 self.CompoundCSChannelWidthLimit[index]

2105 )

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

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

2108

2109 self.txt_douwnstream.setDisabled(True)

2110 self.ChannelCS_rdo_able()

2111

2112 except Exception as e:

2113 MsError(e)

2114

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

2116 def set_WSID_value_change(self):

2117 try:

2118 if self.lisw_WSID.currentItem():

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

2120

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

2122 for i in range(self._ChannelSettingsCount):

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

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

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

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

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

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

2129 self.LowerRegionBaseWidth[

2130 i

2131 ] = self.txtLower_Region_Base_Width.text()

2132 self.UpperRegionBaseWidth[

2133 i

2134 ] = self.txtUpper_Region_Base_Width.text()

2135 self.CompoundCSChannelWidthLimit[

2136 i

2137 ] = self.txtCompound_CSChannel_Width_Limit.text()

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

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

2140

2141 if self.rdo_generateCh.isChecked():

2142 self.SingleCSChannelWidthType[i] = "CWGENERATION"

2143 elif self.rdo_useCh.isChecked():

2144 self.SingleCSChannelWidthType[i] = "CWEQUATION"

2145

2146 self.CrossSectionType[i] = "CSSingle"

2147 if self.chk_compound.isChecked():

2148 self.CrossSectionType[i] = "CSCOMPOUND"

2149

2150 MsInfo("Channel setting was updated.")

2151

2152 else:

2153 MsInfo("Select WSID ")

2154 except Exception as e:

2155 MsError(e)

2156

2157 def ListView_WSID(self, index):

2158 try:

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

2160 SingleCSChannelWidthType = self.SingleCSChannelWidthType[

2161 index.row()

2162 ].upper()

2163 if SingleCSChannelWidthType == "CWGENERATION":

2164 self.rdo_generateCh.setChecked(True)

2165 elif SingleCSChannelWidthType == "CWEQUATION":

2166 self.rdo_useCh.setChecked(True)

2167 else:

2168 self.rdo_generateCh.setChecked(True)

2169 if CrossSectionType == "CSSINGLE":

2170 self.chk_compound.setChecked(False)

2171 elif CrossSectionType == "CSCOMPOUND":

2172 self.chk_compound.setChecked(True)

2173 else:

2174 self.chk_compound.setChecked(False)

2175

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

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

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

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

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

2181 self.txtLower_Region_Base_Width.setText(

2182 self.LowerRegionBaseWidth[index.row()]

2183 )

2184 self.txtUpper_Region_Base_Width.setText(

2185 self.UpperRegionBaseWidth[index.row()]

2186 )

2187 self.txtCompound_CSChannel_Width_Limit.setText(

2188 self.CompoundCSChannelWidthLimit[index.row()]

2189 )

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

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

2192

2193 self.txt_douwnstream.setDisabled(True)

2194 self.ChannelCS_rdo_able()

2195

2196 except Exception as e:

2197 MsError(e)

2198

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

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

2201 def ChannelCS_rdo_able(self):

2202 # 활성 상태

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

2204

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

2206 if self.rdo_useCh.isChecked():

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

2208 self.txt_douwnstream.setDisabled(True)

2209 self.txt_c.setDisabled(False)

2210 self.txt_d.setDisabled(False)

2211 self.txt_e.setDisabled(False)

2212

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

2214 elif self.rdo_generateCh.isChecked():

2215 self.txt_douwnstream.setDisabled(False)

2216 self.txt_c.setDisabled(True)

2217 self.txt_d.setDisabled(True)

2218 self.txt_e.setDisabled(True)

2219

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

2221 if self.chk_compound.isChecked():

2222 self.groupBox_6.setDisabled(False)

2223 else:

2224 self.groupBox_6.setDisabled(True)

2225

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

2227 def Set_Watershed_Parameter_tab_default(self):

2228 # Select watershed 콥보 박스 셋팅

2229 self.Set_Watershed_combo()

2230

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

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

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

2234 self.cmbUnsturatedType.addItems(combolist)

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

2236

2237 for interception_method in EnumInterceptionMethod:

2238 self.cmbInterceptionMethodType.addItem(

2239 interception_method.name, interception_method.value

2240 )

2241

2242 for PET_method in EnumPETMethod:

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

2244

2245 for snowmelt_method in EnumSnowMeltMethod:

2246 self.cmbSnowmeltMethodType.addItem(

2247 snowmelt_method.name, snowmelt_method.value

2248 )

2249

2250 ## 최하류 셀값 설정정

2251 self.Set_MostDownStream()

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

2253

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

2255 self.SelectWsCombobox()

2256

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

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

2259 self.SetWatershedstream()

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

2261 self.SelectWsCombobox()

2262

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

2264

2265 def Set_Watershed_combo(self):

2266 WS_list = []

2267 wscount = self._wsinfo.WScount

2268 AllItem = self._wsinfo.WSIDsAll

2269 for i in range(wscount):

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

2271 WS_list.sort()

2272

2273 self.cb_selectws.clear()

2274 self.cb_selectws.addItems(WS_list)

2275

2276 def Set_MostDownStream(self):

2277 if self._SubWatershedCount == 0:

2278 templist = []

2279 if len(self._StreamWSID) > 0:

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

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

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

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

2284

2285 def chage_UnsturatedType(self):

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

2287

2288 value = "0.1"

2289 if self.selectText == "Linear":

2290 value = "0.2"

2291 elif self.selectText == "Exponential":

2292 value = "6.4"

2293

2294 self.txtCoefUnsatruatedk.setText(value)

2295 self.txtCoefUnsatruatedk.setEnabled(True)

2296

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

2298 def SelectWsCombobox(self):

2299 self.project_use_flag = False

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

2301 # 하류 유역 정보 셋팅

2302 selectWS = self.cb_selectws.currentText()

2303 DownSW = []

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

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

2306

2307 for i in range(Dllresult_Down_count):

2308 DownSW.append(Dllresult_Down[i])

2309

2310 if len(DownSW) > 0:

2311 self.lisw_DownWS.clear()

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

2313 if DownSW[i] > 0:

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

2315 self.lisw_DownWS.addItem(item)

2316 else:

2317 self.lisw_DownWS.clear()

2318

2319 # 상류 유역 정보 셋팅

2320 UPSW = []

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

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

2323 for i in range(Dllresult_UP_count):

2324 UPSW.append(Dllresult_UP[i])

2325

2326 # UPSW.extend(Dllresult_UP)

2327 if len(UPSW) > 0:

2328 self.lisw_UpWS.clear()

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

2330 if UPSW[s] > 0:

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

2332 self.lisw_UpWS.addItem(item1)

2333 else:

2334 self.lisw_UpWS.clear()

2335

2336 try:

2337 # global self._wsinfo

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

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

2340

2341 iniSaturation = str(sws_dict.iniSaturation)

2342 minSlopeChBed = str(sws_dict.minSlopeChBed)

2343 minSlopeOF = str(sws_dict.minSlopeOF)

2344

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

2346 UKType = int(sws_dict.unSatKType)

2347 coefUK = str(sws_dict.coefUnsaturatedK)

2348 interceptMethodType = int(sws_dict.interceptMethod)

2349 potentialETMethodType = int(sws_dict.potentialETMethod)

2350 snowMeltMethodType = int(sws_dict.snowMeltMethod)

2351

2352 minChBaseWidth = str(sws_dict.minChBaseWidth)

2353 chRoughness = str(sws_dict.chRoughness)

2354 dryStreamOrder = str(sws_dict.dryStreamOrder)

2355 ccLCRoughness = str(sws_dict.ccLCRoughness)

2356 ccSoilDepth = str(sws_dict.ccSoilDepth)

2357 ccPorosity = str(sws_dict.ccPorosity)

2358 ccWFSuctionHead = str(sws_dict.ccWFSuctionHead)

2359 ccHydraulicK = str(sws_dict.ccHydraulicK)

2360 iniFlow = str(sws_dict.iniFlow)

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

2362 iniFlow = "0"

2363 etCoeff = str(sws_dict.etCoeff)

2364 TempSnowRain = str(sws_dict.tempSnowRain)

2365 smeltingTemp = str(sws_dict.smeltingTemp)

2366 snowCovRatio = str(sws_dict.snowCovRatio)

2367 smeltCoef = str(sws_dict.smeltCoef)

2368

2369 self.txtIniSaturation.setText(iniSaturation)

2370 self.txtMinSlopeOF.setText(minSlopeOF)

2371 self.txtMinSlopeChBed.setText(minSlopeChBed)

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

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

2374 self.txtChRoughness.setText(chRoughness)

2375 self.txtDryStreamOrder.setText(dryStreamOrder)

2376 self.txtCalCoefLCRoughness.setText(ccLCRoughness)

2377 self.txtCalCoefSoilDepth.setText(ccSoilDepth)

2378 self.txtCalCoefPorosity.setText(ccPorosity)

2379 self.txtCalCoefWFSuctionHead.setText(ccWFSuctionHead)

2380 self.txtCalCoefHydraulicK.setText(ccHydraulicK)

2381 self.txtETCoef.setText(etCoeff)

2382 self.txtTempSnowRain.setText(TempSnowRain)

2383 self.txtSnowmeltingTemp.setText(smeltingTemp)

2384 self.txtSnowCovRatio.setText(snowCovRatio)

2385 self.txtSnowmeltCoef.setText(smeltCoef)

2386

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

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

2389 self.cmbUnsturatedType.setCurrentIndex(UKType)

2390 interceptMethod_index = self.cmbInterceptionMethodType.findData(

2391 interceptMethodType

2392 )

2393 self.cmbInterceptionMethodType.setCurrentIndex(interceptMethod_index)

2394 potentialETMethodType_index = self.cmbPETMethodType.findData(

2395 potentialETMethodType

2396 )

2397 self.cmbPETMethodType.setCurrentIndex(potentialETMethodType_index)

2398 snowMeltMethodType_index = self.cmbSnowmeltMethodType.findData(

2399 snowMeltMethodType

2400 )

2401 self.cmbSnowmeltMethodType.setCurrentIndex(snowMeltMethodType_index)

2402

2403 self.txtCoefUnsatruatedk.setText(coefUK)

2404

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

2406 except Exception as e:

2407 self.txtIniSaturation.setText("0.9")

2408 self.txtMinSlopeOF.setText("0.0001")

2409 self.txtMinSlopeChBed.setText("0.0001")

2410

2411 intAll = float(self.GridCellSize)

2412 if intAll > 0:

2413 cal_MinChBaseWidth = intAll / 10

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

2415 self.txtIniFlow.setText("0")

2416

2417 self.cmbUnsturatedType.setCurrentIndex(0)

2418 self.txtCoefUnsatruatedk.setText("0.2")

2419

2420 self.txtChRoughness.setText("0.045")

2421 self.txtDryStreamOrder.setText("0")

2422 self.txtCalCoefLCRoughness.setText("1")

2423 self.txtCalCoefSoilDepth.setText("1")

2424 self.txtCalCoefPorosity.setText("1")

2425 self.txtCalCoefWFSuctionHead.setText("1")

2426 self.txtCalCoefHydraulicK.setText("1")

2427 InterceptionMethod_None_index = self.cmbInterceptionMethodType.findData(10)

2428 self.cmbInterceptionMethodType.setCurrentIndex(

2429 InterceptionMethod_None_index

2430 )

2431 PETMethod_None_index = self.cmbPETMethodType.findData(10)

2432 self.cmbPETMethodType.setCurrentIndex(PETMethod_None_index)

2433 self.txtETCoef.setText("1")

2434 SnowmeltMethod_None_index = self.cmbSnowmeltMethodType.findData(10)

2435 self.cmbSnowmeltMethodType.setCurrentIndex(SnowmeltMethod_None_index)

2436 self.txtTempSnowRain.setText("1")

2437 self.txtSnowmeltingTemp.setText("1")

2438 self.txtSnowCovRatio.setText("1")

2439 self.txtSnowmeltCoef.setText("1")

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

2441 self.lisw_UserSet.addItem(item1)

2442

2443 def UserSet_Add(self):

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

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

2446 if len(items) == 0:

2447 item1 = QListWidgetItem(str(id))

2448 self.lisw_UserSet.addItem(item1)

2449

2450 IniSaturation = self.txtIniSaturation.text()

2451 MinSlopeOF = self.txtMinSlopeOF.text()

2452 MinSlopeChBed = self.txtMinSlopeChBed.text()

2453 IniFlow = self.txtIniFlow.text()

2454

2455 UnsaturatedKType_int = self.cmbUnsturatedType.currentIndex()

2456

2457 CoefUnsatruatedk = self.txtCoefUnsatruatedk.text()

2458 ChRoughness = self.txtChRoughness.text()

2459 DryStreamOrder = self.txtDryStreamOrder.text()

2460 CalCoefLCRoughness = self.txtCalCoefLCRoughness.text()

2461 CalCoefSoilDepth = self.txtCalCoefSoilDepth.text()

2462 CalCoefPorosity = self.txtCalCoefPorosity.text()

2463 CalCoefWFSuctionHead = self.txtCalCoefWFSuctionHead.text()

2464 CalCoefHydraulicK = self.txtCalCoefHydraulicK.text()

2465 interceptMethod = self.cmbInterceptionMethodType.currentData()

2466 potentialETMethod = self.cmbPETMethodType.currentData()

2467 etCoeff = self.txtETCoef.text()

2468 snowMeltMethod = self.cmbSnowmeltMethodType.currentData()

2469 tempSnowRain = self.txtTempSnowRain.text()

2470 smeltingTemp = self.txtSnowmeltingTemp.text()

2471 snowCovRatio = self.txtSnowCovRatio.text()

2472 smeltCoef = self.txtSnowmeltCoef.text()

2473

2474 MinChBaseWidth = self.txtMinChBaseWidth.text()

2475 result = self._wsinfo.setOneSWSParsAndUpdateAllSWSUsingNetwork(

2476 id,

2477 float(IniSaturation),

2478 float(MinSlopeOF),

2479 int(UnsaturatedKType_int),

2480 float(CoefUnsatruatedk),

2481 float(MinSlopeChBed),

2482 float(MinChBaseWidth),

2483 float(ChRoughness),

2484 int(DryStreamOrder),

2485 float(CalCoefLCRoughness),

2486 float(CalCoefSoilDepth),

2487 float(CalCoefPorosity),

2488 float(CalCoefWFSuctionHead),

2489 float(CalCoefHydraulicK),

2490 int(interceptMethod),

2491 int(potentialETMethod),

2492 float(etCoeff),

2493 int(snowMeltMethod),

2494 float(tempSnowRain),

2495 float(smeltingTemp),

2496 float(snowCovRatio),

2497 float(smeltCoef),

2498 float(IniFlow),

2499 )

2500 if result:

2501 MsInfo("Apply parameter was completed")

2502 else:

2503 MsError("Apply parameter was not completed!")

2504

2505 # 사용자 정의 제거 함수

2506 def UserSet_remove(self):

2507 id = self.cb_selectws.currentText()

2508 comboindex = self.cb_selectws.currentIndex()

2509

2510 if id in self._StreamWSID:

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

2512

2513 else:

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

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

2516

2517 if result and items:

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

2519 self.lisw_UserSet.takeItem(index)

2520 MsInfo("Remove parameter was completed")

2521

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

2523 self.SelectWsCombobox()

2524

2525 def SetWatershedstream(self):

2526 self.ID = []

2527 self.IniSaturation = []

2528 self.MinSlopeOF = []

2529 self.MinSlopeChBed = []

2530 self.MinChBaseWidth = []

2531 self.ChRoughness = []

2532 self.DryStreamOrder = []

2533 self.IniFlow = []

2534 self.CalCoefLCRoughness = []

2535 self.CalCoefPorosity = []

2536 self.CalCoefWFSuctionHead = []

2537 self.CalCoefHydraulicK = []

2538 self.CalCoefSoilDepth = []

2539 self.UserSet = []

2540 self.UnsaturatedKType = []

2541 self.CoefUnsaturatedK = []

2542 InterceptionMethod = []

2543 PETMethod = []

2544 ETCoef = []

2545 SnowmeltMethod = []

2546 TempSnowRain = []

2547 SnowmeltingTemp = []

2548 SnowCovRatio = []

2549 SnowmeltCoef = []

2550 doc = ET.parse(self.ProjectFile)

2551 root = doc.getroot()

2552 # 최하류 유역 Id 값

2553 try:

2554 if self._SubWatershedCount == 0:

2555 intAll = float(self.GridCellSize)

2556 cal_MinChBaseWidth = 0

2557

2558 if intAll > 0:

2559 cal_MinChBaseWidth = intAll / 10

2560

2561 for id in self._StreamWSID:

2562 self._wsinfo.setOneSWSParsAndUpdateAllSWSUsingNetwork(

2563 int(id),

2564 1,

2565 0.0001,

2566 1,

2567 0.2,

2568 0.0001,

2569 float(cal_MinChBaseWidth),

2570 0.045,

2571 0,

2572 1,

2573 1,

2574 1,

2575 1,

2576 1,

2577 0,

2578 1,

2579 1,

2580 0,

2581 1,

2582 0,

2583 0,

2584 0,

2585 0,

2586 )

2587

2588 item1 = QListWidgetItem(str(id))

2589 self.lisw_UserSet.addItem(item1)

2590

2591 return

2592

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

2594 if self._SubWatershedCount == 1:

2595 xmltoDict = [xmltoDict]

2596

2597 for i, watershed in enumerate(xmltoDict):

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

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

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

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

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

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

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

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

2606

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2621 usersetString = watershed["UserSet"]

2622 self.UserSet.append(usersetString)

2623

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

2625 UnsaturatedKType_int = 0

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

2627 UnsaturatedKType = self.UnsaturatedKType[i]

2628 if UnsaturatedKType == "Constant":

2629 UnsaturatedKType_int = 0

2630 elif UnsaturatedKType == "Linear":

2631 UnsaturatedKType_int = 1

2632 elif UnsaturatedKType == "Exponential":

2633 UnsaturatedKType_int = 2

2634

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

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

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

2638 if (

2639 usersetString.upper() == "TRUE"

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

2641 ):

2642 self._wsinfo.setOneSWSParsAndUpdateAllSWSUsingNetwork(

2643 int(self.ID[i]),

2644 float(self.IniSaturation[i]),

2645 float(self.MinSlopeOF[i]),

2646 int(UnsaturatedKType_int),

2647 float(self.CoefUnsaturatedK[i]),

2648 float(self.MinSlopeChBed[i]),

2649 float(self.MinChBaseWidth[i]),

2650 float(self.ChRoughness[i]),

2651 int(self.DryStreamOrder[i]),

2652 float(self.CalCoefLCRoughness[i]),

2653 float(self.CalCoefSoilDepth[i]),

2654 float(self.CalCoefPorosity[i]),

2655 float(self.CalCoefWFSuctionHead[i]),

2656 float(self.CalCoefHydraulicK[i]),

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

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

2659 float(ETCoef[i]),

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

2661 float(TempSnowRain[i]),

2662 float(SnowmeltingTemp[i]),

2663 float(SnowCovRatio[i]),

2664 float(SnowmeltCoef[i]),

2665 float(self.IniFlow[i]),

2666 )

2667

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

2669 self.lisw_UserSet.addItem(item1)

2670

2671 except Exception as esd:

2672 MsError(esd)

2673

2674 def SetMostDownStream_combobox(self):

2675 count = self.cb_selectws.count()

2676 for i in range(0, count):

2677 selectWS = self.cb_selectws.itemText(i)

2678

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

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

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

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

2683 self.cb_selectws.setCurrentIndex(i)

2684 return

2685

2686 # ============================ Flow Control 탭 시작 ===============================================

2687 def Set_FlowControl_tab_default(self):

2688 try:

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

2690 self.tlbFlowControl.setEditTriggers(QAbstractItemView.NoEditTriggers)

2691 # 테이블에 초기 셋팅

2692 self.FlowControlTableSetting()

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

2694 self.FlowContorGird_paint()

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

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

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

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

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

2700 self.btnfcgotogrid.clicked.connect(

2701 lambda: self.btnGotoGrid(self.tlbFlowControl)

2702 )

2703

2704 except Exception as e:

2705 MsError(e)

2706

2707 # Flow control 테이블 셋팅

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

2709 def FlowControlTableSetting(self):

2710 try:

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

2712 self.tlbFlowControl.setHorizontalHeaderLabels(self.flowEle)

2713 self.tlbFlowControl.verticalHeader().hide()

2714 pro_file = self._xmltodict["GRMProject"]["ProjectSettings"]["ProjectFile"]

2715

2716 if self._Flowcontrolgrid_flag == False:

2717 self._FlowControlCount = self._FlowControlCount

2718

2719 if self._FlowControlCount < 1:

2720 return

2721

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

2723 if self._FlowControlCount == 1:

2724 flowGrid = [flowGrid]

2725

2726 for i, flowItem in enumerate(flowGrid):

2727 self.tlbFlowControl.insertRow(i)

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

2729 s = ""

2730 if (t in flowItem) and (

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

2732 ):

2733 s = flowItem[t]

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

2735

2736 except Exception as e:

2737 MsError(e)

2738

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

2740 def FlowControlAddCell(self):

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

2742 self._FXCOL = 0

2743 self._FYROW = 0

2744 MsInfo(" No cells selected. ")

2745 else:

2746 self._FXCOL = self.tool._FXCOL

2747 self._FYROW = self.tool._FYROW

2748 self._AddFlowcontrol_Edit_or_Insert_type = "Insert"

2749 results = AddFlowControl(

2750 self._AddFlowcontrol_Edit_or_Insert_type,

2751 _DataTimeFormat=self.dataTimeFormat,

2752 )

2753 results.exec_()

2754

2755 self._AddFlowcontrolFilePath = results._AddFlowcontrolFilePath

2756 self._AddFlowcontrolType = results._AddFlowcontrolType

2757 self._AddFlowcontrolTimeInterval = results._AddFlowcontrolTimeInterval

2758 self._AddFlowcontrolName = results._AddFlowcontrolName

2759 self._AddFlowcontrol_Edit_or_Insert_type = (

2760 results._AddFlowcontrol_Edit_or_Insert_type

2761 )

2762 self._AddFlowcontrol_IniStorage = results._AddFlowcontrol_IniStorage

2763 self._AddFlowcontrol_MaxStorage = results._AddFlowcontrol_MaxStorage

2764 self._AddNomalHighStorage = results._AddNomalHighStorage

2765 self._AddRestrictedStorage = results._AddRestrictedStorage

2766 self._AddRetiPeriodSt = results._AddRetiPeriodSt

2767 self._AddRetiPeriodEd = results._AddRetiPeriodEd

2768 self._AddFlowcontrol_ROType = results._AddFlowcontrol_ROType

2769 self._AddFlowcontrol_AutoROMmaxOutflow_CMS = (

2770 results._AddFlowcontrol_AutoROMmaxOutflow_CMS

2771 )

2772 self._AddFlowcontrol_ROConstQ = results._AddFlowcontrol_ROConstQ

2773 self._AddFlowcontrol_ROConstQDuration = (

2774 results._AddFlowcontrol_ROConstQDuration

2775 )

2776 self._EditFlowFlowDataFile = results._EditFlowFlowDataFile

2777

2778 if self._Flowcontrolgrid_flag:

2779 if self._AddFlowcontrol_Edit_or_Insert_type == "Insert":

2780 self.ADDFlowData()

2781 self._Flowcontrolgrid_flag_Insert = False

2782

2783 def ADDFlowData(self):

2784 try:

2785 counts = self.tlbFlowControl.rowCount()

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

2787 self.tlbFlowControl.insertRow(counts)

2788 self.tlbFlowControl.setItem(

2789 counts, 0, QTableWidgetItem(self._AddFlowcontrolName)

2790 )

2791 self.tlbFlowControl.setItem(

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

2793 )

2794 self.tlbFlowControl.setItem(

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

2796 )

2797

2798 self._FXCOL = 0

2799 self._FYROW = 0

2800 self.tlbFlowControl.setItem(

2801 counts, 3, QTableWidgetItem(self._AddFlowcontrolTimeInterval)

2802 )

2803 self.tlbFlowControl.setItem(

2804 counts, 4, QTableWidgetItem(self._AddFlowcontrolType)

2805 )

2806 self.tlbFlowControl.setItem(

2807 counts, 5, QTableWidgetItem(self._AddFlowcontrolFilePath)

2808 )

2809 self.tlbFlowControl.setItem(

2810 counts, 6, QTableWidgetItem(self._AddFlowcontrol_IniStorage)

2811 )

2812 self.tlbFlowControl.setItem(

2813 counts, 7, QTableWidgetItem(self._AddFlowcontrol_MaxStorage)

2814 )

2815 self.tlbFlowControl.setItem(

2816 counts, 8, QTableWidgetItem(self._AddNomalHighStorage)

2817 )

2818 self.tlbFlowControl.setItem(

2819 counts, 9, QTableWidgetItem(self._AddRestrictedStorage)

2820 )

2821 self.tlbFlowControl.setItem(

2822 counts, 10, QTableWidgetItem(self._AddRetiPeriodSt)

2823 )

2824 self.tlbFlowControl.setItem(

2825 counts, 11, QTableWidgetItem(self._AddRetiPeriodEd)

2826 )

2827 self.tlbFlowControl.setItem(

2828 counts, 12, QTableWidgetItem(self._AddFlowcontrol_ROType)

2829 )

2830 self.tlbFlowControl.setItem(

2831 counts,

2832 13,

2833 QTableWidgetItem(self._AddFlowcontrol_AutoROMmaxOutflow_CMS),

2834 )

2835 self.tlbFlowControl.setItem(

2836 counts, 14, QTableWidgetItem(self._AddFlowcontrol_ROConstQ)

2837 )

2838 self.tlbFlowControl.setItem(

2839 counts, 15, QTableWidgetItem(self._AddFlowcontrol_ROConstQDuration)

2840 )

2841

2842 self._Flowcontrolgrid_flag = True

2843 self.UpdateFlowControl()

2844

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

2846 if self.chkFlowContorGird.isChecked():

2847 self.FlowContorGird_paint()

2848 except Exception as e:

2849 MsError(e)

2850

2851 def FlowControlEdit(self):

2852 self._FlowControlTable = self.tlbFlowControl

2853 row = self.tlbFlowControl.currentRow()

2854 self._EditFlowCurrentRow = row

2855 if row > -1:

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

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

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

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

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

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

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

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

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

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

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

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

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

2869 self._EditFlowAutoROMmaxOutflow_CMS = self.tlbFlowControl.item(

2870 row, 13

2871 ).text()

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

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

2874

2875 self.flowEle

2876 self._AddFlowcontrol_Edit_or_Insert_type = "Edit"

2877 self._FlowControlCount = self._FlowControlCount

2878 results = AddFlowControl(

2879 self._AddFlowcontrol_Edit_or_Insert_type,

2880 self._EditFlowName,

2881 self._EditFlowDT,

2882 self._EditFlowControlType,

2883 self._EditFlowFlowDataFile,

2884 self._EditFlowIniStorage,

2885 self._EditFlowMaxStorage,

2886 self._EditNomalHighStorage,

2887 self._EditRestrictedStorage,

2888 self._EditRetiPeriodSt,

2889 self._EditRetiPeriodEd,

2890 self._EditFlowROType,

2891 self._EditFlowAutoROMmaxOutflow_CMS,

2892 self._EditFlowROConstQ,

2893 self._EditFlowROConstQDuration,

2894 self.dataTimeFormat,

2895 )

2896 results.exec_()

2897

2898 self._FlowControlTable.setItem(

2899 row, 0, QTableWidgetItem(results._EditFlowName)

2900 )

2901 self._FlowControlTable.setItem(

2902 row, 3, QTableWidgetItem(results._EditFlowDT)

2903 )

2904 self._FlowControlTable.setItem(

2905 row, 4, QTableWidgetItem(results._EditFlowControlType)

2906 )

2907 self._FlowControlTable.setItem(

2908 row, 5, QTableWidgetItem(results._EditFlowFlowDataFile)

2909 )

2910 self._FlowControlTable.setItem(

2911 row, 6, QTableWidgetItem(results._EditFlowIniStorage)

2912 )

2913 self._FlowControlTable.setItem(

2914 row, 7, QTableWidgetItem(results._EditFlowMaxStorage)

2915 )

2916 self._FlowControlTable.setItem(

2917 row, 8, QTableWidgetItem(results._EditNomalHighStorage)

2918 )

2919 self._FlowControlTable.setItem(

2920 row, 9, QTableWidgetItem(results._EditRestrictedStorage)

2921 )

2922 self._FlowControlTable.setItem(

2923 row, 10, QTableWidgetItem(results._EditRetiPeriodSt)

2924 )

2925 self._FlowControlTable.setItem(

2926 row, 11, QTableWidgetItem(results._EditRetiPeriodEd)

2927 )

2928 self._FlowControlTable.setItem(

2929 row, 12, QTableWidgetItem(results._EditFlowROType)

2930 )

2931 self._FlowControlTable.setItem(

2932 row, 13, QTableWidgetItem(results._EditFlowAutoROMmaxOutflow_CMS)

2933 )

2934 self._FlowControlTable.setItem(

2935 row, 14, QTableWidgetItem(results._EditFlowROConstQ)

2936 )

2937 self._FlowControlTable.setItem(

2938 row, 15, QTableWidgetItem(results._EditFlowROConstQDuration)

2939 )

2940

2941 self.UpdateFlowControl()

2942

2943 else:

2944 MsInfo("Check! select row ")

2945

2946 def UpdateFlowControl(self):

2947 # 딕셔너리 삭제

2948 if self._FlowControlCount > 0:

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

2950 DictoXml = unparse(self._xmltodict)

2951

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

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

2954 root = xmltree.getroot()

2955 count = self.tlbFlowControl.rowCount()

2956 self._FlowControlCount = count

2957

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

2959 child = ET.Element("FlowControlGrid")

2960 root.append(child)

2961

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

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

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

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

2966 child.append(element)

2967

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

2969 docs = dict(parse(xmltree_string))

2970 self._xmltodict.clear()

2971 self._xmltodict.update(docs)

2972

2973 def tlbFlowControl_clik_enent(self):

2974 global _ClickX, _ClickY

2975 row = self.tlbFlowControl.currentRow()

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

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

2978

2979 def RemoveTalbeRow(self):

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

2981 # 선택된 Row 가 있을때

2982 if row > -1:

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

2984 result = QMessageBox.question(

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

2986 )

2987 if result == QMessageBox.Yes:

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

2989 _Flowcontrolgrid_flag = True

2990 self.tlbFlowControl.removeRow(row)

2991

2992 self.UpdateFlowControl()

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

2994

2995 self.post_grid_remove2()

2996 self.FlowContorGird_paint()

2997 if self.chkWatch_Point.isChecked():

2998 self.watchpoint_paint()

2999

3000 # 2. xy좌표로

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

3002 try:

3003 xc = float(xcoord)

3004 yc = float(ycoord)

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

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

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

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

3009 row = "out of extent"

3010 column = "out of extent"

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

3012 else:

3013 self.tool.Cell_X_Center = (

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

3015 )

3016 self.tool.Cell_Y_Center = (

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

3018 ) # (extent.yMinimum())

3019 if (

3020 self.tool.Cell_X_Center <= self._xmax

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

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

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

3024 ):

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

3026 except Exception as e:

3027 MsError(e)

3028

3029

3030 class CanvasTool(QgsMapTool):

3031 def __init__(self, canvas):

3032 QgsMapTool.__init__(self, canvas)

3033 self.canvas = canvas

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

3035 self._wsinfo = _get_set_control.get_wsinfo()

3036 self._GreenAmptCount = _get_set_control.get_GreenAmptCount()

3037 self._xmltodict = _get_set_control.get_xmltodict()

3038 self._SoilDepthCount = _get_set_control.get_SoilDepthCount()

3039 self._LandCoverCount = _get_set_control.get_LandCoverCount()

3040 self._FYROW = 0

3041 self._YROW = 0

3042 self._FXCOL = 0

3043 self._XCOL = 0

3044

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

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

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

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

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

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

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

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

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

3054 self.Cell_X_Center = 0

3055 self.Cell_Y_Center = 0

3056

3057 def scale_changed(self):

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

3059

3060 def scale_changed_disconnect(self):

3061 try:

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

3063 except:

3064 pass

3065

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

3067 def scale_change_marker(self):

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

3069 self.post_vertex_remove()

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

3071

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

3073 def post_vertex_remove(self):

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

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

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

3077

3078 def create_vertex(self, x, y):

3079 marker = QgsVertexMarker(self.canvas)

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

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

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

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

3084 marker.setIconSize(Size_Marker)

3085 marker.setIconType(QgsVertexMarker.ICON_BOX)

3086 marker.setPenWidth(1)

3087

3088 def getCVID(self, Rt, Ct):

3089 cvid_v = 0

3090 for c in range(self._width):

3091 for r in range(Ct):

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

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

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

3095 QgsPointXY(xxx, yyy), QgsRaster.IdentifyFormatValue

3096 )

3097

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

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

3100 cvid_v = cvid_v + 1

3101

3102 cvid = 0

3103 for cs in range(Rt + 1):

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

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

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

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

3108 QgsPointXY(xxx, yyy), QgsRaster.IdentifyFormatValue

3109 )

3110

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

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

3113 cvid = cvid + 1

3114 return cvid_v + cvid

3115

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

3117 def canvasPressEvent(self, event):

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

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

3120

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

3122 if self.layer is not None:

3123 row, column = self.Point_To_RowColumn(point)

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

3125 self._XCOL = column

3126 self._YROW = row

3127

3128 self._FYROW = self._YROW

3129 self._FXCOL = self._XCOL

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

3131

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

3133 _get_set_control.GlobalLabel_SetText(text)

3134

3135 self.Input_Cell_Value(row, column)

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

3137 row = "out of extent"

3138 column = "out of extent"

3139

3140 else:

3141 self.Cell_X_Center = (

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

3143 )

3144 self.Cell_Y_Center = (

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

3146 )

3147

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

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

3150 QgsRaster.IdentifyFormatValue,

3151 )

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

3153

3154 self._Cnavas_Click_X = self.Cell_X_Center

3155 self._Cnavas_Click_Y = self.Cell_Y_Center

3156 if (

3157 self.Cell_X_Center <= self._xmax

3158 or self._xmin <= self.Cell_X_Center

3159 or self.Cell_Y_Center <= self._ymax

3160 or self._ymin <= self.Cell_Y_Center

3161 ):

3162 self.post_vertex_remove()

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

3164

3165 else:

3166 row = "no raster"

3167 column = "no raster"

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

3169

3170 def Input_Cell_Value(self, x, y):

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

3172 CellCount = self._wsinfo.cellCountInWatershed

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

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

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

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

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

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

3179

3180 _get_set_control.GlobalControl_SetValue(

3181 str(CellCount),

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

3183 str(Stream_Result),

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

3185 str(FA_Result),

3186 str(Slop_Result),

3187 str(watershed),

3188 )

3189

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

3191

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

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

3194

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

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

3197

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

3199 if self._GreenAmptCount > 1:

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

3201 GridValue = GreenAmpt["GridValue"]

3202 if str(Texture_Result) == GridValue:

3203 GRMCode = GreenAmpt["GRMCode"]

3204 Porosity = GreenAmpt["Porosity"]

3205 EffectivePorosity = GreenAmpt["EffectivePorosity"]

3206 WFSoilSuctionHead = GreenAmpt["WFSoilSuctionHead"]

3207 HydraulicConductivity = GreenAmpt["HydraulicConductivity"]

3208 _get_set_control.GlobalControl_texture_SetValue(

3209 GridValue,

3210 GRMCode,

3211 Porosity,

3212 EffectivePorosity,

3213 WFSoilSuctionHead,

3214 HydraulicConductivity,

3215 )

3216 break

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

3218 break

3219 elif self._GreenAmptCount == 1:

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

3221 if str(Texture_Result) == GridValue:

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

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

3224 "Porosity"

3225 ]

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

3227 "EffectivePorosity"

3228 ]

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

3230 "WFSoilSuctionHead"

3231 ]

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

3233 "GreenAmptParameter"

3234 ]["HydraulicConductivity"]

3235 _get_set_control.GlobalControl_texture_SetValue(

3236 GridValue,

3237 GRMCode,

3238 Porosity,

3239 EffectivePorosity,

3240 WFSoilSuctionHead,

3241 HydraulicConductivity,

3242 )

3243

3244 if self._SoilDepthCount > 1:

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

3246 GridValue = SoilDepth["GridValue"]

3247 if str(Depth_Result) == GridValue:

3248 GRMCode = SoilDepth["GRMCode"]

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

3250 SoilDepth = SoilDepth["SoilDepth_cm"]

3251 _get_set_control.GlobalControl_Depth_SetValue(

3252 GridValue, GRMCode, SoilDepth

3253 )

3254 break

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

3256 break

3257

3258 elif self._SoilDepthCount == 1:

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

3260 if str(Depth_Result) == GridValue:

3261 GRMCode = self._xmltodict["GRMProject"]["SoilDepth"]["GRMCode"]

3262 SoilDepth = self._xmltodict["GRMProject"]["SoilDepth"]["SoilDepth_cm"]

3263 _get_set_control.GlobalControl_Depth_SetValue(

3264 GridValue, GRMCode, SoilDepth

3265 )

3266

3267 if self._LandCoverCount > 1:

3268 for LandCover in self._xmltodict["GRMProject"]["LandCover"]:

3269 GridValue = LandCover["GridValue"]

3270 if str(Landcover_Result) == GridValue:

3271 GRMCode = LandCover["GRMCode"]

3272 RoughnessCoefficient = LandCover["RoughnessCoefficient"]

3273 ImperviousRatio = LandCover["ImperviousRatio"]

3274 CanopyRatio = LandCover["CanopyRatio"]

3275 InterceptionMaxWaterCanopy_mm = LandCover[

3276 "InterceptionMaxWaterCanopy_mm"

3277 ]

3278 _get_set_control.GlobalControl_Landcover_SetValue(

3279 GridValue,

3280 GRMCode,

3281 RoughnessCoefficient,

3282 ImperviousRatio,

3283 CanopyRatio,

3284 InterceptionMaxWaterCanopy_mm,

3285 )

3286 break

3287 elif Landcover_Result is None or Landcover_Result == "":

3288 break

3289

3290 elif self._LandCoverCount == 1:

3291 GridValue = self._xmltodict["GRMProject"]["LandCover"]["GridValue"]

3292 if str(Depth_Result) == GridValue:

3293 GRMCode = self._xmltodict["GRMProject"]["LandCover"]["GRMCode"]

3294 RoughnessCoefficient = self._xmltodict["GRMProject"]["LandCover"][

3295 "RoughnessCoefficient"

3296 ]

3297 ImperviousRatio = self._xmltodict["GRMProject"]["LandCover"][

3298 "ImperviousRatio"

3299 ]

3300 CanopyRatio = self._xmltodict["GRMProject"]["LandCover"]["CanopyRatio"]

3301 InterceptionMaxWaterCanopy_mm = self._xmltodict["GRMProject"][

3302 "LandCover"

3303 ]["InterceptionMaxWaterCanopy_mm"]

3304 _get_set_control.GlobalControl_Landcover_SetValue(

3305 GridValue,

3306 GRMCode,

3307 RoughnessCoefficient,

3308 ImperviousRatio,

3309 CanopyRatio,

3310 InterceptionMaxWaterCanopy_mm,

3311 )

3312

3313 def Point_To_RowColumn(self, point):

3314 column = int(((self._ymax - point.y()) / self._ysize))

3315 row = int(((point.x() - self._xmin) / self._xsize))

3316 return row, column

3317

3318 def canvasMoveEvent(self, event):

3319 x = event.pos().x()

3320 y = event.pos().y()

3321 point = self.canvas.getCoordinateTransform().toMapCoordinates(x, y)

3322

3323 def canvasReleaseEvent(self, event):

3324 # Get the click

3325 x = event.pos().x()

3326 y = event.pos().y()

3327 point = self.canvas.getCoordinateTransform().toMapCoordinates(x, y)

3328

3329 def activate(self):

3330 pass

3331

3332 def deactivate(self):

3333 pass

3334

3335 def isZoomTool(self):

3336 return False

3337

3338 def isTransient(self):

3339 return False

3340

3341 def isEditTool(self):

3342 return True

3343

3344 # canvas event

3345 def ZoomtoExtent(self):

3346 self.canvas.zoomToFullExtent()

3347 self.canvas.refresh()

3348

3349 def ZoomtoNextExtent(self):

3350 self.canvas.zoomToNextExtent()

3351 self.canvas.refresh()

3352

3353 def ZoomtoPrevious(self):

3354 self.canvas.zoomToPreviousExtent()

3355 self.canvas.refresh()

3356

3357 def canvas_zoomIn(self):

3358 actionZoomIn = QAction(self)

3359 self.toolZoomIn = QgsMapToolZoom(self.canvas, False) # false = in

3360 self.toolZoomIn.setAction(actionZoomIn)

3361 self.canvas.setMapTool(self.toolZoomIn)

3362 self.canvas.refresh()

3363

3364 def canvas_zoomOut(self):

3365 actionZoomOut = QAction(self)

3366 self.toolZoomOut = QgsMapToolZoom(self.canvas, True) # True = out

3367 self.toolZoomOut.setAction(actionZoomOut)

3368 self.canvas.setMapTool(self.toolZoomOut)

3369 self.canvas.refresh()

3370

3371 def canvas_pan(self):

3372 actionPan = QAction(self)

3373 self.toolPan = QgsMapToolPan(self.canvas)

3374 self.toolPan.setAction(actionPan)

3375 self.canvas.setMapTool(self.toolPan)

3376

3377 #

3378 # #2017/11/23----------------------

3379 def channel_width_cal(self, FAcvalue):

3380 # mw에서는 line edit 값을 바꿀 수 있고 그에 따라 결과 값이 바뀜. 일단 여기는 이렇세 처리함

3381 c = float(1.698)

3382 d = float(0.318)

3383 e = float(0.5)

3384

3385 # FAc 는 cell 값, Slope는 gmp의 MinSlopeChBed 값임

3386 slope = float(0.0005)

3387

3388 width = (

3389 c

3390 * pow((FAcvalue * (self._xsize * self._xsize / 1000000)), d)

3391 / pow(slope, e)

3392 )

3393 try:

3394 User_Cw = "%.3f" % width

3395 except Exception as e:

3396 return "0"

3397 return str(User_Cw)