HmsFileParser¶
Internal parsing utilities for HMS file formats.
hms_commander._parsing.HmsFileParser
¶
Common parser for HMS ASCII text files (.basin, .met, .control, .gage).
Provides static methods for file I/O and content parsing with consistent encoding handling and block/parameter extraction patterns.
This class consolidates ~230 lines of duplicated parsing logic from HmsBasin, HmsMet, HmsControl, and HmsGage classes.
Source code in hms_commander/_parsing.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 | |
read_file(file_path)
staticmethod
¶
Read HMS file with UTF-8 → CP1252 → Latin-1 encoding fallback.
HMS files may use different encodings depending on when they were created and what characters they contain. This method tries UTF-8 first, then falls back to Latin-1 if decoding fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Union[str, Path]
|
Path to HMS file (.basin, .met, .control, .gage, etc.) |
required |
Returns:
| Type | Description |
|---|---|
str
|
File content as string |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file doesn't exist |
Example
content = HmsFileParser.read_file("model.basin") print(len(content)) 5432
Source code in hms_commander/_parsing.py
write_file(file_path, content, encoding='utf-8')
staticmethod
¶
Write HMS file with specified encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Union[str, Path]
|
Output file path |
required |
content
|
str
|
File content string |
required |
encoding
|
str
|
Character encoding (default: utf-8) |
'utf-8'
|
Example
HmsFileParser.write_file("model.basin", updated_content)
Source code in hms_commander/_parsing.py
parse_blocks(content, block_keyword)
staticmethod
¶
Parse HMS file into named blocks (e.g., "Subbasin:", "Gage:", "Reach:").
Handles patterns like
Subbasin: Sub1 Area: 100.0 Downstream: Junction-1 End:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
str
|
HMS file content |
required |
block_keyword
|
str
|
Block type (Subbasin, Junction, Reach, Gage, etc.) |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Dict[str, str]]
|
Dict mapping element names to their attribute dictionaries |
Example
blocks = HmsFileParser.parse_blocks(content, "Subbasin") print(blocks["Sub1"]["Area"]) '100.0' print(blocks["Sub1"]["Downstream"]) 'Junction-1'
Source code in hms_commander/_parsing.py
find_all_blocks(content, block_keyword)
staticmethod
¶
Find all blocks of a given type, returning match objects with positions.
Unlike parse_blocks() which returns only parsed data, this method preserves the regex Match objects so callers can do positional replacement (e.g., reverse-iteration for in-place editing).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
str
|
HMS file content |
required |
block_keyword
|
str
|
Block type (Subbasin, Junction, Reach, etc.) |
required |
Returns:
| Type | Description |
|---|---|
List[Tuple[Match, str, Dict[str, str]]]
|
List of (match_object, element_name, parsed_attrs) tuples, |
List[Tuple[Match, str, Dict[str, str]]]
|
ordered by position in file. |
Example
blocks = HmsFileParser.find_all_blocks(content, "Subbasin") for match, name, attrs in reversed(blocks): ... # Edit in reverse order to preserve string offsets ... content = content[:match.start()] + new_block + content[match.end():]
Source code in hms_commander/_parsing.py
parse_named_section(content, section_keyword)
staticmethod
¶
Parse a single named section (e.g., "Meteorology:", "Control:").
Different from parse_blocks() because these sections typically appear once per file and may not have explicit "End:" markers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
str
|
HMS file content |
required |
section_keyword
|
str
|
Section type (e.g., "Meteorology", "Control") |
required |
Returns:
| Type | Description |
|---|---|
Tuple[str, Dict[str, str]]
|
Tuple of (section_name, section_parameters) |
Example
name, params = HmsFileParser.parse_named_section(content, "Control") print(name) 'Jan2020' print(params["Start Date"]) '01Jan2020'
Source code in hms_commander/_parsing.py
update_parameter(content, param_name, new_value)
staticmethod
¶
Update a parameter value in HMS file content.
Searches for the parameter by name and replaces its value while preserving the file structure and formatting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
str
|
HMS file content or block content |
required |
param_name
|
str
|
Parameter name to update (case-sensitive) |
required |
new_value
|
Union[str, int, float]
|
New value to set |
required |
Returns:
| Type | Description |
|---|---|
Tuple[str, bool]
|
Tuple of (modified content, whether change was made) |
Example
updated, changed = HmsFileParser.update_parameter( ... content, "Initial Deficit", 1.0 ... ) if changed: ... print("Parameter updated successfully")
Source code in hms_commander/_parsing.py
find_block(content, block_keyword, block_name)
staticmethod
¶
Find a specific named block in content.
Used when you need to locate and potentially replace a specific block (e.g., a particular Subbasin or Gage).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
str
|
HMS file content |
required |
block_keyword
|
str
|
Block type (e.g., "Subbasin") |
required |
block_name
|
str
|
Name of the specific block to find |
required |
Returns:
| Type | Description |
|---|---|
Optional[Match]
|
Tuple of (match_object, header, block_content, footer) |
str
|
Returns (None, '', '', '') if block not found |
Example
match, header, body, footer = HmsFileParser.find_block( ... content, "Subbasin", "Sub-1" ... ) if match: ... print(f"Found block with {len(body)} characters")
Source code in hms_commander/_parsing.py
replace_block(content, match, new_block_content)
staticmethod
¶
Replace a block's content while preserving header and footer.
Use with find_block() to locate a block, modify its content, and replace it in the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
str
|
Original file content |
required |
match
|
Match
|
Match object from find_block() |
required |
new_block_content
|
str
|
New content for the block body |
required |
Returns:
| Type | Description |
|---|---|
str
|
Updated file content |
Example
match, header, body, footer = HmsFileParser.find_block( ... content, "Subbasin", "Sub-1" ... ) modified_body = body.replace("Area: 100", "Area: 150") updated = HmsFileParser.replace_block(content, match, modified_body)
Source code in hms_commander/_parsing.py
to_numeric(value)
staticmethod
¶
Convert string value to float if possible, otherwise return original string.
Handles scientific notation (e.g., '1.3824636581E7') and regular decimals. Returns original string if conversion fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
String value to convert |
required |
Returns:
| Type | Description |
|---|---|
Union[float, str]
|
Float if conversion succeeds, original string otherwise |
Example
HmsFileParser.to_numeric("123.45") 123.45 HmsFileParser.to_numeric("1.5E6") 1500000.0 HmsFileParser.to_numeric("Junction-1") 'Junction-1'