<commit_before>#!/usr/bin/env python3
#
# Tests the basic methods of the Nelder-Mead optimiser.
#
# This file is part of PINTS (https://github.com/pints-team/pints/) which is
# released under the BSD 3-clause license. See accompanying LICENSE.md for
# copyright notice and full license details.
#
import numpy as np
import unittest
import sys

import pints
import pints.toy

from shared import StreamCapture

debug = False
method = pints.NelderMead

# Consistent unit testing in Python 2 and 3
try:
    unittest.TestCase.assertRaisesRegex
except AttributeError:
    unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp


class TestNelderMead(unittest.TestCase):
    """
    Tests the basic methods of the Nelder-Mead optimiser.
    """
    def setUp(self):
        """ Called before every test """
        np.random.seed(1)

    def problem(self):
        """ Returns a test problem, starting point, sigma, and boundaries. """
        r = pints.toy.ParabolicError()
        x = [0.1, 0.1]
        s = 0.1
        b = pints.RectangularBoundaries([-1, -1], [1, 1])
        return r, x, s, b

    def test_unbounded(self):
        # Runs an optimisation without boundaries.
        r, x, s, b = self.problem()
        opt = pints.OptimisationController(r, x, method=method)
        opt.set_threshold(1e-3)
        opt.set_log_to_screen(debug)
        found_parameters, found_solution = opt.run()
        self.assertTrue(found_solution < 1e-3)

    @unittest.skipIf(sys.hexversion < 0x03040000, 'Python < 3.4')
    def test_bounded_warning(self):
        # Boundaries are not supported
        r, x, s, b = self.problem()

        # Rectangular boundaries
        with self.assertLogs(level='WARN'):
            pints.OptimisationController(r, x, boundaries=b, method=method)

    def test_ask_tell(self):
        # Tests ask-and-tell related error handling.
        r, x, s, b = self.problem()
        opt = method(x)

        # Stop called when not running
        self.assertFalse(opt.stop())

        # Best position and score called before run
        self.assertEqual(list(opt.xbest()), list(x))
        self.assertEqual(opt.fbest(), float('inf'))

        # Not running
        self.assertFalse(opt.running())

        # Running
        xs = opt.ask()
        fxs = [r(x) for x in xs]
        self.assertTrue(opt.running())
        opt.tell(fxs)
        self.assertTrue(opt.running())
        xs = opt.ask()
        fxs = [r(x) for x in xs]
        opt.tell(fxs)

        # Tell before ask
        self.assertRaisesRegex(<commit_msg>Fixed warning catching in nelder mead test.<commit_after>#!/usr/bin/env python3
#
# Tests the basic methods of the Nelder-Mead optimiser.
#
# This file is part of PINTS (https://github.com/pints-team/pints/) which is
# released under the BSD 3-clause license. See accompanying LICENSE.md for
# copyright notice and full license details.
#
import numpy as np
import unittest
import sys

import pints
import pints.toy

from shared import StreamCapture

debug = False
method = pints.NelderMead

# Consistent unit testing in Python 2 and 3
try:
    unittest.TestCase.assertRaisesRegex
except AttributeError:
    unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp


class TestNelderMead(unittest.TestCase):
    """
    Tests the basic methods of the Nelder-Mead optimiser.
    """
    def setUp(self):
        """ Called before every test """
        np.random.seed(1)

    def problem(self):
        """ Returns a test problem, starting point, sigma, and boundaries. """
        r = pints.toy.ParabolicError()
        x = [0.1, 0.1]
        s = 0.1
        b = pints.RectangularBoundaries([-1, -1], [1, 1])
        return r, x, s, b

    def test_unbounded(self):
        # Runs an optimisation without boundaries.
        r, x, s, b = self.problem()
        opt = pints.OptimisationController(r, x, method=method)
        opt.set_threshold(1e-3)
        opt.set_log_to_screen(debug)
        found_parameters, found_solution = opt.run()
        self.assertTrue(found_solution < 1e-3)

    @unittest.skipIf(sys.hexversion < 0x03040000, 'Python < 3.4')
    def test_bounded_warning(self):
        # Boundaries are not supported
        r, x, s, b = self.problem()

        # Rectangular boundaries
        import warnings
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            pints.OptimisationController(r, x, boundaries=b, method=method)
            self.assertEqual(len(w), 1)
            self.assertIn('does not support boundaries', str(w[-1].message))

    def test_ask_tell(self):
        # Tests ask-and-tell related error handling.
        r, x, s, b = self.problem()
        opt = method(x)

        # Stop called when not running
        self.assertFalse(opt.stop())

        # Best position and score called before run
        self.assertEqual(list(opt.xbest()), list(x))
        self.assertEqual(opt.fbest(), float('inf'))

        # Not running
        self.assertFalse(opt.running())

        # Running
        xs = opt.ask()
        fxs = [r(x) for x in xs]
        self.assertTrue(opt.running())
        opt.tell(fxs)
        self.assertTrue(opt.running())
        xs = opt.ask()
        fxs = [r(x) for x in xs]
        opt.tell(fxs)

        # Tell before ask
        self.assertRaisesRegex(
{'fraction_non_alphanumeric': 0.10892756878158338, 'fraction_numerical': 0.01160396780834737, 'mean_word_length': 2.5088640840446486, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7373132', 'n_tokens_mistral': 1725, 'n_tokens_neox': 1633, 'n_words': 455}