Skip to content

Commit

Permalink
solver updates (#223)
Browse files Browse the repository at this point in the history
* merge fix

* Remove obsolete F0, F1 from generic_solvers

* Another r string warning removal

* Removing obsolete Unknown attributes on the generic solver

* Getting rid of the problem_description method in every solver

* Removing some commented out code.

* Clean up the expression's initialisation code

* simplifying the uw_counter_object idea to keep a total_instances and instance_number

* Removing the metaclass counter idea - now simpler. Need to add a stress test

* Adding _version.py file.

Also starting a runtime record class, currently in __init__.py

* Object counter function to class function + property

* Introducting uw_record.

uw_record gives information on the installation and runtime

Access via:
import underworld3 as uw
uw.auditor.get_installation_data
uw.auditor.get_runtime_data

* uw_record lives in underworld/utilities/__init__.py
* uw_record collects data only on proc 0 and broadcasts to all procs.
  For get_runtime_data be aware of this design. As calling often could cause
  an operational overhead. While get_installation_data only bcasts at initialisation.
* Coming idea is to serialised the output get_installation_data into
  hdf5 files

* Rename uw_record -> auditor

* access via underworld3.auditor
* test included in test_0005_utils.py

* Modify test script name for uw_counter

* Clean up the interface of 'auditor'

* Removing the uw_count class
  • Loading branch information
julesghub authored Aug 26, 2024
1 parent f9b94c7 commit 790307d
Show file tree
Hide file tree
Showing 12 changed files with 292 additions and 140 deletions.
3 changes: 2 additions & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = underworld3
version = 0.98b
version = attr: underworld3.__version__

#[build_ext]
#inplace = True
Expand All @@ -20,6 +20,7 @@ install_requires =
pint
psutil
typing_extensions

package_dir =
= src
packages = find:
Expand Down
37 changes: 8 additions & 29 deletions src/underworld3/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@

PETSc.Sys.popErrorHandler()

try:
from ._version import __version__
except ImportError:
__version__ = "Unknown" # check src/underworld3/_version.py

def view():
from IPython.display import Latex, Markdown, display
Expand All @@ -97,8 +101,11 @@ def view():
from ._var_types import *
from .utilities._petsc_tools import *
from .utilities._nb_tools import *
from .utilities._utils import auditor

from underworld3.utilities import _api_tools
from .utilities import _api_tools
#from underworld3.utilities import _api_tools
from .utilities._utils import auditor

import underworld3.adaptivity
import underworld3.coordinates
Expand Down Expand Up @@ -131,31 +138,6 @@ def view():
_libdirs = _OD()
_incdirs = _OD({_np.get_include(): None})


# def _is_notebook() -> bool:
# """
# Function to determine if the python environment is a Notebook or not.

# Returns 'True' if executing in a notebook, 'False' otherwise

# Script taken from https://stackoverflow.com/a/39662359/8106122
# """

# try:
# shell = get_ipython().__class__.__name__
# if shell == "ZMQInteractiveShell":
# return True # Jupyter notebook or qtconsole
# elif shell == "TerminalInteractiveShell":
# return False # Terminal running IPython
# else:
# return False # Other type (?)
# except NameError:
# return False # Probably standard Python interpreter


# is_notebook = _is_notebook()


## -------------------------------------------------------------

# pdoc3 over-rides. pdoc3 has a strange path-traversal algorithm
Expand All @@ -175,6 +157,3 @@ def view():
# child class modifications

__pdoc__["systems.constitutive_models.Constitutive_Model.Parameters"] = False


## Add an options dictionary for arbitrary underworld things
1 change: 1 addition & 0 deletions src/underworld3/_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = "0.98.1b"
49 changes: 9 additions & 40 deletions src/underworld3/cython/petsc_generic_snes_solvers.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ from xmlrpc.client import Boolean
import sympy
from sympy import sympify

from typing import Optional, Union
from typing import Optional, Union, TypeAlias
from petsc4py import PETSc

import underworld3
Expand Down Expand Up @@ -37,14 +37,6 @@ class SolverBaseClass(uw_object):

self.Unknowns = self._Unknowns(self)

self._u = self.Unknowns.u
self._DuDt = self.Unknowns.DuDt
self._DFDt = self.Unknowns.DFDt

self._L = self.Unknowns.L # grad(u)
self._E = self.Unknowns.E # sym part
self._W = self.Unknowns.W # asym part

self._order = 0
self._constitutive_model = None

Expand Down Expand Up @@ -190,6 +182,11 @@ class SolverBaseClass(uw_object):
return


# Deprecate in favour of properties for solver.F0, solver.F1
@timing.routine_timer_decorator
def _setup_problem_description(self):
raise RuntimeError("Contact Developers - shouldn't be calling SolverBaseClass _setup_problem_description")

@timing.routine_timer_decorator
def add_condition(self, f_id, c_type, conds, label, components=None):
"""
Expand All @@ -201,6 +198,7 @@ class SolverBaseClass(uw_object):
----------
f_id: int
Index of the solver's field (equation) to apply the condition.
Note: The solvers field id is usually different to the mesh's field ids.
c_type: string
BC type. Either dirichlet (essential) or neumann (natural) conditions.
conds: array_like of floats or a sympy.Matrix
Expand Down Expand Up @@ -289,30 +287,13 @@ class SolverBaseClass(uw_object):
"""
self.add_condition(0, 'dirichlet', conds, boundary, components)


## Properties that are common to all solvers
## F0 and F1 are the force / flux terms, respectively
## Solvers over-ride these to describe the problem type
@property
def F0(self):

f0 = uw.function.expression(
r"\mathbf{f}_0\left( \mathbf{u} \right)",
None,
"Pointwise force term: f_0(u)",
)

return f0
raise RuntimeError("Contact Developers - SolverBaseClass F0 is being used")

@property
def F1(self):
f1 = uw.function.expression(
r"\mathbf{F}_1\left( \mathbf{u} \right)",
None,
"Pointwise flux term: F_1(u)",
)

return f1
raise RuntimeError("Contact Developers - SolverBaseClass F0 is being used")

@property
def u(self):
Expand Down Expand Up @@ -439,16 +420,11 @@ class SNES_Scalar(SolverBaseClass):
self.Unknowns.DuDt = DuDt
self.Unknowns.DFDt = DFDt

# self.u = u_Field
# self.DuDt = DuDt
# self.DFDt = DFDt

self.name = solver_name
self.verbose = verbose
self._tolerance = 1.0e-4

## Todo: this is obviously not particularly robust

if solver_name != "" and not solver_name.endswith("_"):
self.petsc_options_prefix = solver_name+"_"
else:
Expand Down Expand Up @@ -488,8 +464,6 @@ class SNES_Scalar(SolverBaseClass):
self.petsc_options.delValue("snes_monitor_short")
self.petsc_options.delValue("snes_converged_reason")

self._F0 = sympy.Matrix.zeros(1,1)
self._F1 = sympy.Matrix.zeros(1,mesh.dim)
self.dm = None


Expand All @@ -508,7 +482,6 @@ class SNES_Scalar(SolverBaseClass):
self.mesh._equation_systems_register.append(self)

self.is_setup = False
# super().__init__()

@property
def tolerance(self):
Expand Down Expand Up @@ -1085,8 +1058,6 @@ class SNES_Vector(SolverBaseClass):
vtype=uw.VarType.VECTOR, degree=degree )


self._F0 = sympy.Matrix.zeros(1, self.mesh.dim)
self._F1 = sympy.Matrix.zeros(self.mesh.dim, self.mesh.dim)
self.dm = None

## sympy.Matrix
Expand All @@ -1111,8 +1082,6 @@ class SNES_Vector(SolverBaseClass):

self.mesh._equation_systems_register.append(self)

# super().__init__()

@property
def tolerance(self):
return self._tolerance
Expand Down
2 changes: 1 addition & 1 deletion src/underworld3/discretisation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1650,7 +1650,7 @@ def __init__(
self.symbol = symbol

if mesh.instance_number > 1:
invisible = "\,\!" * mesh.instance_number
invisible = r"\,\!" * mesh.instance_number
self.symbol = f"{{ {{ {invisible} }} {symbol} }}"

self.clean_name = re.sub(r"[^a-zA-Z0-9_]", "", name)
Expand Down
21 changes: 13 additions & 8 deletions src/underworld3/function/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ class UWexpression(Symbol, uw_object):
```{python}
alpha = UWexpression(
r'\\alpha',
value=3.0e-5,
sym=3.0e-5,
description="thermal expansivity"
)
print(alpha.sym)
Expand All @@ -96,17 +96,22 @@ class UWexpression(Symbol, uw_object):
"""

def __new__(cls, name, value, description="No description provided"):
def __new__(cls, name, *args, **kwargs,):

obj = Symbol.__new__(cls, name)
obj.sym = sympy.sympify(value)
obj.symbol = name
return obj

def __init__(self, name, value, description="No description provided"):

self._sym = sympy.sympify(value)
self._description = description
def __init__(self, name, sym=None, description="No description provided", value=None):
if value is not None and sym is None:
import warnings;
warnings.warn(message=f"DEPRECATION warning, don't use 'value' attribute for expression: {value}, please use 'sym' attribute")
sym = value
if value is not None and sym is not None:
raise ValueError("Both 'sym' and 'value' attributes are provided, please use one")

self.sym = sympy.sympify(sym)
self.symbol = name
self.description = description

return

Expand Down
14 changes: 0 additions & 14 deletions src/underworld3/systems/solvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,6 @@ def __init__(
if solver_name == "":
solver_name = "Poisson_{}_".format(self.instance_number)

# Register the problem setup function
self._setup_problem_description = self.poisson_problem_description

# default values for properties
self.f = sympy.Matrix.zeros(1, 1)

Expand Down Expand Up @@ -210,9 +207,6 @@ def __init__(
if solver_name == "":
self.solver_name = "Darcy_{}_".format(self.instance_number)

# Register the problem setup function
self._setup_problem_description = self.darcy_problem_description

# default values for properties
self._f = sympy.Matrix([0])
self._k = 1
Expand Down Expand Up @@ -458,8 +452,6 @@ def __init__(

self._bodyforce = sympy.Matrix([[0] * self.mesh.dim])

self._setup_problem_description = self.stokes_problem_description

# this attrib records if we need to setup the problem (again)
self.is_setup = False

Expand Down Expand Up @@ -842,7 +834,6 @@ def __init__(
if solver_name == "":
self.name = "SProj_{}_".format(self.instance_number)

self._setup_problem_description = self.projection_problem_description
self.is_setup = False
self._smoothing = 0.0
self._uw_weighting_function = 1.0
Expand Down Expand Up @@ -974,7 +965,6 @@ def __init__(
if solver_name == "":
solver_name = "VProj{}_".format(self.instance_number)

self._setup_problem_description = self.projection_problem_description
self.is_setup = False
self._smoothing = 0.0
self._penalty = 0.0
Expand Down Expand Up @@ -1298,8 +1288,6 @@ def __init__(
self.is_setup = False

self.restore_points_to_domain_func = restore_points_func
self._setup_problem_description = self.adv_diff_slcn_problem_description

### Setup the history terms ... This version should not build anything
### by default - it's the template / skeleton

Expand Down Expand Up @@ -1636,8 +1624,6 @@ def __init__(
)

self.restore_points_to_domain_func = restore_points_func
self._setup_problem_description = self.navier_stokes_problem_description

self._bodyforce = sympy.Matrix([[0] * self.mesh.dim])
self._constitutive_model = None

Expand Down
3 changes: 1 addition & 2 deletions src/underworld3/utilities/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ def _append_petsc_path():

from .uw_petsc_gen_xdmf import Xdmf, generateXdmf, generate_uw_Xdmf
from .uw_swarmIO import swarm_h5, swarm_xdmf
from ._utils import CaptureStdout, h5_scan, mem_footprint, gather_data
from ._utils import CaptureStdout, h5_scan, mem_footprint, gather_data, auditor

from .read_medit_ascii import read_medit_ascii, print_medit_mesh_info
from .create_dmplex_from_medit import create_dmplex_from_medit

Loading

0 comments on commit 790307d

Please sign in to comment.