Skip to content

Commit

Permalink
Use Python warnings (#133)
Browse files Browse the repository at this point in the history
* Use Python warnings

* Remove deprecate too
  • Loading branch information
chrisrichardson committed Nov 22, 2022
1 parent 2b69e80 commit 4fd9a80
Show file tree
Hide file tree
Showing 16 changed files with 64 additions and 71 deletions.
5 changes: 3 additions & 2 deletions test/test_scratch.py
Expand Up @@ -8,10 +8,11 @@
"""

import pytest
import warnings

# This imports everything external code will see from ufl
from ufl import *
from ufl.log import error, warning
from ufl.log import error
from ufl.tensors import as_scalar, unit_indexed_tensor, unwrap_list_tensor

# TODO: Import only what you need from classes and algorithms:
Expand Down Expand Up @@ -149,7 +150,7 @@ def compute_gprimeterm(ngrads, vval, vcomp, wshape, wcomp):
if self._cd._data:
# TODO: Make it possible to silence this message in particular?
# It may be good to have for debugging...
warning("Assuming d{%s}/d{%s} = 0." % (o, self._w))
warnings.warn("Assuming d{%s}/d{%s} = 0." % (o, self._w))
else:
# Make sure we have a tuple to match the self._v tuple
if not isinstance(oprimes, tuple):
Expand Down
4 changes: 2 additions & 2 deletions ufl/__init__.py
Expand Up @@ -258,7 +258,7 @@

# Output control
from ufl.log import get_handler, get_logger, set_handler, set_level, add_logfile, \
UFLException, DEBUG, INFO, WARNING, ERROR, CRITICAL
UFLException, DEBUG, INFO, ERROR, CRITICAL

# Types for geometric quantities

Expand Down Expand Up @@ -366,7 +366,7 @@
__all__ = [
'product',
'get_handler', 'get_logger', 'set_handler', 'set_level', 'add_logfile',
'UFLException', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL',
'UFLException', 'DEBUG', 'INFO', 'ERROR', 'CRITICAL',
'as_cell', 'AbstractCell', 'Cell', 'TensorProductCell',
'as_domain', 'AbstractDomain', 'Mesh', 'MeshView', 'TensorProductMesh',
'L2', 'H1', 'H2', 'HCurl', 'HDiv', 'HInf', 'HEin', 'HDivDiv',
Expand Down
5 changes: 3 additions & 2 deletions ufl/algorithms/apply_derivatives.py
Expand Up @@ -7,9 +7,10 @@
#
# SPDX-License-Identifier: LGPL-3.0-or-later

import warnings
from collections import defaultdict

from ufl.log import error, warning
from ufl.log import error

from ufl.core.expr import ufl_err_str
from ufl.core.terminal import Terminal
Expand Down Expand Up @@ -1013,7 +1014,7 @@ def compute_gprimeterm(ngrads, vval, vcomp, wshape, wcomp):
# TODO: Make it possible to silence this message
# in particular? It may be good to have for
# debugging...
warning("Assuming d{%s}/d{%s} = 0." % (o, self._w))
warnings.warn("Assuming d{%s}/d{%s} = 0." % (o, self._w))
else:
# Make sure we have a tuple to match the self._v tuple
if not isinstance(oprimes, tuple):
Expand Down
13 changes: 7 additions & 6 deletions ufl/algorithms/apply_geometry_lowering.py
Expand Up @@ -11,10 +11,11 @@
#
# SPDX-License-Identifier: LGPL-3.0-or-later

import warnings
from functools import reduce
from itertools import combinations

from ufl.log import error, warning
from ufl.log import error

from ufl.core.multiindex import Index, indices
from ufl.corealg.multifunction import MultiFunction, memoized_handler
Expand Down Expand Up @@ -189,7 +190,7 @@ def cell_volume(self, o):
if not domain.is_piecewise_linear_simplex_domain():
# Don't lower for non-affine cells, instead leave it to
# form compiler
warning("Only know how to compute the cell volume of an affine cell.")
warnings.warn("Only know how to compute the cell volume of an affine cell.")
return o

r = self.jacobian_determinant(JacobianDeterminant(domain))
Expand All @@ -206,7 +207,7 @@ def facet_area(self, o):
if not domain.is_piecewise_linear_simplex_domain():
# Don't lower for non-affine cells, instead leave it to
# form compiler
warning("Only know how to compute the facet area of an affine cell.")
warnings.warn("Only know how to compute the facet area of an affine cell.")
return o

# Area of "facet" of interval (i.e. "area" of a vertex) is defined as 1.0
Expand Down Expand Up @@ -273,7 +274,7 @@ def _reduce_cell_edge_length(self, o, reduction_op):

if not domain.ufl_coordinate_element().degree() == 1:
# Don't lower bendy cells, instead leave it to form compiler
warning("Only know how to compute cell edge lengths of P1 or Q1 cell.")
warnings.warn("Only know how to compute cell edge lengths of P1 or Q1 cell.")
return o

elif domain.ufl_cell().cellname() == "interval":
Expand All @@ -297,7 +298,7 @@ def cell_diameter(self, o):

if not domain.ufl_coordinate_element().degree() in {1, (1, 1)}:
# Don't lower bendy cells, instead leave it to form compiler
warning("Only know how to compute cell diameter of P1 or Q1 cell.")
warnings.warn("Only know how to compute cell diameter of P1 or Q1 cell.")
return o

elif domain.is_piecewise_linear_simplex_domain():
Expand Down Expand Up @@ -331,7 +332,7 @@ def _reduce_facet_edge_length(self, o, reduction_op):

elif not domain.ufl_coordinate_element().degree() == 1:
# Don't lower bendy cells, instead leave it to form compiler
warning("Only know how to compute facet edge lengths of P1 or Q1 cell.")
warnings.warn("Only know how to compute facet edge lengths of P1 or Q1 cell.")
return o

else:
Expand Down
6 changes: 4 additions & 2 deletions ufl/algorithms/estimate_degrees.py
Expand Up @@ -10,7 +10,9 @@
# Modified by Anders Logg, 2009-2010
# Modified by Jan Blechta, 2012

from ufl.log import warning, error
import warnings

from ufl.log import error
from ufl.form import Form
from ufl.integral import Integral
from ufl.algorithms.multifunction import MultiFunction
Expand Down Expand Up @@ -117,7 +119,7 @@ def _not_handled(self, v, *args):

def expr(self, v, *ops):
"For most operators we take the max degree of its operands."
warning("Missing degree estimation handler for type %s" % v._ufl_class_.__name__)
warnings.warn("Missing degree estimation handler for type %s" % v._ufl_class_.__name__)
return self._add_degrees(v, *ops)

# Utility types with no degree concept
Expand Down
5 changes: 3 additions & 2 deletions ufl/algorithms/formtransformations.py
Expand Up @@ -12,8 +12,9 @@
# Modified by Garth N. Wells, 2010.
# Modified by Marie E. Rognes, 2010.

import warnings

from ufl.log import error, warning, debug
from ufl.log import error, debug

# All classes:
from ufl.core.expr import ufl_err_str
Expand Down Expand Up @@ -316,7 +317,7 @@ def compute_form_with_arity(form, arity, arguments=None):
error("compute_form_with_arity cannot handle parts.")

if len(arguments) < arity:
warning("Form has no parts with arity %d." % arity)
warnings.warn("Form has no parts with arity %d." % arity)
return 0 * form

# Assuming that the form is not a sum of terms
Expand Down
8 changes: 5 additions & 3 deletions ufl/conditional.py
Expand Up @@ -7,7 +7,9 @@
#
# SPDX-License-Identifier: LGPL-3.0-or-later

from ufl.log import warning, error
import warnings

from ufl.log import error
from ufl.core.expr import ufl_err_str
from ufl.core.ufl_type import ufl_type
from ufl.core.operator import Operator
Expand Down Expand Up @@ -265,7 +267,7 @@ def evaluate(self, x, mapping, component, index_values):
try:
res = min(a, b)
except ValueError:
warning('Value error in evaluation of min() of %s and %s.' % self.ufl_operands)
warnings.warn('Value error in evaluation of min() of %s and %s.' % self.ufl_operands)
raise
return res

Expand All @@ -290,7 +292,7 @@ def evaluate(self, x, mapping, component, index_values):
try:
res = max(a, b)
except ValueError:
warning('Value error in evaluation of max() of %s and %s.' % self.ufl_operands)
warnings.warn('Value error in evaluation of max() of %s and %s.' % self.ufl_operands)
raise
return res

Expand Down
12 changes: 7 additions & 5 deletions ufl/core/expr.py
Expand Up @@ -19,11 +19,13 @@
# Modified by Anders Logg, 2008
# Modified by Massimiliano Leoni, 2016

from ufl.log import error, deprecate
import warnings

from ufl.log import error

# --- The base object for all UFL expression tree nodes ---


class Expr(object):
"""Base class for all UFL expression types.
Expand Down Expand Up @@ -293,15 +295,15 @@ def _ufl_expr_reconstruct_(self, *operands):

def ufl_domains(self):
"Return all domains this expression is defined on."
deprecate("Expr.ufl_domains() is deprecated, please "
"use extract_domains(expr) instead.")
warnings.warn("Expr.ufl_domains() is deprecated, please "
"use extract_domains(expr) instead.", DeprecationWarning)
from ufl.domain import extract_domains
return extract_domains(self)

def ufl_domain(self):
"Return the single unique domain this expression is defined on, or throw an error."
deprecate("Expr.ufl_domain() is deprecated, please "
"use extract_unique_domain(expr) instead.")
warnings.warn("Expr.ufl_domain() is deprecated, please "
"use extract_unique_domain(expr) instead.", DeprecationWarning)
from ufl.domain import extract_unique_domain
return extract_unique_domain(self)

Expand Down
6 changes: 4 additions & 2 deletions ufl/core/terminal.py
Expand Up @@ -11,7 +11,9 @@
# Modified by Anders Logg, 2008
# Modified by Massimiliano Leoni, 2016

from ufl.log import error, warning
import warnings

from ufl.log import error
from ufl.core.expr import Expr
from ufl.core.ufl_type import ufl_type

Expand Down Expand Up @@ -59,7 +61,7 @@ def evaluate(self, x, mapping, component, index_values, derivatives=()):
if hasattr(self, 'ufl_evaluate'):
return self.ufl_evaluate(x, component, derivatives)
# Take component if any
warning("Couldn't map '%s' to a float, returning ufl object without evaluation." % str(self))
warnings.warn("Couldn't map '%s' to a float, returning ufl object without evaluation." % str(self))
f = self
if component:
f = f[component]
Expand Down
7 changes: 4 additions & 3 deletions ufl/finiteelement/elementlist.py
Expand Up @@ -13,9 +13,10 @@
# Modified by Lizao Li <lzlarryli@gmail.com>, 2015, 2016
# Modified by Massimiliano Leoni, 2016

import warnings
from numpy import asarray

from ufl.log import warning, error
from ufl.log import error
from ufl.sobolevspace import L2, H1, H2, HDiv, HCurl, HEin, HDivDiv, HInf
from ufl.utils.formatting import istr
from ufl.cell import Cell, TensorProductCell
Expand Down Expand Up @@ -436,11 +437,11 @@ def canonical_element_description(family, cell, order, form_degree):
family = "Q"
elif family == "Discontinuous Lagrange":
if order >= 1:
warning("Discontinuous Lagrange element requested on %s, creating DQ element." % cell.cellname())
warnings.warn("Discontinuous Lagrange element requested on %s, creating DQ element." % cell.cellname())
family = "DQ"
elif family == "Discontinuous Lagrange L2":
if order >= 1:
warning("Discontinuous Lagrange L2 element requested on %s, creating DQ L2 element." % cell.cellname())
warnings.warn("Discontinuous Lagrange L2 element requested on %s, creating DQ L2 element." % cell.cellname())
family = "DQ L2"

# Validate cellname if a valid cell is specified
Expand Down
5 changes: 3 additions & 2 deletions ufl/form.py
Expand Up @@ -11,10 +11,11 @@
# Modified by Massimiliano Leoni, 2016.
# Modified by Cecile Daversin-Catty, 2018.

import warnings
from itertools import chain
from collections import defaultdict

from ufl.log import error, warning
from ufl.log import error
from ufl.domain import sort_domains
from ufl.integral import Integral
from ufl.checks import is_scalar_constant_expression
Expand Down Expand Up @@ -378,7 +379,7 @@ def __call__(self, *args, **kwargs):
if f in coeffs:
repdict[f] = coefficients[f]
else:
warning("Coefficient %s is not in form." % ufl_err_str(f))
warnings.warn("Coefficient %s is not in form." % ufl_err_str(f))
if repdict:
from ufl.formoperators import replace
return replace(self, repdict)
Expand Down
39 changes: 8 additions & 31 deletions ufl/log.py
Expand Up @@ -14,22 +14,19 @@
import sys
import types
import logging
from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL # noqa: F401
import warnings
from logging import DEBUG, INFO, ERROR, CRITICAL # noqa: F401

log_functions = ["log", "debug", "info", "deprecate", "warning", "error",
log_functions = ["log", "debug", "info", "error",
"begin", "end",
"set_level", "push_level", "pop_level", "set_indent",
"add_indent",
"set_handler", "get_handler", "get_logger", "add_logfile",
"set_prefix",
"info_red", "info_green", "info_blue",
"warning_red", "warning_green", "warning_blue"]
"info_red", "info_green", "info_blue"]

__all__ = log_functions + ["Logger", "log_functions"] +\
["DEBUG", "INFO", "DEPRECATE", "WARNING", "ERROR", "CRITICAL"]


DEPRECATE = (INFO + WARNING) // 2
["DEBUG", "INFO", "ERROR", "CRITICAL"]


# This is used to override emit() in StreamHandler for printing
Expand Down Expand Up @@ -63,7 +60,7 @@ def __init__(self, name, exception_type=Exception):

# Set up handler
h = logging.StreamHandler(sys.stdout)
h.setLevel(WARNING)
h.setLevel(ERROR)
# Override emit() in handler for indentation
h.emit = types.MethodType(emit, h)
self._handler = h
Expand All @@ -90,7 +87,7 @@ def add_logfile(self, filename=None, mode="a", level=DEBUG):
if filename is None:
filename = "%s.log" % self._name
if filename in self._logfiles:
self.warning("Adding logfile %s multiple times." % filename)
warnings.warn("Adding logfile %s multiple times." % filename)
return
h = logging.FileHandler(filename, mode)
h.emit = types.MethodType(emit, h)
Expand Down Expand Up @@ -132,26 +129,6 @@ def info_blue(self, *message):
"Write info message in blue."
self.log(INFO, BLUE % self._format_raw(*message))

def deprecate(self, *message):
"Write deprecation message."
self.log(DEPRECATE, RED % self._format_raw(*message))

def warning(self, *message):
"Write warning message."
self._log.warning(self._format(*message))

def warning_red(self, *message):
"Write warning message in red."
self._log.warning(RED % self._format(*message))

def warning_green(self, *message):
"Write warning message in green."
self._log.warning(GREEN % self._format(*message))

def warning_blue(self, *message):
"Write warning message in blue."
self._log.warning(BLUE % self._format(*message))

def error(self, *message):
"Write error message and raise an exception."
self._log.error(*message)
Expand Down Expand Up @@ -242,4 +219,4 @@ class UFLValueError(UFLException):
for foo in log_functions:
exec("%s = ufl_logger.%s" % (foo, foo))

set_level(DEPRECATE) # noqa
set_level(ERROR) # noqa
7 changes: 4 additions & 3 deletions ufl/mathfunctions.py
Expand Up @@ -13,8 +13,9 @@
import math
import cmath
import numbers
import warnings

from ufl.log import warning, error
from ufl.log import error
from ufl.core.operator import Operator
from ufl.core.ufl_type import ufl_type
from ufl.constantvalue import is_true_ufl_scalar, Zero, RealValue, FloatValue, IntValue, ComplexValue, ConstantValue, as_ufl
Expand Down Expand Up @@ -63,7 +64,7 @@ def evaluate(self, x, mapping, component, index_values):
else:
res = getattr(cmath, self._name)(a)
except ValueError:
warning('Value error in evaluation of function %s with argument %s.' % (self._name, a))
warnings.warn('Value error in evaluation of function %s with argument %s.' % (self._name, a))
raise
return res

Expand Down Expand Up @@ -289,7 +290,7 @@ def evaluate(self, x, mapping, component, index_values):
except TypeError:
error('Atan2 does not support complex numbers.')
except ValueError:
warning('Value error in evaluation of function atan_2 with arguments %s, %s.' % (a, b))
warnings.warn('Value error in evaluation of function atan_2 with arguments %s, %s.' % (a, b))
raise
return res

Expand Down

0 comments on commit 4fd9a80

Please sign in to comment.