Skip to content

Commit

Permalink
cleaner subpkg ref passing
Browse files Browse the repository at this point in the history
  • Loading branch information
wpbonelli committed Nov 5, 2024
1 parent 5984f18 commit 64d4187
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 85 deletions.
2 changes: 1 addition & 1 deletion flopy/mf6/utils/codegen/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def _get_template_env():
env.filters["maybe_file"] = Filters.Var.maybe_file
env.filters["type"] = Filters.Var.type

env.filters["nokw"] = Filters.nokw
env.filters["safe_str"] = Filters.safe_str
env.filters["escape_trailing_underscore"] = (
Filters.escape_trailing_underscore
)
Expand Down
8 changes: 3 additions & 5 deletions flopy/mf6/utils/codegen/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,7 @@ def from_dfn(cls, dfn: Dfn) -> Iterator["Context"]:
These are structured representations of input context classes.
Each input definition yields one or more input contexts.
"""
meta = dfn.meta.copy()
ref = Ref.from_dfn(dfn)
if ref:
meta["ref"] = ref
for name in Context.Name.from_dfn(dfn):
yield Context(name=name, vars=dfn.data, meta=meta)
yield Context(
name=name, vars=dfn.data.copy(), meta=dfn.meta.copy()
)
129 changes: 60 additions & 69 deletions flopy/mf6/utils/codegen/dfn.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,69 +85,6 @@ class Ref(TypedDict):
parent: str
description: Optional[str]

@classmethod
def from_dfn(cls, dfn: "Dfn") -> Optional["Ref"]:
"""
Try to load a reference from the definition.
Returns `None` if the definition cannot be
referenced by other contexts.
"""

if not dfn.meta or "dfn" not in dfn.meta:
return None

_, meta = dfn.meta["dfn"]

lines = {
"subpkg": next(
iter(
m
for m in meta
if isinstance(m, str) and m.startswith("subpac")
),
None,
),
"parent": next(
iter(
m
for m in meta
if isinstance(m, str) and m.startswith("parent")
),
None,
),
}

def _subpkg():
line = lines["subpkg"]
_, key, abbr, param, val = line.split()
matches = [v for v in dfn.values() if v["name"] == val]
if not any(matches):
descr = None
else:
if len(matches) > 1:
warn(f"Multiple matches for referenced variable {val}")
match = matches[0]
descr = match["description"]

return {
"key": key,
"val": val,
"abbr": abbr,
"param": param,
"description": descr,
}

def _parent():
line = lines["parent"]
split = line.split()
return split[1]

return (
cls(**_subpkg(), parent=_parent())
if all(v for v in lines.values())
else None
)


class Dfn(UserDict):
"""
Expand Down Expand Up @@ -457,12 +394,65 @@ def _fields() -> Vars:
default=default,
)

vars_ = {
var["name"]: _map(var)
for var in flat.values(multi=True)
if not var.get("in_record", False)
}

def _subpkg() -> Optional["Ref"]:
lines = {
"subpkg": next(
iter(
m
for m in meta
if isinstance(m, str) and m.startswith("subpac")
),
None,
),
"parent": next(
iter(
m
for m in meta
if isinstance(m, str) and m.startswith("parent")
),
None,
),
}

def __subpkg():
line = lines["subpkg"]
_, key, abbr, param, val = line.split()
matches = [v for v in vars_.values() if v["name"] == val]
if not any(matches):
descr = None
else:
if len(matches) > 1:
warn(f"Multiple matches for referenced variable {val}")
match = matches[0]
descr = match["description"]

return {
"key": key,
"val": val,
"abbr": abbr,
"param": param,
"description": descr,
}

def _parent():
line = lines["parent"]
split = line.split()
return split[1]

return (
Ref(**__subpkg(), parent=_parent())
if all(v for v in lines.values())
else None
)

return cls(
{
var["name"]: _map(var)
for var in flat.values(multi=True)
if not var.get("in_record", False)
},
vars_,
name,
{
"dfn": (
Expand All @@ -473,6 +463,7 @@ def _fields() -> Vars:
meta,
),
"fkeys": fkeys,
"subpkg": _subpkg(),
},
)

Expand Down Expand Up @@ -518,7 +509,7 @@ def _load_all_v1(dfndir: PathLike) -> Dfns:
name = Dfn.Name(*path.stem.split("-"))
with open(path) as f:
dfn = Dfn.load(f, name=name, common=common)
ref = Ref.from_dfn(dfn)
ref = dfn.meta.get("subpkg", None)
if ref:
refs[ref["key"]] = ref

Expand Down
10 changes: 5 additions & 5 deletions flopy/mf6/utils/codegen/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ def prefix(ctx_name) -> str:

@pass_context
def parent(ctx, ctx_name) -> str:
ref = ctx["meta"].get("ref", None)
if ref:
return ref["parent"]
subpkg = ctx["meta"].get("subpkg", None)
if subpkg:
return subpkg["parent"]
if ctx_name == ("sim", "nam"):
return None
elif (
Expand All @@ -80,7 +80,7 @@ def parent(ctx, ctx_name) -> str:
or ctx_name.l in ["sim", "exg", "sln"]
):
return "simulation"
elif ref:
elif subpkg:
if ctx_name.l == "utl" and ctx_name.r == "hpc":
return "simulation"
return "package"
Expand Down Expand Up @@ -420,7 +420,7 @@ def _should_build(var: dict) -> bool:

return list(filter(None, _statements()))

def nokw(v: str) -> str:
def safe_str(v: str) -> str:
return (f"{v}_" if v in kwlist else v).replace("-", "_")

def escape_trailing_underscore(v: str) -> str:
Expand Down
4 changes: 2 additions & 2 deletions flopy/mf6/utils/codegen/templates/macros.jinja
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
{% macro init_vars(vars, alias=false, indent=0, skip=none) %}
{%- for name, var in vars.items() if name not in skip %}
{% set v = var|maybe_file -%}
{% set n = (name if alias else v.name)|nokw -%}
{% set n = (name if alias else v.name)|safe_str -%}
{{ ""|indent(indent, first=true) }}{{ n }}{%- if v.default is defined %}={{ v.default|value }}{%- endif -%},
{%- endfor %}
{% endmacro %}

{% macro vars_docs(vars, indent=0) %}
{%- for var in vars.values() recursive %}
{% set v = var|maybe_file -%}
{% set n = v.name|nokw|escape_trailing_underscore -%}
{% set n = v.name|safe_str|escape_trailing_underscore -%}
{{ ""|indent(indent, first=true) }}{% if loop.depth > 1 %}* {% endif %}{{ n }} : {{ v|type }}
{%- if v.description is defined and v.description is not none %}
{{ v.description|wordwrap|indent(indent + (loop.depth * 4), first=true) }}
Expand Down
6 changes: 3 additions & 3 deletions flopy/mf6/utils/codegen/templates/package.py.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ class Modflow{{ title }}(MFPackage):

self._init_complete = True

{% if "ref" in meta and name.r != "hpc" %}
{% if "subpkg" in meta and name.r != "hpc" %}
class {{ title }}Packages(MFChildPackages):
"""
{{ title }}Packages is a container class for the Modflow{{ title }} class.
Expand Down Expand Up @@ -101,7 +101,7 @@ class {{ title }}Packages(MFChildPackages):
new_package = Modflow{{ title }}(
self._cpparent,
{%- for n, var in vars.items() if n not in name|skip %}
{{ n }}={{ n }},
{{ n|safe_str }}={{ n|safe_str }},
{%- endfor %}
filename=filename,
pname=pname,
Expand All @@ -119,7 +119,7 @@ class {{ title }}Packages(MFChildPackages):
new_package = Modflow{{ title }}(
self._cpparent,
{%- for n, var in vars.items() if n not in name|skip %}
{{ n }}={{ n }},
{{ n|safe_str }}={{ n|safe_str }},
{%- endfor %}
filename=filename,
pname=pname,
Expand Down

0 comments on commit 64d4187

Please sign in to comment.