Skip to content

Commit

Permalink
Bugfix release 0.403 / first ogstools release
Browse files Browse the repository at this point in the history
  • Loading branch information
joergbuchwald committed Aug 23, 2024
1 parent 27ded1e commit 52874e9
Show file tree
Hide file tree
Showing 19 changed files with 2,073 additions and 1,001 deletions.
2 changes: 1 addition & 1 deletion ogs6py/_version.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-
"""Provide a central version."""
__version__ = "0.402"
__version__ = "0.403"
8 changes: 8 additions & 0 deletions ogs6py/classes/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
# Copyright (c) 2012-2024, OpenGeoSys Community (http://www.opengeosys.org)
# Distributed under a Modified BSD License.
# See accompanying file LICENSE.txt or
# http://www.opengeosys.org/project/license
#

# Author: Joerg Buchwald (Helmholtz Centre for Environmental Research GmbH - UFZ)

from . import display
from . import mesh
from . import geo
Expand Down
58 changes: 41 additions & 17 deletions ogs6py/classes/build_tree.py
Original file line number Diff line number Diff line change
@@ -1,56 +1,77 @@
# -*- coding: utf-8 -*-
"""
Copyright (c) 2012-2021, OpenGeoSys Community (http://www.opengeosys.org)
Distributed under a Modified BSD License.
See accompanying file LICENSE or
http://www.opengeosys.org/project/license
"""


from typing import TypeAlias

from lxml import etree as ET

OptionalETElement: TypeAlias = (
ET.Element
) # ToDo this should be Optional[ET.Element]


# pylint: disable=C0103, R0902, R0914, R0913
class BuildTree:
""" helper class to create a nested dictionary
"""helper class to create a nested dictionary
representing the xml structure
"""
def __init__(self, tree):

def __init__(self, tree: ET.ElementTree) -> None:
self.tree = tree

def _get_root(self):
root = self.tree.getroot()
return root
def _get_root(self) -> ET.Element:
return self.tree.getroot()

@classmethod
def _convertargs(cls, args):
def _convertargs(cls, args: dict[str, str]) -> None:
"""
convert arguments that are not lists or dictionaries to strings
"""
for item, value in args.items():
if not isinstance(value, (list, dict)):
if not isinstance(value, list | dict):
args[item] = str(value)

@classmethod
def populate_tree(cls, parent, tag, text=None, attr=None, overwrite=False):
def populate_tree(
cls,
parent: ET.Element,
tag: str,
text: str | None = None,
attr: dict[str, str] | None = None,
overwrite: bool = False,
) -> ET.Element:
"""
method to create dictionary from an xml entity
"""
q = None
if not tag is None:
if tag is not None:
if overwrite is True:
for child in parent:
if child.tag == tag:
q = child
if q is None:
q = ET.SubElement(parent, tag)
if not text is None:
if text is not None:
q.text = str(text)
if not attr is None:
if attr is not None:
for key, val in attr.items():
q.set(key, str(val))
return q

@classmethod
def get_child_tag(cls, parent, tag, attr=None, attr_val=None):
def get_child_tag(
cls,
parent: ET.Element,
tag: str,
attr: dict[str, str] | None = None,
attr_val: str | None = None,
) -> OptionalETElement:
"""
search for child tag based on tag and possible attributes
"""
Expand All @@ -65,15 +86,18 @@ def get_child_tag(cls, parent, tag, attr=None, attr_val=None):
return q

@classmethod
def get_child_tag_for_type(cls, parent, tag, subtagval, subtag="type"):
def get_child_tag_for_type(
cls, parent: ET.Element, tag: str, subtagval: str, subtag: str = "type"
) -> OptionalETElement:
"""
search for child tag based on subtag type
"""
q = None
for child in parent:
if child.tag == tag:
for subchild in child:
if subchild.tag == subtag:
if subchild.text == subtagval:
q = child
if (subchild.tag == subtag) and (
subchild.text == subtagval
):
q = child
return q
38 changes: 24 additions & 14 deletions ogs6py/classes/curves.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
# -*- coding: utf-8 -*-
"""
Copyright (c) 2012-2021, OpenGeoSys Community (http://www.opengeosys.org)
Copyright (c) 2012-2024, OpenGeoSys Community (http://www.opengeosys.org)
Distributed under a Modified BSD License.
See accompanying file LICENSE or
http://www.opengeosys.org/project/license
"""
# pylint: disable=C0103, R0902, R0914, R0913
from ogs6py.classes import build_tree
from typing import Any

from lxml import etree as ET

from ogstools.ogs6py import build_tree


class Curves(build_tree.BuildTree):
"""
Class to create the curve section of the project file.
"""
def __init__(self, tree):

def __init__(self, tree: ET.ElementTree) -> None:
self.tree = tree
self.root = self._get_root()
self.curves = self.populate_tree(self.root, "curves", overwrite=True)

def add_curve(self, **args):
def add_curve(self, **args: Any) -> None:
"""
Adds a new curve.
Expand All @@ -29,23 +34,28 @@ def add_curve(self, **args):
values : `list`
"""
if "name" not in args:
raise KeyError("No curve name given.")
msg = "No curve name given."
raise KeyError(msg)
if "coords" not in args:
raise KeyError("No coordinates given.")
msg = "No coordinates given."
raise KeyError(msg)
if "values" not in args:
raise KeyError("No values given.")
msg = "No values given."
raise KeyError(msg)
if len(args["coords"]) != len(args["values"]):
raise ValueError("Number of time coordinate points differs from number of values")
msg = """Number of time coordinate points differs \
from number of values"""
raise ValueError(msg)
curve = self.populate_tree(self.curves, "curve")
self.populate_tree(curve, "name", args['name'])
self.populate_tree(curve, "name", args["name"])
coord_str = ""
value_str = ""
for i, coord in enumerate(args["coords"]):
if i < (len(args["coords"])-1):
if i < (len(args["coords"]) - 1):
coord_str = coord_str + str(coord) + " "
value_str = value_str + str(args["values"][i]) + " "
if i == (len(args["coords"])-1):
if i == (len(args["coords"]) - 1):
coord_str = coord_str + str(coord)
value_str = value_str + str(args["values"][i])
self.populate_tree(curve, 'coords', text=coord_str)
self.populate_tree(curve, 'values', text=value_str)
self.populate_tree(curve, "coords", text=coord_str)
self.populate_tree(curve, "values", text=value_str)
125 changes: 89 additions & 36 deletions ogs6py/classes/display.py
Original file line number Diff line number Diff line change
@@ -1,53 +1,106 @@
# -*- coding: utf-8 -*-
"""
Copyright (c) 2012-2021, OpenGeoSys Community (http://www.opengeosys.org)
Distributed under a Modified BSD License.
See accompanying file LICENSE or
http://www.opengeosys.org/project/license
"""
from contextlib import suppress

from lxml import etree as ET

try:
from IPython.display import display, Markdown, Latex
from IPython.display import Markdown, display

verbose = True
except ImportError:
verbose = False


# pylint: disable=C0103, R0902, R0914, R0913
class Display:
""" helper class to create a nested dictionary
"""helper class to create a nested dictionary
representing the xml structure
"""
def __init__(self,tree):

def __init__(self, tree: ET.ElementTree):
if verbose is True:
display(Markdown('## OpenGeoSys project file'))
display(Markdown('### Main Info'))
display(Markdown(f"**Process name:** {tree.find('./processes/process/name').text}"))
display(Markdown(f"**Process type:** {tree.find('./processes/process/type').text}"))
t_end = float(tree.find('./time_loop/processes/process/time_stepping/t_end').text)
t_init = float(tree.find('./time_loop/processes/process/time_stepping/t_initial').text)
display(Markdown(f"**Simulation time:** {t_end-t_init}"))
proc_vars = tree.findall("./process_variables/process_variable")
display(Markdown(f"**Output prefix:** {tree.find('./time_loop/output/prefix').text}"))
display(Markdown('### Boundary conditions'))
for var in proc_vars:
proc_var_entries = var.getchildren()
for entry in proc_var_entries:
if entry.tag == "name":
display(Markdown(f"**Process Variable:** {entry.text}"))
if entry.tag == "initial_condition":
display(Markdown(f" - **Initial Condition:** {entry.text}"))
if entry.tag == "order":
display(Markdown(f" - **Order:** {entry.text}"))
if entry.tag == "boundary_conditions":
bcs = entry.getchildren()
for bc in bcs:
bc_entries = bc.getchildren()
for subentry in bc_entries:
if subentry.tag == "type":
display(Markdown(f" - **Type:** {subentry.text}"))
if subentry.tag == "mesh":
display(Markdown(f" - **Mesh:** {subentry.text}"))
if subentry.tag == "geometrical_set":
display(Markdown(f" - **Geometrical Set:** {subentry.text}"))
if subentry.tag == "geometry":
display(Markdown(f" - **Geometry:** {subentry.text}"))
display(Markdown("## OpenGeoSys project file"))
display(Markdown("### Main Info"))
with suppress(AttributeError):
display(
Markdown(
f"**Process name:** {tree.find('./processes/process/name').text}"
)
)
with suppress(AttributeError):
display(
Markdown(
f"**Process type:** {tree.find('./processes/process/type').text}"
)
)
with suppress(AttributeError):
t_end = float(
tree.find(
"./time_loop/processes/process/time_stepping/t_end"
).text
)
t_init = float(
tree.find(
"./time_loop/processes/process/time_stepping/t_initial"
).text
)
display(Markdown(f"**Simulation time:** {t_end-t_init}"))
with suppress(AttributeError):
proc_vars = tree.findall("./process_variables/process_variable")
with suppress(AttributeError):
display(
Markdown(
f"**Output prefix:** {tree.find('./time_loop/output/prefix').text}"
)
)
display(Markdown("### Boundary conditions"))
for var in proc_vars:
proc_var_entries = var.getchildren()
for entry in proc_var_entries:
if entry.tag == "name":
display(
Markdown(f"**Process Variable:** {entry.text}")
)
if entry.tag == "initial_condition":
display(
Markdown(
f" - **Initial Condition:** {entry.text}"
)
)
if entry.tag == "order":
display(Markdown(f" - **Order:** {entry.text}"))
if entry.tag == "boundary_conditions":
bcs = entry.getchildren()
for bc in bcs:
bc_entries = bc.getchildren()
for subentry in bc_entries:
if subentry.tag == "type":
display(
Markdown(
f" - **Type:** {subentry.text}"
)
)
if subentry.tag == "mesh":
display(
Markdown(
f" - **Mesh:** {subentry.text}"
)
)
if subentry.tag == "geometrical_set":
display(
Markdown(
f" - **Geometrical Set:** {subentry.text}"
)
)
if subentry.tag == "geometry":
display(
Markdown(
f" - **Geometry:** {subentry.text}"
)
)
13 changes: 8 additions & 5 deletions ogs6py/classes/geo.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
# -*- coding: utf-8 -*-
"""
Copyright (c) 2012-2021, OpenGeoSys Community (http://www.opengeosys.org)
Copyright (c) 2012-2024, OpenGeoSys Community (http://www.opengeosys.org)
Distributed under a Modified BSD License.
See accompanying file LICENSE or
http://www.opengeosys.org/project/license
"""
# pylint: disable=C0103, R0902, R0914, R0913
from ogs6py.classes import build_tree
from lxml import etree as ET

from ogstools.ogs6py import build_tree


class Geo(build_tree.BuildTree):
"""
Class containing the geometry file.
"""
def __init__(self, tree):

def __init__(self, tree: ET.ElementTree) -> None:
self.tree = tree
self.root = self._get_root()
self.populate_tree(self.root, "geometry", overwrite=True)

def add_geometry(self, filename):
def add_geometry(self, filename: str) -> None:
"""
Adds a geometry file.
Expand Down
Loading

0 comments on commit 52874e9

Please sign in to comment.