# discretize.tests.OrderTest#

class discretize.tests.OrderTest(methodName='runTest')[source]#

Base class for testing convergence of discrete operators with respect to cell size.

OrderTest is a base class for testing the order of convergence of discrete operators with respect to cell size. OrderTest is inherited by the test class for the given operator. Within the test class, the user sets the parameters for the convergence testing and defines a method getError which defines the error as a norm of the residual (see example).

Parameters
namestr

Name the convergence test

meshTypeslist of str

List denoting the mesh types on which the convergence will be tested. List entries must of the list {‘uniformTensorMesh’, ‘randomTensorMesh’, ‘uniformCylindricalMesh’, ‘randomCylindricalMesh’, ‘uniformTree’, ‘randomTree’, ‘uniformCurv’, ‘rotateCurv’, ‘sphereCurv’}

expectedOrdersfloat or list of float (default = 2.0)

Defines the expect orders of convergence for all meshes defined in meshTypes. If list, must have same length as argument meshTypes.

tolerancefloat or list of float (default = 0.85)

Defines tolerance for numerical approximate of convergence order. If list, must have same length as argument meshTypes.

meshSizeslist of int

From coarsest to finest, defines the number of mesh cells in each axis direction for the meshes used in the convergence test; e.g. [4, 8, 16, 32]

meshDimensionint

Mesh dimension. Must be 1, 2 or 3

Notes

Consider an operator $$A(f)$$ that acts on a test function $$f$$. And let $$A_h (f)$$ be the discrete approximation to the original operator constructed on a mesh will cell size $$h$$. OrderTest assesses the convergence of

$error(h) = \| A_h(f) - A(f) \|$

as $$h \rightarrow 0$$. Note that you can provide any norm to quantify the error. The convergence test is passed when the numerically estimated rate of convergence is within a specified tolerance of the expected convergence rate supplied by the user.

Examples

Here, we utilize the OrderTest class to validate the rate of convergence for the face_divergence. Our convergence test is done for a uniform 2D tensor mesh. Under the test class TestDIV2D, we define the static parameters for the order test. We then define a method getError for this class which returns the norm of some residual. With these two pieces defined, we can call the order test as shown below.

>>> from discretize.tests import OrderTest
>>> import unittest
>>> import numpy as np

>>> class TestDIV2D(OrderTest):
...     # Static properties for OrderTest
...     name = "Face Divergence 2D"
...     meshTypes = ["uniformTensorMesh"]
...     meshDimension = 2
...     expectedOrders = 2.0
...     tolerance = 0.85
...     meshSizes = [8, 16, 32, 64]
...     def getError(self):
...         # Test function
...         fx = lambda x, y: np.sin(2 * np.pi * x)
...         fy = lambda x, y: np.sin(2 * np.pi * y)
...         # Analytic solution for operator acting on test function
...         sol = lambda x, y: 2 * np.pi * (np.cos(2 * np.pi * x) + np.cos(2 * np.pi * y))
...         # Evaluate test function on faces
...         f = np.r_[
...             fx(self.M.faces_x[:, 0], self.M.faces_x[:, 1]),
...             fy(self.M.faces_y[:, 0], self.M.faces_y[:, 1])
...         ]
...         # Analytic solution at cell centers
...         div_f = sol(self.M.cell_centers[:, 0], self.M.cell_centers[:, 1])
...         # Numerical approximation of divergence at cell centers
...         div_f_num = self.M.face_divergence * f
...         # Define the error function as a norm
...         err = np.linalg.norm((div_f_num - div_f), np.inf)
...         return err
...     def test_order(self):
...         self.orderTest()


Methods

 __call__(*args, **kwds) Call self as a function. addClassCleanup(function, /, *args, **kwargs) Same as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass). addCleanup(function, *args, **kwargs) Add a function, with arguments, to be called when the test is completed. addTypeEqualityFunc(typeobj, function) Add a type specific assertEqual style function to compare a type. assertAlmostEqual(first, second[, places, ...]) Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta. assertCountEqual(first, second[, msg]) Asserts that two iterables have the same elements, the same number of times, without regard to order. assertDictContainsSubset(subset, dictionary) Checks whether dictionary is a superset of subset. assertEqual(first, second[, msg]) Fail if the two objects are unequal as determined by the '==' operator. assertFalse(expr[, msg]) Check that the expression is false. assertGreater(a, b[, msg]) Just like self.assertTrue(a > b), but with a nicer default message. assertGreaterEqual(a, b[, msg]) Just like self.assertTrue(a >= b), but with a nicer default message. assertIn(member, container[, msg]) Just like self.assertTrue(a in b), but with a nicer default message. assertIs(expr1, expr2[, msg]) Just like self.assertTrue(a is b), but with a nicer default message. assertIsInstance(obj, cls[, msg]) Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message. assertIsNone(obj[, msg]) Same as self.assertTrue(obj is None), with a nicer default message. assertIsNot(expr1, expr2[, msg]) Just like self.assertTrue(a is not b), but with a nicer default message. assertIsNotNone(obj[, msg]) Included for symmetry with assertIsNone. assertLess(a, b[, msg]) Just like self.assertTrue(a < b), but with a nicer default message. assertLessEqual(a, b[, msg]) Just like self.assertTrue(a <= b), but with a nicer default message. assertListEqual(list1, list2[, msg]) A list-specific equality assertion. assertLogs([logger, level]) Fail unless a log message of level level or higher is emitted on logger_name or its children. assertMultiLineEqual(first, second[, msg]) Assert that two multi-line strings are equal. assertNotAlmostEqual(first, second[, ...]) Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta. assertNotEqual(first, second[, msg]) Fail if the two objects are equal as determined by the '!=' operator. assertNotIn(member, container[, msg]) Just like self.assertTrue(a not in b), but with a nicer default message. assertNotIsInstance(obj, cls[, msg]) Included for symmetry with assertIsInstance. assertNotRegex(text, unexpected_regex[, msg]) Fail the test if the text matches the regular expression. assertRaises(expected_exception, *args, **kwargs) Fail unless an exception of class expected_exception is raised by the callable when invoked with specified positional and keyword arguments. assertRaisesRegex(expected_exception, ...) Asserts that the message in a raised exception matches a regex. assertRegex(text, expected_regex[, msg]) Fail the test unless the text matches the regular expression. assertSequenceEqual(seq1, seq2[, msg, seq_type]) An equality assertion for ordered sequences (like lists and tuples). assertSetEqual(set1, set2[, msg]) A set-specific equality assertion. assertTrue(expr[, msg]) Check that the expression is true. assertTupleEqual(tuple1, tuple2[, msg]) A tuple-specific equality assertion. assertWarns(expected_warning, *args, **kwargs) Fail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. assertWarnsRegex(expected_warning, ...) Asserts that the message in a triggered warning matches a regexp. Run the test without collecting errors in a TestResult Execute all class cleanup functions. Execute all cleanup functions. fail([msg]) Fail immediately, with the given message. failureException alias of AssertionError Compute error defined as a norm of the residual. For number of cells specified in meshSizes setup mesh, call getError and prints mesh size, error, ratio between current and previous error, and estimated order of convergence. Hook method for setting up the test fixture before exercising it. Hook method for setting up class fixture before running tests in the class. Generate mesh and set as current mesh for testing. Returns a one-line description of the test, or None if no description has been provided. skipTest(reason) Skip this test. subTest([msg]) Return a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. Hook method for deconstructing the test fixture after testing it. Hook method for deconstructing the class fixture after running all tests in the class.
 assertAlmostEquals assertDictEqual assertEquals assertNotAlmostEquals assertNotEquals assertNotRegexpMatches assertRaisesRegexp assertRegexpMatches assert_ countTestCases defaultTestResult failIf failIfAlmostEqual failIfEqual failUnless failUnlessAlmostEqual failUnlessEqual failUnlessRaises id run