Ejemplo n.º 1
0
# This file is part of the pyMOR project (http://www.pymor.org).
# Copyright 2013-2019 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
from pymortests.base import runmodule
from pymortests.fixtures.analyticalproblem import analytical_problem, picklable_analytical_problem
from pymortests.pickling import assert_picklable, assert_picklable_without_dumps_function


def test_pickle(analytical_problem):
    assert_picklable(analytical_problem)


def test_pickle_without_dumps_function(picklable_analytical_problem):
    assert_picklable_without_dumps_function(picklable_analytical_problem)

if __name__ == "__main__":
    runmodule(filename=__file__)
Ejemplo n.º 2
0
        for g in self.grids:
            for d in xrange(g.dim):
                os, ps = g.reference_element(d).quadrature_info()
                for t in os.keys():
                    for o, p in izip(os[t], ps[t]):
                        self.assertEqual(
                            g.quadrature_points(d, order=o, quadrature_type=t).shape, (g.size(d), p, g.dim_outer)
                        )
                        self.assertEqual(
                            g.quadrature_points(d, npoints=p, quadrature_type=t).shape, (g.size(d), p, g.dim_outer)
                        )

    def test_quadrature_points_values(self):
        for g in self.grids:
            for d in xrange(g.dim):
                A, B = g.embeddings(d)
                os, ps = g.reference_element(d).quadrature_info()
                for t in os.keys():
                    for o, p in izip(os[t], ps[t]):
                        Q = g.quadrature_points(d, order=o, quadrature_type=t)
                        q, _ = g.reference_element(d).quadrature(order=o, quadrature_type=t)
                        np.testing.assert_allclose(Q, g.quadrature_points(d, npoints=p, quadrature_type=t))
                        np.testing.assert_allclose(Q, B[:, np.newaxis, :] + np.einsum("eij,qj->eqi", A, q))


# this needs to go into every module that wants to use dynamically generated types, ie. testcases, below the test code
from pymor.core.dynamic import *

if __name__ == "__main__":
    runmodule(name="pymortests.grid")
Ejemplo n.º 3
0
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

import numpy as np

from pymor.algorithms.basic import almost_equal
from pymor.core.pickle import dumps, loads
from pymortests.fixtures.discretization import discretization, picklable_discretization
from pymortests.base import runmodule
from pymortests.pickling import assert_picklable, assert_picklable_without_dumps_function


def test_pickle(discretization):
    assert_picklable(discretization)


def test_pickle_without_dumps_function(picklable_discretization):
    assert_picklable_without_dumps_function(picklable_discretization)


def test_pickle_by_solving(discretization):
    d = discretization
    d2 = loads(dumps(d))
    d.disable_caching()
    d2.disable_caching()
    for mu in d.parameter_space.sample_randomly(3, seed=234):
        assert np.all(almost_equal(d.solve(mu), d2.solve(mu)))


if __name__ == "__main__":
    runmodule(filename=__file__)
Ejemplo n.º 4
0
# This file is part of the pyMor project (http://www.pymor.org).
# Copyright Holders: Felix Albrecht, Rene Milk, Stephan Rave
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

from __future__ import absolute_import, division, print_function

from pymor.core import defaults
from pymortests.base import TestBase, runmodule


class DefaultsTest(TestBase):

    def testStr(self):
        rep = str(defaults)
        self.assertGreater(len(rep), 0)

if __name__ == "__main__":
    runmodule(name='pymortests.core.defaults')
Ejemplo n.º 5
0
from pymortests.base import (TestBase, runmodule, SubclassForImplemetorsOf)
from pymor import core


@SubclassForImplemetorsOf(BasicInterface)
class PickleMeInterface(TestBase):

    def testDump(self):
        try:
            obj = self.Type()
            self.assertIsInstance(obj, self.Type)
            if issubclass(self.Type, core.Unpicklable):
                return
        except TypeError as e:
            self.logger.debug('PicklingError: Not testing {} because its init failed: {}'.format(self.Type, str(e)))
            return

        with tempfile.NamedTemporaryFile(mode='wb', delete=False) as dump_file:
            core.dump(obj, dump_file)
            dump_file.close()
            f = open(dump_file.name, 'rb')
            unpickled = core.load(f)
            self.assertEqual(obj.__class__, unpickled.__class__)
            os.unlink(dump_file.name)

# this needs to go into every module that wants to use dynamically generated types, ie. testcases, below the test code
from pymor.core.dynamic import *

if __name__ == "__main__":
    runmodule(name='pymortests.core.pickling')
Ejemplo n.º 6
0
                dump_file.close()
                f = open(dump_file.name, 'rb')
                unpickled = pymor.core.load(f)
                self.assert_(getattr(obj, attribute_name) == getattr(unpickled, attribute_name))
                os.unlink(dump_file.name)
        picklme(AverageImplementer(), 'some_attribute')
        picklme(CacheImplementer(), 'some_attribute')
        picklme(RectGrid(num_intervals=(4, 4)), 'num_intervals')

    def testDeprecated(self):
        @decorators.Deprecated('use other stuff instead')
        def deprecated_function():
            pass
        # Cause all warnings to always be triggered.
        import warnings
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            # Trigger a warning.
            deprecated_function()
            # Verify some things
            self.assertEqual(len(w), 1)
            self.assertTrue(issubclass(w[-1].category, DeprecationWarning))
            self.assertTrue("DeprecationWarning" in str(w[-1].message))

    def testVersion(self):
        self.assertGreater(pymor.version, pymor.NO_VERSION)
        self.assertIsInstance(pymor.version, tuple)

if __name__ == "__main__":
    runmodule(name='pymortests.core.interface')
Ejemplo n.º 7
0
from __future__ import absolute_import, division, print_function

from pymor import parameters
from pymortests.base import TestBase, runmodule


class TestCubicParameterspace(TestBase):

    def setUp(self):
        TestBase.setUp(self)
        self.space = parameters.CubicParameterSpace({'diffusionl': 1}, 0.1, 1)
        self.samples = 100

    def _check_values(self, values):
        self.assertEqual(len(values), self.samples)
        for value in values:
            self.assertTrue(self.space.contains(value))

    def test_uniform(self):
        values = list(self.space.sample_uniformly(self.samples))
        self._check_values(values)

    def test_randomly(self):
        values = list(self.space.sample_randomly(self.samples))
        self._check_values(values)


if __name__ == "__main__":
    runmodule(name='pymortests.parameters')
Ejemplo n.º 8
0
            grid = mock.Mock()
            inst.validate_interface(object(), pymor.grids.boundaryinfos.AllDirichletBoundaryInfo(grid))

    def test_disabled_contracts(self):
        contracts.disable_all()

        @contract
        def disabled(phrase):
            '''
            :type phrase: str
            '''
            return phrase
        # this should not throw w/ contracts disabled
        disabled(int(8))
        contracts.enable_all()
        # this will still not throw because the disabled value is checked at decoration time only
        disabled(int(8))

        @contract
        def enabled(phrase):
            '''
            :type phrase: str
            '''
            return phrase
        # a newly decorated function will throw
        with self.assertRaises(exceptions.ContractNotRespected):
            enabled(int(8))

if __name__ == "__main__":
    runmodule(name='pymortests.core.contract')
Ejemplo n.º 9
0
# This file is part of the pyMor project (http://www.pymor.org).
# Copyright Holders: Felix Albrecht, Rene Milk, Stephan Rave
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

from __future__ import absolute_import, division, print_function

import numpy as np
import random
from math import sin, exp

from pymortests.base import TestBase, runmodule
from pymor.playground.expression_function import ExpressionFunction

FUNCTIONS = [(ExpressionFunction(['x**2'], 'x'), lambda x: np.array([x ** 2])),
             (ExpressionFunction(['x**2', 'sin(x)'], 'x'), lambda x: np.array([x ** 2, sin(x)])),
             (ExpressionFunction(['exp(xp)'], 'xp'), lambda x: np.array([exp(x)]))]


class TestExpressionFunction(TestBase):

    def test_eval(self):
        for (fn, fe) in FUNCTIONS:
            for x in (random.uniform(0, 1) for _ in xrange(9000)):
                np.testing.assert_array_almost_equal(fn([x]), fe(x))


if __name__ == "__main__":
    random.seed()
    runmodule(name='pymortests.playground')
Ejemplo n.º 10
0
                self.logger.info(int1 - int0)

    def test_limit(self):
        for c in [IamLimitedCached(cache.SMALL_MEMORY_CONFIG),
                  IamLimitedCached(cache.SMALL_DISK_CONFIG)]:
            for i in range(25):
                c.cache_region.backend.print_limit()
                _ = c.me_takey_no_time(i)
                c.cache_region.backend.print_limit()

    def test_copy(self):
        from copy import copy
        x = IWillBeCopied()
        x_id = x.my_id(1)
        y = copy(x)
        y_id = y.my_id(1)
        self.assertNotEqual(x_id, y_id)

    def test_backend_api(self):
        for backend_cls in [cache.LimitedFileBackend, cache.LimitedMemoryBackend, cache.DummyBackend]:
            backend = backend_cls({})
            self.assertEqual(backend.get('mykey'), cache.NO_VALUE)
            backend.set('mykey', 1)
            self.assertEqual(backend.get('mykey'), 1 if backend_cls != cache.DummyBackend else cache.NO_VALUE)
            backend.delete('mykey')
            self.assertEqual(backend.get('mykey'), cache.NO_VALUE)


if __name__ == "__main__":
    runmodule(name='pymortests.core.cache')
Ejemplo n.º 11
0
    exercise_logger(logger)


def logclass(cls):
    logger = cls.logger
    exercise_logger(logger)


def test_logger():
    import pymor

    fails = []
    for importer, pack_name, _ in pkgutil.walk_packages(
        pymor.__path__, pymor.__name__ + ".", lambda n: fails.append(n)
    ):
        yield logmodule, pack_name
        try:
            importer.find_module(pack_name).load_module(pack_name)
        except TypeError, e:
            fails.append(pack_name)
    import pprint

    if len(fails):
        core.getLogger(__name__).error("Failed imports: {}".format(pprint.pformat(set(fails))))
    for cls in pymor.core.interfaces.BasicInterface.implementors(True):
        yield logclass, cls


if __name__ == "__main__":
    runmodule(name="pymortests.core.logger")
Ejemplo n.º 12
0
        self.assertFalse(True, "test is missing")


class CmpTest(TestBase):

    def test_props(self):
        tol_range = [None, 0.0, 1]
        nan = float('nan')
        inf = float('inf')
        for (rtol, atol) in itertools.product(tol_range, tol_range):
            msg = 'rtol: {} | atol {}'.format(rtol, atol)
            self.assertTrue(float_cmp(0, 0, rtol, atol), msg)
            self.assertTrue(float_cmp(-0, -0, rtol, atol), msg)
            self.assertTrue(float_cmp(-1, -1, rtol, atol), msg)
            self.assertTrue(float_cmp(0, -0, rtol, atol), msg)
            self.assertFalse(float_cmp(2, -2, rtol, atol), msg)

            self.assertFalse(float_cmp(nan, nan, rtol, atol), msg)
            self.assertTrue(nan != nan)
            self.assertFalse(nan == nan)
            self.assertFalse(float_cmp(-nan, nan, rtol, atol), msg)

            self.assertFalse(float_cmp(inf, inf, rtol, atol), msg)
            self.assertFalse(inf != inf)
            self.assertTrue(inf == inf)
            self.assertTrue(float_cmp(-inf, inf, rtol, atol), msg)


if __name__ == "__main__":
    runmodule(name='pymortests.tools')
Ejemplo n.º 13
0
                        g.quadrature_points(d, npoints=max(ps[t]) + 1, quadrature_type=t)

    def test_quadrature_points_shape(self):
        for g in self.grids:
            for d in xrange(g.dim):
                os, ps = g.reference_element(d).quadrature_info()
                for t in os.keys():
                    for o, p in izip(os[t], ps[t]):
                        self.assertEqual(g.quadrature_points(d, order=o, quadrature_type=t).shape,
                                         (g.size(d), p, g.dim_outer))
                        self.assertEqual(g.quadrature_points(d, npoints=p, quadrature_type=t).shape,
                                         (g.size(d), p, g.dim_outer))

    def test_quadrature_points_values(self):
        for g in self.grids:
            for d in xrange(g.dim):
                A, B = g.embeddings(d)
                os, ps = g.reference_element(d).quadrature_info()
                for t in os.keys():
                    for o, p in izip(os[t], ps[t]):
                        Q = g.quadrature_points(d, order=o, quadrature_type=t)
                        q, _ = g.reference_element(d).quadrature(order=o, quadrature_type=t)
                        np.testing.assert_allclose(Q, g.quadrature_points(d, npoints=p, quadrature_type=t))
                        np.testing.assert_allclose(Q, B[:, np.newaxis, :] + np.einsum('eij,qj->eqi', A, q))

# this needs to go into every module that wants to use dynamically generated types, ie. testcases, below the test code
from pymor.core.dynamic import *

if __name__ == "__main__":
    runmodule(name='pymortests.grid')
Ejemplo n.º 14
0
# This file is part of the pyMor project (http://www.pymor.org).
# Copyright Holders: Felix Albrecht, Rene Milk, Stephan Rave
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

from __future__ import absolute_import, division, print_function

from pymortests.base import runmodule


if __name__ == "__main__":
    runmodule(name='pymortests.benchmarks')