Repository navigation
Expand file tree
/
Copy pathExtract_USGS_Config.py
More file actions
269 lines (218 loc) · 7.59 KB
/
Copy pathExtract_USGS_Config.py
File metadata and controls
269 lines (218 loc) · 7.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# -------------------------------------------------------------------
# Extract USGS Config Builder
#
# Creates/edits a .config file that stores:
# - path to a .usgs file
# - path to a TimeSeries.dss file
#
# Intended for use with Extract_USGS script
# -------------------------------------------------------------------
from java.awt import BorderLayout, GridBagLayout, GridBagConstraints, Insets
from java.awt.event import ActionListener
from javax.swing import JDialog, JPanel, JLabel, JTextField, JButton, JFileChooser, JOptionPane, SwingUtilities
from javax.swing.filechooser import FileNameExtensionFilter
from hec2.rts.script import RTS
import os, java.io
CONFIG_VERSION = "1"
DEFAULT_CONFIG_NAME = "extract_usgs.config"
# Watershed context
WATERSHED_NAME = str(RTS.getWatershed())
PROJ_DIR = RTS.getWatershed().getProjectDirectory()
CWMS_HOME = os.path.normpath(os.path.join(PROJ_DIR, "..", ".."))
# Default .usgs location: <projectDir>\shared\source\<Watershed>.usgs
DEFAULT_USGS_PATH = os.path.join(PROJ_DIR, "shared", "source", WATERSHED_NAME + ".usgs")
# Default DSS location: go up two directories from <projectDir>, then: database\USGS\<Watershed>_TimeSeries.dss
DEFAULT_DSS_PATH = os.path.join(CWMS_HOME, "database", "USGS_Data", WATERSHED_NAME + "_TimeSeries.dss")
def _abs_norm(p):
if p is None:
return ""
p = p.strip()
if not p:
return ""
return os.path.abspath(p)
def load_config(config_path):
data = {
"version": CONFIG_VERSION,
"usgs_file": "",
"dss_file": "",
}
if not config_path or (not os.path.isfile(config_path)):
return data
f = None
try:
f = open(config_path, "r")
for raw in f:
line = raw.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
continue
k, v = line.split("=", 1)
k = k.strip()
v = v.strip()
if k in data:
data[k] = v
finally:
if f:
f.close()
return data
def save_config(config_path, usgs_file, dss_file):
usgs_file = _abs_norm(usgs_file)
dss_file = _abs_norm(dss_file)
f = None
try:
f = open(config_path, "w")
f.write("# USGS paths config\n")
f.write("version={0}\n".format(CONFIG_VERSION))
f.write("usgs_file={0}\n".format(usgs_file))
f.write("dss_file={0}\n".format(dss_file))
finally:
if f:
f.close()
def choose_file(parent, title, extensions, desc, initial_path=None, directories_only=False):
fc = JFileChooser()
if initial_path:
try:
if os.path.isdir(initial_path):
fc.setCurrentDirectory(java.io.File(initial_path))
elif os.path.isfile(initial_path):
fc.setSelectedFile(java.io.File(initial_path))
fc.setCurrentDirectory(java.io.File(os.path.dirname(initial_path)))
except:
pass
fc.setDialogTitle(title)
if directories_only:
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
else:
if extensions:
fc.setFileFilter(FileNameExtensionFilter(desc, extensions))
rc = fc.showOpenDialog(parent)
if rc == JFileChooser.APPROVE_OPTION:
return str(fc.getSelectedFile().getAbsolutePath())
return None
class USGSConfigDialog(JDialog):
def __init__(self, parent, config_path):
JDialog.__init__(self, parent, "USGS Paths Configuration", True)
self.config_path = config_path
loaded = load_config(config_path)
usgs_default = loaded.get("usgs_file", "").strip() or DEFAULT_USGS_PATH
dss_default = loaded.get("dss_file", "").strip() or DEFAULT_DSS_PATH
self.usgsField = JTextField(usgs_default, 45)
self.dssField = JTextField(dss_default, 45)
self._build_ui(parent)
self.pack()
self.setLocationRelativeTo(parent)
def _build_ui(self, parent):
panel = JPanel(GridBagLayout())
gbc = GridBagConstraints()
gbc.insets = Insets(6, 6, 6, 6)
gbc.fill = GridBagConstraints.HORIZONTAL
# Row 0: config path label
gbc.gridx = 0
gbc.gridy = 0
gbc.gridwidth = 3
panel.add(JLabel("Config file: {0}".format(self.config_path)), gbc)
# Row 1: USGS file
gbc.gridwidth = 1
gbc.gridy = 1
gbc.gridx = 0
panel.add(JLabel("Select .usgs file:"), gbc)
gbc.gridx = 1
panel.add(self.usgsField, gbc)
btnBrowseUSGS = JButton("Browse...")
gbc.gridx = 2
panel.add(btnBrowseUSGS, gbc)
# Row 2: DSS file
gbc.gridy = 2
gbc.gridx = 0
panel.add(JLabel("Select output dss file:"), gbc)
gbc.gridx = 1
panel.add(self.dssField, gbc)
btnBrowseDSS = JButton("Browse...")
gbc.gridx = 2
panel.add(btnBrowseDSS, gbc)
# Row 3: Buttons
btnPanel = JPanel()
btnSave = JButton("Save")
btnCancel = JButton("Cancel")
btnPanel.add(btnSave)
btnPanel.add(btnCancel)
# Wiring actions
class BrowseUSGS(ActionListener):
def actionPerformed(self, event):
initial = self_outer.usgsField.getText().strip()
if not initial:
initial = os.path.join(PROJ_DIR, "shared", "source")
path = choose_file(
self_outer,
"Select .usgs file",
["usgs"],
"USGS Control File (*.usgs)",
initial_path=initial,
directories_only=False
)
if path:
self_outer.usgsField.setText(path)
class BrowseDSS(ActionListener):
def actionPerformed(self, event):
initial = self_outer.dssField.getText().strip()
if not initial:
initial = PROJ_DIR
path = choose_file(
self_outer,
"Select DSS file",
["dss"],
"HEC-DSS File (*.dss)",
initial_path=initial,
directories_only=False
)
if path:
self_outer.dssField.setText(path)
class SaveAction(ActionListener):
def actionPerformed(self, event):
usgs_path = _abs_norm(self_outer.usgsField.getText())
dss_path = _abs_norm(self_outer.dssField.getText())
# Basic validation
if (not usgs_path) or (not usgs_path.lower().endswith(".usgs")):
JOptionPane.showMessageDialog(self_outer, "Please select a valid .usgs file.", "Validation", JOptionPane.WARNING_MESSAGE)
return
if not os.path.isfile(usgs_path):
JOptionPane.showMessageDialog(self_outer, "The .usgs file does not exist:\n{0}".format(usgs_path), "Validation", JOptionPane.WARNING_MESSAGE)
return
if (not dss_path) or (not dss_path.lower().endswith(".dss")):
JOptionPane.showMessageDialog(self_outer, "Please select a valid .dss file.", "Validation", JOptionPane.WARNING_MESSAGE)
return
# Create directory for config file if needed
cfg_dir = os.path.dirname(self_outer.config_path)
if cfg_dir and (not os.path.isdir(cfg_dir)):
try:
os.makedirs(cfg_dir)
except Exception as e:
JOptionPane.showMessageDialog(self_outer, "Could not create config directory:\n{0}\n\n{1}".format(cfg_dir, e), "Error", JOptionPane.ERROR_MESSAGE)
return
try:
save_config(self_outer.config_path, usgs_path, dss_path)
except Exception as e:
JOptionPane.showMessageDialog(self_outer, "Failed to save config:\n{0}".format(e), "Error", JOptionPane.ERROR_MESSAGE)
return
JOptionPane.showMessageDialog(self_outer, "Saved:\n{0}".format(self_outer.config_path), "Saved", JOptionPane.INFORMATION_MESSAGE)
self_outer.dispose()
class CancelAction(ActionListener):
def actionPerformed(self, event):
self_outer.dispose()
self_outer = self
btnBrowseUSGS.addActionListener(BrowseUSGS())
btnBrowseDSS.addActionListener(BrowseDSS())
btnSave.addActionListener(SaveAction())
btnCancel.addActionListener(CancelAction())
self.getContentPane().setLayout(BorderLayout())
self.getContentPane().add(panel, BorderLayout.CENTER)
self.getContentPane().add(btnPanel, BorderLayout.SOUTH)
def run_dialog(config_path, parent=None):
dlg = USGSConfigDialog(parent, config_path)
dlg.setVisible(True)
# -------------------
# Choose config path
# -------------------
config_path = os.path.join(PROJ_DIR, "shared", "source", DEFAULT_CONFIG_NAME)
SwingUtilities.invokeLater(lambda: run_dialog(config_path, None))