Skip to content

Commit

Permalink
Merge pull request dailyerosion#219 from akrherz/240322
Browse files Browse the repository at this point in the history
Omnibus
  • Loading branch information
akrherz authored Apr 2, 2024
2 parents 6d66fb3 + f99643f commit c47eef6
Show file tree
Hide file tree
Showing 21 changed files with 673 additions and 511 deletions.
17 changes: 12 additions & 5 deletions .github/workflows/pydep.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
PYTHON_VERSION: ["3.9", "3.10", "3.11"]
PYTHON_VERSION: ["3.9", "3.11", "3.12"]
env:
PYTHON_VERSION: ${{ matrix.PYTHON_VERSION }}
steps:
Expand All @@ -26,6 +26,12 @@ jobs:
run: |
cat .github/workflows/etchosts.txt | sudo tee -a /etc/hosts
# daryl is a hack
- name: Create symlink
run: |
set -e
sudo ln -s `pwd` /opt/dep
# setup conda-forge with micromamba
- name: Setup Python
uses: mamba-org/setup-micromamba@v1
Expand Down Expand Up @@ -56,12 +62,13 @@ jobs:
run: |
set -e
python -m pip install . --upgrade --no-deps
coverage run --source=pydep setup.py test
coverage xml
python -m pytest --cov=pydep tests
python -m coverage xml
- name: Upload codecov
if: ${{ env.PYTHON_VERSION == '3.11' }}
uses: codecov/codecov-action@v3
if: ${{ env.PYTHON_VERSION == '3.12' }}
uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: coverage.xml
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
**/*.xlsx
**/*.txt
**/*.pptx
**/*.feather
/.vscode
prj2wepp/wepp/hill.slp
prj2wepp/wepp/data/managements
Expand Down
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.3.4"
rev: "v0.3.5"
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
Expand Down
8 changes: 7 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
[tool.ruff]
line-length = 79
lint.select = ["E", "F", "I"]
lint.select = [
"B", # bugbear
"E",
"F",
"I",
# "PD", # pandas
]
target-version = "py39"

4 changes: 2 additions & 2 deletions scripts/cligen/plot_qc_mrms_precip.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import numpy as np
from geopandas import read_postgis
from matplotlib.patches import Polygon
from pyiem.database import get_dbconn
from pyiem.iemre import (
EAST,
NORTH,
Expand All @@ -19,7 +20,6 @@
get_daily_mrms_ncname,
)
from pyiem.plot import MapPlot
from pyiem.util import get_dbconn

YS = np.arange(SOUTH, NORTH, 0.01)
XS = np.arange(WEST, EAST, 0.01)
Expand Down Expand Up @@ -92,7 +92,7 @@ def do(valid):
geom_col="geom",
index_col="fpath",
)
for fpath, row in df.iterrows():
for _fpath, row in df.iterrows():
mp.ax.plot(row["geom"].xy[0], row["geom"].xy[1], c="k")

df = read_postgis(
Expand Down
4 changes: 2 additions & 2 deletions scripts/convergence/plot_avgs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pyiem.util import get_dbconn
from pyiem.database import get_dbconn
from scipy import stats

YEAR = int(sys.argv[1])
Expand Down Expand Up @@ -62,7 +62,7 @@
(fig, ax) = plt.subplots(1, 1, figsize=(8, 6))

averages = []
for i in range(10):
for _ in range(10):
averages.append([])

for i in range(10):
Expand Down
112 changes: 110 additions & 2 deletions scripts/dynamic_tillage/accum_acres_plot.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,116 @@
"""Plot accumulated acres diagnostic."""

import pandas as pd
from pyiem.plot import figure_axes
from pyiem.util import get_sqlalchemy_conn
from matplotlib.patches import Rectangle
from pyiem.database import get_sqlalchemy_conn
from pyiem.plot import MapPlot, figure_axes


def plot_map(i, dt, huc12df, fields):
"""Make a map diagnostic"""
minx, miny, maxx, maxy = huc12df["geom"].to_crs(4326).total_bounds
buffer = 0.01
huc12 = huc12df.index.values[0]

mp = MapPlot(
title=f"DEP Planting Progress {dt:%Y %b %d} for HUC12: {huc12}",
logo="dep",
sector="custom",
west=minx - buffer,
north=maxy + buffer,
south=miny - buffer,
east=maxx + buffer,
caption="Daily Erosion Project",
continentalcolor="white",
)
huc12df.to_crs(mp.panels[0].crs).plot(
ax=mp.panels[0].ax,
aspect=None,
facecolor="None",
edgecolor="b",
linewidth=2,
zorder=100,
)
fields["color"] = "white"
fields.loc[fields["till1"].notna(), "color"] = "tan"
fields.loc[fields["plant"].notna(), "color"] = "g"
fields.to_crs(mp.panels[0].crs).plot(
ax=mp.panels[0].ax,
aspect=None,
facecolor=fields["color"],
edgecolor="k",
linewidth=1,
zorder=100,
)
p0 = Rectangle((0, 0), 1, 1, fc="white", ec="k")
p1 = Rectangle((0, 0), 1, 1, fc="tan", ec="k")
p2 = Rectangle((0, 0), 1, 1, fc="g", ec="k")
mp.panels[0].ax.legend(
(p0, p1, p2),
("Awaiting", "Tilled", "Planted"),
ncol=3,
fontsize=11,
loc=2,
)

mp.fig.savefig(f"{i:04.0f}.png")
mp.close()


def plot_timeseries(year, df, huc12):
"""Make a diagnostic."""
(fig, ax) = figure_axes(
logo="dep",
title=f"DEP {year} Tillage/Plant Operation Timing for HUC12: {huc12}",
subtitle="<=10% Daily Rate, All Field OFEs below 0.9 Plastic Limit",
)
ax2 = ax.twinx()
x = pd.date_range(f"{year}/04/15", f"{year}/06/03")
ax2.bar(
x - pd.Timedelta(hours=8),
df["acres_planted"],
color="#00ff00",
alpha=0.5,
width=0.3,
align="edge",
zorder=2,
)
ax2.bar(
x,
df["acres_tilled"],
color="#ff0000",
alpha=0.5,
width=0.3,
align="edge",
zorder=2,
)

ax.plot(
x,
df["acres_not_planted"],
color="k",
label="Not Planted",
zorder=3,
lw=3,
)
ax.plot(x, df["acres_to_till"], color="r", label="Tillage", zorder=3, lw=3)
ax.plot(
x,
df["acres_to_plant"],
c="g",
label="Plant",
zorder=3,
lw=3,
)
ax.set_ylabel("Acres Available for Operations")
ax.legend(loc=1)
ax.grid(True)
ax.set_ylim(bottom=-10)
ax2.set_ylim(bottom=-10)
ax2.set_ylabel("Acreas Worked per Day (bars)")
ax.set_zorder(ax2.get_zorder() + 1)
ax.patch.set_visible(False)
fig.savefig(f"{year}_timeseries.png")


def main():
Expand Down
111 changes: 111 additions & 0 deletions scripts/dynamic_tillage/bootstrap_year.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
"""Bootstrap database for dynamic tillage."""

from datetime import date

import click
from pandas.io.sql import read_sql
from pydep.tillage import make_tillage
from pyiem.database import get_dbconnc, get_sqlalchemy_conn
from pyiem.util import logger
from sqlalchemy import text

LOG = logger()


@click.command()
@click.option("--year", type=int, help="Year to bootstrap", required=True)
@click.option("--scenario", type=int, default=0)
def main(year, scenario):
"""Run for the given year."""
with get_sqlalchemy_conn("idep") as conn:
# Delete current year's data
res = conn.execute(
text("""
delete from field_operations o USING fields f
WHERE o.field_id = f.field_id and o.year = :year
and f.scenario = :scenario
"""),
{"year": year, "scenario": scenario},
)
LOG.info("deleted %s field operation rows", res.rowcount)
conn.commit()
# figure out the fields we need to compute
fields = read_sql(
text("""
select field_id, landuse, management,
st_y(st_centroid(st_transform(geom, 4326))) as lat
from fields where scenario = :scenario
and isag and landuse is not null and management is not null
"""),
conn,
params={"scenario": scenario},
index_col="field_id",
)
LOG.info("Processing %s fields", len(fields.index))
conn, cursor = get_dbconnc("idep")
colidx = year - 2007
inserts = 0
for field_id, row in fields.iterrows():
zone = "KS_NORTH"
if row["lat"] >= 42.5:
zone = "IA_NORTH"
elif row["lat"] >= 41.5:
zone = "IA_CENTRAL"
elif row["lat"] >= 40.5:
zone = "IA_SOUTH"
res = make_tillage(
scenario,
zone,
row["landuse"][colidx - 1],
row["landuse"][colidx],
row["landuse"][colidx - 2], # HACK
row["management"][colidx],
year - 2006,
)
events = 0
for line in res.split("\n"):
tokens = line.split()
if len(tokens) < 5 or tokens[4] != "Tillage" or int(tokens[0]) > 6:
continue
events += 1
# till1, till2, till3, plant
dates = [None, None, None, None]
if events == 1:
dates[3] = date(year, 6, 1)
elif events == 2:
dates[0] = date(year, 6, 1)
dates[3] = date(year, 6, 2)
elif events == 3:
dates[0] = date(year, 6, 1)
dates[1] = date(year, 6, 2)
dates[3] = date(year, 6, 3)
elif events == 4:
dates[0] = date(year, 6, 1)
dates[1] = date(year, 6, 2)
dates[2] = date(year, 6, 3)
dates[3] = date(year, 6, 4)
elif events > 4:
LOG.info("events: %s", events)
LOG.info("res: %s", res)
raise ValueError("too many events")
cursor.execute(
"""
INSERT into field_operations
(field_id, year, till1, till2, till3, plant)
VALUES (%s, %s, %s, %s, %s, %s)
""",
(field_id, year, dates[0], dates[1], dates[2], dates[3]),
)
inserts += 1
if inserts % 10_000 == 0:
cursor.close()
conn.commit()
cursor = conn.cursor()

cursor.close()
conn.commit()
conn.close()


if __name__ == "__main__":
main()
Loading

0 comments on commit c47eef6

Please sign in to comment.