Skip to content

Commit 4aaf5ae

Browse files
authored
Apply ruff check rules, add pre-commit configuration (#45)
* Rewrite os module with pathlib and subrocess modules * Apply I isort rule * Apply E, W pycodestyle rules, also a few ruff format fixes * Apply UP pyupgrade rule * Apply F Pyflakes rule, with a few TODOs added * Apply RET flake8-return rule * Apply D pydocstyle rule
1 parent 85edbcf commit 4aaf5ae

24 files changed

+356
-337
lines changed

.pre-commit-config.yaml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
ci:
2+
autoupdate_schedule: quarterly
3+
exclude: \.grb$
4+
repos:
5+
- repo: https://github.com/pre-commit/pre-commit-hooks
6+
rev: v5.0.0
7+
hooks:
8+
- id: check-yaml
9+
- repo: https://github.com/astral-sh/ruff-pre-commit
10+
rev: v0.9.3
11+
hooks:
12+
# Run the linter.
13+
- id: ruff
14+
args: [ --fix ]
15+
# Run the formatter.
16+
- id: ruff-format

docs/pestutilslib/docx_to_md.py

Lines changed: 40 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
import sys
2-
import os
1+
from subprocess import run
32

43

54
def processFile(inFile, outFile):
6-
mdFile = open(inFile, "r")
5+
mdFile = open(inFile)
76
toc = []
87
levels = [0, 0, 0, 0, 0]
98
newFile = open(outFile, "w")
@@ -14,8 +13,7 @@ def processFile(inFile, outFile):
1413
for line in mdFile:
1514
if partOfToc and line != "\n":
1615
continue
17-
else:
18-
partOfToc = False
16+
partOfToc = False
1917
if "Table of Contents" in line:
2018
tocLoc = len(tempFile) + 1
2119
partOfToc = True
@@ -39,8 +37,7 @@ def processFile(inFile, outFile):
3937

4038
def addSectionTag(line, secId):
4139
startIndex = line.find(" ")
42-
line = line[: startIndex + 1] + "<a id='" + secId + "' />" + line[startIndex + 1 :]
43-
return line
40+
return line[: startIndex + 1] + "<a id='" + secId + "' />" + line[startIndex + 1 :]
4441

4542

4643
def buildToc(line, toc, levels):
@@ -78,8 +75,7 @@ def buildToc(line, toc, levels):
7875

7976
def cleanLine(text):
8077
text = stripNewline(text)
81-
text = removeAnchors(text)
82-
return text
78+
return removeAnchors(text)
8379

8480

8581
def stripNewline(text):
@@ -96,13 +92,21 @@ def removeAnchors(text):
9692

9793
def clean(docx_file, inFile, outFile, run_pandoc=True):
9894
if run_pandoc:
99-
os.system(
100-
"pandoc -t gfm --wrap=none --extract-media . -o file.md {0} --mathjax".format(
101-
docx_file
102-
)
103-
)
104-
num_str = [str(i) for i in range(1, 11)]
105-
lines = open(inFile, "r").readlines()
95+
cmds = [
96+
"pandoc",
97+
"-t",
98+
"gfm",
99+
"--wrap=none",
100+
"--extract-media",
101+
".",
102+
"-o",
103+
"file.md",
104+
docx_file,
105+
"--mathjax",
106+
]
107+
run(cmds, check=True)
108+
# num_str = [str(i) for i in range(1, 11)]
109+
lines = open(inFile).readlines()
106110

107111
# notoc_lines = []
108112
i = 0
@@ -112,9 +116,11 @@ def clean(docx_file, inFile, outFile, run_pandoc=True):
112116
# while True:
113117
# i += 1
114118
# line = lines[i]
115-
# if line.lower().strip().startswith("introduction") or line.lower().strip().startswith("# introduction") :
119+
# if line.lower().strip().startswith(
120+
# "introduction"
121+
# ) or line.lower().strip().startswith("# introduction"):
116122
# break
117-
# #print(line)
123+
# # print(line)
118124
# notoc_lines.append(line)
119125
# i += 1
120126
# lines = notoc_lines
@@ -132,19 +138,18 @@ def clean(docx_file, inFile, outFile, run_pandoc=True):
132138
)
133139
if "blockquote" in lines[i]:
134140
lines[i] = lines[i].replace("<blockquote>", "").replace("</blockquote>", "")
135-
if lines[i].strip().startswith("$") and not "bmatrix" in lines[i].lower():
141+
if lines[i].strip().startswith("$") and "bmatrix" not in lines[i].lower():
136142
label = lines[i].split()[-1]
137143
eq_str = lines[i].replace("$$", "$").split("$")[1]
138144
eq_str = (
139-
r"{0}".format(eq_str)
140-
.replace("\\\\", "\\")
145+
rf"{eq_str}".replace("\\\\", "\\")
141146
.replace(" \\ ", " ")
142147
.replace("\\_", "_")
143148
)
144-
math_str_pre = '<img src="https://latex.codecogs.com/svg.latex?\Large&space;{0}'.format(
145-
eq_str
149+
math_str_pre = (
150+
rf'<img src="https://latex.codecogs.com/svg.latex?\Large&space;{eq_str}'
146151
)
147-
math_str_post = '" title="\Large {0}" /> {1} <br>'.format(eq_str, label)
152+
math_str_post = rf'" title="\Large {eq_str}" /> {label} <br>'
148153
lines[i] = math_str_pre + " " + math_str_post
149154
if lines[i].strip().startswith("<table>"): # and "pcf" in lines[i].lower():
150155
lines[i] = '<div style="text-align: left">' + lines[i] + "</div>"
@@ -165,9 +170,17 @@ def clean(docx_file, inFile, outFile, run_pandoc=True):
165170
# lines.pop(i)
166171
# if "bmatrix" in lines[i].lower():
167172
# break
168-
# eq_str = r"{0}".format(eq_str).replace("\\\\", "\\").replace(" \\ ", " ").replace("\\_", "_")
169-
# math_str_pre = "<img src=\"https://latex.codecogs.com/svg.latex?\Large&space;{0}".format(eq_str)
170-
# math_str_post = "\" title=\"\Large {0}\" />".format(eq_str)
173+
# eq_str = (
174+
# r"{0}".format(eq_str)
175+
# .replace("\\\\", "\\")
176+
# .replace(" \\ ", " ")
177+
# .replace("\\_", "_")
178+
# )
179+
# math_str_pre = '<img src="https://latex.codecogs.com/svg.latex'\
180+
# '?\Large&space;{0}'.format(
181+
# eq_str
182+
# )
183+
# math_str_post = '" title="\Large {0}" />'.format(eq_str)
171184
# lines[i] = math_str_pre + " " + math_str_post
172185

173186
i += 1

examples/clear_output_all.py

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
1-
import os
1+
from pathlib import Path
2+
from subprocess import run
23

3-
dirs = ["."]
44
notebook_count = 0
5-
for d in dirs:
6-
nb_files = [
7-
os.path.join(d, f) for f in os.listdir(d) if f.lower().endswith(".ipynb")
8-
]
9-
for nb_file in nb_files:
10-
print("clearing", nb_file)
11-
os.system(
12-
"jupyter nbconvert --ClearOutputPreprocessor.enabled=True --ClearMetadataPreprocessor.enabled=True --inplace {0}".format(
13-
nb_file
14-
)
15-
)
16-
notebook_count += 1
17-
print(notebook_count, " notebooks cleared")
5+
for nb_file in Path(__file__).parent.rglob("*.ipynb"):
6+
print("clearing", nb_file)
7+
run(
8+
[
9+
"jupyter",
10+
"nbconvert",
11+
"--ClearOutputPreprocessor.enabled=True",
12+
"--ClearMetadataPreprocessor.enabled=True",
13+
"--inplace",
14+
nb_file,
15+
],
16+
check=True,
17+
)
18+
notebook_count += 1
19+
print(notebook_count, "notebooks cleared")

examples/exploring_lowlevel_pypestutils_functions.ipynb

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,13 @@
1616
"outputs": [],
1717
"source": [
1818
"import os\n",
19-
"import sys\n",
2019
"import shutil\n",
21-
"import subprocess as sp\n",
20+
"from datetime import datetime\n",
2221
"\n",
23-
"import numpy as np\n",
24-
"import pandas as pd\n",
22+
"import flopy\n",
2523
"import matplotlib.pyplot as plt\n",
26-
"\n",
27-
"import flopy"
24+
"import numpy as np\n",
25+
"import pandas as pd"
2826
]
2927
},
3028
{
@@ -293,7 +291,7 @@
293291
" ax.pcolormesh(Easting, Northing, mtop)\n",
294292
" ax.scatter(kdf.x, kdf.y, marker=\"^\", c=\"k\", label=\"gw level loc\")\n",
295293
" ax.legend(loc=\"upper left\")\n",
296-
" ax.set_title(\"gw level locations in layer {0}\".format(lay), loc=\"left\")"
294+
" ax.set_title(f\"gw level locations in layer {lay}\", loc=\"left\")"
297295
]
298296
},
299297
{
@@ -850,7 +848,6 @@
850848
"aa_pp = aa * pp_space * 10 # ?\n",
851849
"zone_pp = np.ones_like(ppeasting, dtype=int)\n",
852850
"fac_file = os.path.join(w_d, \"factors.bin\")\n",
853-
"from datetime import datetime\n",
854851
"\n",
855852
"s = datetime.now()\n",
856853
"ipts = lib.calc_kriging_factors_2d(\n",

examples/exploring_pypestutils_helpers.ipynb

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,11 @@
1616
"outputs": [],
1717
"source": [
1818
"import os\n",
19-
"import sys\n",
2019
"import shutil\n",
21-
"import subprocess as sp\n",
2220
"\n",
21+
"import matplotlib.pyplot as plt\n",
2322
"import numpy as np\n",
24-
"import pandas as pd\n",
25-
"import matplotlib.pyplot as plt"
23+
"import pandas as pd"
2624
]
2725
},
2826
{

examples/ppu_helpers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import os
2-
import pyemu
32

43

54
def setup_pps(d):
@@ -10,10 +9,11 @@ def setup_pps(d):
109

1110

1211
def apply_pps():
13-
from pypestutils import helpers
1412
import numpy as np
1513
import pandas as pd
1614

15+
from pypestutils import helpers
16+
1717
df = pd.read_csv("pp_info.csv")
1818
gridspec_fname = "org.grb"
1919
for model_file, pp_file in zip(df.model_file, df.pp_file):

examples/pypestutils_pstfrom_quadtree_mf6.ipynb

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,10 @@
2222
"source": [
2323
"import os\n",
2424
"import shutil\n",
25+
"\n",
26+
"import matplotlib.pyplot as plt\n",
2527
"import numpy as np\n",
26-
"import pandas as pd\n",
27-
"import matplotlib.pyplot as plt"
28+
"import pandas as pd"
2829
]
2930
},
3031
{
@@ -40,8 +41,8 @@
4041
"metadata": {},
4142
"outputs": [],
4243
"source": [
43-
"import pyemu\n",
44-
"import flopy"
44+
"import flopy\n",
45+
"import pyemu"
4546
]
4647
},
4748
{
@@ -529,7 +530,7 @@
529530
"metadata": {},
530531
"outputs": [],
531532
"source": [
532-
"with open(os.path.join(template_ws, tpl_files[0]), \"r\") as f:\n",
533+
"with open(os.path.join(template_ws, tpl_files[0])) as f:\n",
533534
" for _ in range(4):\n",
534535
" print(f.readline().strip())"
535536
]
@@ -560,7 +561,7 @@
560561
"metadata": {},
561562
"outputs": [],
562563
"source": [
563-
"_ = [print(line.rstrip()) for line in open(\"ppu_helpers.py\", \"r\").readlines()]"
564+
"_ = [print(line.rstrip()) for line in open(\"ppu_helpers.py\").readlines()]"
564565
]
565566
},
566567
{

examples/pypestutils_pstfrom_structured_mf6.ipynb

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,10 @@
2222
"source": [
2323
"import os\n",
2424
"import shutil\n",
25+
"\n",
26+
"import matplotlib.pyplot as plt\n",
2527
"import numpy as np\n",
26-
"import pandas as pd\n",
27-
"import matplotlib.pyplot as plt"
28+
"import pandas as pd"
2829
]
2930
},
3031
{
@@ -40,8 +41,8 @@
4041
"metadata": {},
4142
"outputs": [],
4243
"source": [
43-
"import pyemu\n",
44-
"import flopy"
44+
"import flopy\n",
45+
"import pyemu"
4546
]
4647
},
4748
{
@@ -612,7 +613,7 @@
612613
"metadata": {},
613614
"outputs": [],
614615
"source": [
615-
"with open(os.path.join(template_ws, tpl_files[0]), \"r\") as f:\n",
616+
"with open(os.path.join(template_ws, tpl_files[0])) as f:\n",
616617
" for _ in range(4):\n",
617618
" print(f.readline().strip())"
618619
]
@@ -643,7 +644,7 @@
643644
"metadata": {},
644645
"outputs": [],
645646
"source": [
646-
"_ = [print(line.rstrip()) for line in open(\"ppu_helpers.py\", \"r\").readlines()]"
647+
"_ = [print(line.rstrip()) for line in open(\"ppu_helpers.py\").readlines()]"
647648
]
648649
},
649650
{

0 commit comments

Comments
 (0)