<commit_before>from ..base import BaseTopazTest

class TestConstraintVariableObject(BaseTopazTest):
    def test_names(self, space):
        space.execute("ConstraintVariable")
        space.execute("Constraints")

    def test_local(self, space):
        w_res = space.execute("""
        require "libcassowary"
        a = 1
        always{ a == 10 }
        return a
        """)
        assert self.unwrap(space, w_res) == 10
        w_res = space.execute("""
        b = 1
        always { b > 10 }
        b = 11
        return b
        """)
        assert self.unwrap(space, w_res) == 11

    def test_ivar(self, space):
        w_res = space.execute("""
        require "libcassowary"
        @a = 1
        always { @a == 10 }
        return @a
        """)
        assert self.unwrap(space, w_res) == 10
        w_res = space.execute("""
        @b = 1
        always { @b > 10 }
        @b = 11
        return @b
        """)
        assert self.unwrap(space, w_res) == 11

    def test_cvar(self, space):
        w_res = space.execute("""
        require "libcassowary"
        @@a = 1
        always { @@a == 10 }
        return @@a
        """)
        assert self.unwrap(space, w_res) == 10
        w_res = space.execute("""
        @@b = 1
        always { @@b > 10 }
        @@b = 11
        return @@b
        """)
        assert self.unwrap(space, w_res) == 11

    def test_simple_path(self, space):
        w_res = space.execute("""
        require "libcassowary"
        res = []
        class Point
          def x
            @x
          end

          def y
            @y
          end

          def initialize(x, y)
            @x = x
            @y = y
            always { @x >= 0 }
            always { @y >= 0 }
            always { @x < 640 }
            always { @y < 480 }
          end
        end

        pt1 = Point.new(-1, 10)
        pt2 = Point.new(20, 20)
        res << [[pt1.x, pt1.y], [pt2.x, pt2.y]]
        always { pt1.x == pt2.x }
        res << [[pt1.x, pt1.y], [pt2.x, pt2.y]]
        always { pt1.x == 5 }
        res << [[pt1.x, pt1.y], [pt2.x, pt2.y]]
        """)
        assert self.unwrap(space, w_res) == [
            [[0, 10], [20, 20]],
            [[0, 10], [0, 20]],
            [[5, 10], [5, 20]]
        ] or self.unwrap(space, w_res) == [
            [[0, 10], [20, 20]],
            [[20, 10], [20, 20]],
            [[5, 10], [5, 20]]
        ]

    def test_complex_path(self, space):
        w_res = space.execute("""
        require "libcassowary"
        res = []
        class Point
          def x
            @x
          end

          def y
            @y
          end

          def initialize(x, y)
            @x = x
            @y = y
            always { @x >= 0 }
            always { @y >= 0 }
            always { @x < 640 }
            always { @y < 480 }
          end
        end

        class HorizontalLine
          def start
            @start
          end

          def end
            @end
          end

          def initialize(pt1, pt2)
            @start = pt1
            @end = pt2
            always { pt1.y == pt2.y }
          end

          def length
            @end.x - @start.x
          end
        end

        h = HorizontalLine.new(Point.new(1, 1), Point.new(2, 2))
        always { h.length >= 100 }
        return h.length
        """)
        assert self.unwrap(space, w_res) == 100

    def test_errors(self, space):
        with self.raises(space, "ArgumentError"):
            space.execute("always")
        with self.raises(space, "TypeError"):
            space.execute("always { true }")
        with self.raises(space, "TypeError"):
            space.execute("always { true }")

    def test_preferences(self, space):
        w_res = space.execute("""
        require "libcassowary"
        res = []
        x = 10
        always(:strong) { x > 10 }
        res << x
        always(:medium) { x < 5 }
        res << x
        always(:required) { x < 10 }
        res << x
        return res
        """)
        assert self.unwrap(space, w_res) == [11, 11, 9]

    def test_quadratic(self, space):
        w_res = space.execute("""
        require "libz3"
        a = 1.0
        always { a ** 2.0 < 16 }
        return a
        """)
        assert self.unwrap(space, w_res) == -3

    def test_quadratic_real(self, space):
        w_res = space.execute("""
        require "libz3"
        a = 1.0
        always { a ** 2.0 == 30.25 }
        return a
        """)
        assert self.unwrap(space, w_res) == -5.5

    def test_quadratic_pos_real(self, space):
        w_res = space.execute("""
        require "libz3"
        a = 1.0
        always { a ** 2.0 == 30.25 }
        always { a > 0 }
        return a
        """)
        assert self.unwrap(space, w_res) == 5.5

    def test_boolean(self, space):
        w_res = space.execute("""
        require "libz3"
        a = false
        always { a == true }
        return a
        """)
        assert w_res is space.w_true

    def test_div(self, space):
        w_res = space.execute("""
        require "libz3"
        x = 5
        y = 1
        always { x / y == 2 }
        return x, y
        """)
        assert self.unwrap(space, w_res) == [1, 0]

    def test_complex_path_with_z3(self, space):
        w_res = space.execute("""
        require "libz3"
        res = []
        class Point
          def x
            @x
          end

          def y
            @y
          end

          def initialize(x, y)
            @x = x
            @y = y
            always { @x >= 0 }
            always { @y >= 0 }
            always { @x < 640 }
            always { @y < 480 }
          end
        end

        class HorizontalLine
          def start
            @start
          end

          def end
            @end
          end

          def initialize(pt1, pt2)
            @start = pt1
            @end = pt2
            always { pt1.y == pt2.y }
          end

          def length
            @end.x - @start.x
          end
        end

        h = HorizontalLine.new(Point.new(1, 1), Point.new(2, 2))
        always { h.length >= 100 }
        return h.length
        """)
        assert self.unwrap(space, w_res) >= 100

    def test_attr_reader(self, space):
        w_res = space.execute("""
        require "libz3"
        res = []
        class Point
          attr_accessor :x, :y

          def initialize(x, y)
            self.x = x
            self.y = y
            always { self.x >= 0 }
            always { self.y >= 0 }
          end
        end
        pt = Point.new(-10, -10)
        return pt.x, pt.y
        """)
        assert self.unwrap(space, w_res) == [0, 0]
<commit_msg>[TDD] add a test for the behaviour when setting variables on the path to a constraint<commit_after>from ..base import BaseTopazTest

class TestConstraintVariableObject(BaseTopazTest):
    def test_names(self, space):
        space.execute("ConstraintVariable")
        space.execute("Constraints")

    def test_local(self, space):
        w_res = space.execute("""
        require "libcassowary"
        a = 1
        always{ a == 10 }
        return a
        """)
        assert self.unwrap(space, w_res) == 10
        w_res = space.execute("""
        b = 1
        always { b > 10 }
        b = 11
        return b
        """)
        assert self.unwrap(space, w_res) == 11

    def test_ivar(self, space):
        w_res = space.execute("""
        require "libcassowary"
        @a = 1
        always { @a == 10 }
        return @a
        """)
        assert self.unwrap(space, w_res) == 10
        w_res = space.execute("""
        @b = 1
        always { @b > 10 }
        @b = 11
        return @b
        """)
        assert self.unwrap(space, w_res) == 11

    def test_cvar(self, space):
        w_res = space.execute("""
        require "libcassowary"
        @@a = 1
        always { @@a == 10 }
        return @@a
        """)
        assert self.unwrap(space, w_res) == 10
        w_res = space.execute("""
        @@b = 1
        always { @@b > 10 }
        @@b = 11
        return @@b
        """)
        assert self.unwrap(space, w_res) == 11

    def test_simple_path(self, space):
        w_res = space.execute("""
        require "libcassowary"
        res = []
        class Point
          def x
            @x
          end

          def y
            @y
          end

          def initialize(x, y)
            @x = x
            @y = y
            always { @x >= 0 }
            always { @y >= 0 }
            always { @x < 640 }
            always { @y < 480 }
          end
        end

        pt1 = Point.new(-1, 10)
        pt2 = Point.new(20, 20)
        res << [[pt1.x, pt1.y], [pt2.x, pt2.y]]
        always { pt1.x == pt2.x }
        res << [[pt1.x, pt1.y], [pt2.x, pt2.y]]
        always { pt1.x == 5 }
        res << [[pt1.x, pt1.y], [pt2.x, pt2.y]]
        """)
        assert self.unwrap(space, w_res) == [
            [[0, 10], [20, 20]],
            [[0, 10], [0, 20]],
            [[5, 10], [5, 20]]
        ] or self.unwrap(space, w_res) == [
            [[0, 10], [20, 20]],
            [[20, 10], [20, 20]],
            [[5, 10], [5, 20]]
        ]

    def test_complex_path(self, space):
        w_res = space.execute("""
        require "libcassowary"
        res = []
        class Point
          def x
            @x
          end

          def y
            @y
          end

          def initialize(x, y)
            @x = x
            @y = y
            always { @x >= 0 }
            always { @y >= 0 }
            always { @x < 640 }
            always { @y < 480 }
          end
        end

        class HorizontalLine
          def start
            @start
          end

          def end
            @end
          end

          def initialize(pt1, pt2)
            @start = pt1
            @end = pt2
            always { pt1.y == pt2.y }
          end

          def length
            @end.x - @start.x
          end
        end

        h = HorizontalLine.new(Point.new(1, 1), Point.new(2, 2))
        always { h.length >= 100 }
        return h.length
        """)
        assert self.unwrap(space, w_res) == 100

    def test_errors(self, space):
        with self.raises(space, "ArgumentError"):
            space.execute("always")
        with self.raises(space, "TypeError"):
            space.execute("always { true }")
        with self.raises(space, "TypeError"):
            space.execute("always { true }")

    def test_preferences(self, space):
        w_res = space.execute("""
        require "libcassowary"
        res = []
        x = 10
        always(:strong) { x > 10 }
        res << x
        always(:medium) { x < 5 }
        res << x
        always(:required) { x < 10 }
        res << x
        return res
        """)
        assert self.unwrap(space, w_res) == [11, 11, 9]

    def test_quadratic(self, space):
        w_res = space.execute("""
        require "libz3"
        a = 1.0
        always { a ** 2.0 < 16 }
        return a
        """)
        assert self.unwrap(space, w_res) == -3

    def test_quadratic_real(self, space):
        w_res = space.execute("""
        require "libz3"
        a = 1.0
        always { a ** 2.0 == 30.25 }
        return a
        """)
        assert self.unwrap(space, w_res) == -5.5

    def test_quadratic_pos_real(self, space):
        w_res = space.execute("""
        require "libz3"
        a = 1.0
        always { a ** 2.0 == 30.25 }
        always { a > 0 }
        return a
        """)
        assert self.unwrap(space, w_res) == 5.5

    def test_boolean(self, space):
        w_res = space.execute("""
        require "libz3"
        a = false
        always { a == true }
        return a
        """)
        assert w_res is space.w_true

    def test_div(self, space):
        w_res = space.execute("""
        require "libz3"
        x = 5
        y = 1
        always { x / y == 2 }
        return x, y
        """)
        assert self.unwrap(space, w_res) == [1, 0]

    def test_complex_path_with_z3(self, space):
        w_res = space.execute("""
        require "libz3"
        res = []
        class Point
          def x
            @x
          end

          def y
            @y
          end

          def initialize(x, y)
            @x = x
            @y = y
            always { @x >= 0 }
            always { @y >= 0 }
            always { @x < 640 }
            always { @y < 480 }
          end
        end

        class HorizontalLine
          def start
            @start
          end

          def end
            @end
          end

          def initialize(pt1, pt2)
            @start = pt1
            @end = pt2
            always { pt1.y == pt2.y }
          end

          def length
            @end.x - @start.x
          end
        end

        h = HorizontalLine.new(Point.new(1, 1), Point.new(2, 2))
        always { h.length >= 100 }
        return h.length
        """)
        assert self.unwrap(space, w_res) >= 100

    def test_attr_reader(self, space):
        w_res = space.execute("""
        require "libz3"
        res = []
        class Point
          attr_accessor :x, :y

          def initialize(x, y)
            self.x = x
            self.y = y
            always { self.x >= 0 }
            always { self.y >= 0 }
          end
        end
        pt = Point.new(-10, -10)
        return pt.x, pt.y
        """)
        assert self.unwrap(space, w_res) == [0, 0]

    def test_invalidation_along_path(self, space):
        w_res = space.execute("""
        require "libz3"

        $area_executions = 0
        res = []

        class Point
          attr_accessor :x, :y

          def initialize(x, y)
            self.x, self.y = x, y
          end
        end

        class Rect
          attr_accessor :origin, :extent

          def initialize(origin, extent)
            self.origin, self.extent = origin, extent
          end

          def area
            $area_executions += 1
            extent.x * extent.y
          end
        end

        r = Rect.new(Point.new(0, 0), Point.new(10, 10))
        always { r.area > 100 }
        res << r.extent.x << r.extent.y

        r.extent.x = 100
        res << r.extent.x << r.extent.y

        r.extent = Point.new(50, 50)
        res << r.extent.x << r.extent.y

        return res, $area_executions
        """)
        assert self.unwrap(space, w_res) == [
            [
                11, 10,
                100, 10,
                50, 50
            ],
            2
        ]
<|endoftext|>


<commit_before>import threading
import unittest

from opentrons.robot.robot import Robot
from opentrons.containers.placeable import Deck
from opentrons import instruments, containers
from opentrons.util.vector import Vector

class RobotTest(unittest.TestCase):
    def setUp(self):
        Robot.reset_for_tests()
        self.robot = Robot.get_instance()

        self.robot.reset()
        self.robot.connect()
        self.robot.home(enqueue=False)

    def test_add_container(self):
        c1 = self.robot.add_container('96-flat', 'A1')
        res = self.robot.containers()
        expected = {
            '96-flat': c1
        }
        self.assertEquals(res, expected)

        c2 = self.robot.add_container('96-flat', 'A2', 'my-special-plate')
        res = self.robot.containers()
        expected = {
            '96-flat': c1,
            'my-special-plate': c2
        }
        self.assertEquals(res, expected)

    def test_comment(self):
        self.robot.clear_commands()
        self.robot.comment('hello')
        self.assertEquals(len(self.robot.commands()), 1)
        self.assertEquals(self.robot._commands[0].description, 'hello')

    def test_home_after_disconnect(self):
        self.robot.disconnect()
        self.assertRaises(RuntimeError, self.robot.home)

    def test_simulate(self):
        self.robot.disconnect()
        p200 = instruments.Pipette(axis='b', name='my-fancy-pancy-pipette')
        p200.aspirate().dispense()
        self.robot.simulate()
        self.assertEquals(len(self.robot._commands), 2)
        self.assertEquals(self.robot.connections['live'], None)

    def test_stop_run(self):
        p200 = instruments.Pipette(axis='b', name='my-fancy-pancy-pipette')
        p200.calibrate_plunger(top=0, bottom=5, blow_out=6, drop_tip=7)

        for i in range(1000):
            p200.aspirate().dispense()

        res = None

        def _run():
            nonlocal res
            res = self.robot.run()

        thread = threading.Thread(target=_run)
        thread.start()

        self.robot.stop()

        thread.join()

        self.assertEquals(
            res[-1], 'Received a STOP signal and exited from movements')

    def test_calibrated_max_dimension(self):

        expected = self.robot._deck.max_dimensions(self.robot._deck)
        res = self.robot._calibrated_max_dimension()
        self.assertEquals(res, expected)

        p200 = instruments.Pipette(axis='b', name='my-fancy-pancy-pipette')
        plate = containers.load('96-flat', 'A1')
        self.robot.move_head(x=10, y=10, z=10)
        p200.calibrate_position((plate, Vector(0, 0, 0)))

        res = self.robot._calibrated_max_dimension()

        expected = Vector(plate.max_dimensions(plate)) + Vector(10, 10, 10)
        self.assertEquals(res, expected)

    def test_create_arc(self):
        p200 = instruments.Pipette(axis='b', name='my-fancy-pancy-pipette')
        plate = containers.load('96-flat', 'A1')
        plate2 = containers.load('96-flat', 'B1')

        self.robot.move_head(x=10, y=10, z=10)
        p200.calibrate_position((plate, Vector(0, 0, 0)))
        self.robot.move_head(x=10, y=10, z=100)
        p200.calibrate_position((plate2, Vector(0, 0, 0)))

        res = self.robot._create_arc((0, 0, 0), plate[0])
        expected = [
            {'z': 100},
            {'x': 0, 'y': 0},
            {'z': 0}
        ]
        self.assertEquals(res, expected)

        res = self.robot._create_arc((0, 0, 0), plate[0])
        expected = [
            {'z': 20.5 + 5},
            {'x': 0, 'y': 0},
            {'z': 0}
        ]
        self.assertEquals(res, expected)

    def test_disconnect(self):
        self.robot.disconnect()
        res = self.robot.is_connected()
        self.assertEquals(bool(res), False)

    def test_get_connected_port(self):
        res = self.robot.get_connected_port()
        self.assertEquals(res, self.robot.VIRTUAL_SMOOTHIE_PORT)

    def test_robot_move_to(self):
        self.robot.move_to((Deck(), (100, 0, 0)))
        self.robot.run()
        position = self.robot._driver.get_head_position()['current']
        self.assertEqual(position, (100, 0, 0))

    def test_move_head(self):
        self.robot.move_head(x=100, y=0, z=20)
        current = self.robot._driver.get_head_position()['current']
        self.assertEquals(current, (100, 0, 20))

    def test_home(self):

        self.robot.disconnect()
        self.robot.connect()

        self.assertDictEqual(self.robot.axis_homed, {
            'x': False, 'y': False, 'z': False, 'a': False, 'b': False
        })

        self.robot.clear_commands()
        self.robot.home('xa', enqueue=True)
        self.assertDictEqual(self.robot.axis_homed, {
            'x': False, 'y': False, 'z': False, 'a': False, 'b': False
        })
        self.assertEquals(len(self.robot._commands), 1)
        self.robot.run()
        self.assertDictEqual(self.robot.axis_homed, {
            'x': True, 'y': False, 'z': False, 'a': True, 'b': False
        })

        self.robot.clear_commands()
        self.robot.home(enqueue=False)
        self.assertEquals(len(self.robot._commands), 0)

        self.assertDictEqual(self.robot.axis_homed, {
            'x': True, 'y': True, 'z': True, 'a': True, 'b': True
        })

    def test_robot_pause_and_resume(self):
        self.robot.move_to((Deck(), (100, 0, 0)), enqueue=True)
        self.robot.move_to((Deck(), (101, 0, 0)), enqueue=True)
        self.assertEqual(len(self.robot._commands), 2)

        self.robot.pause()

        def _run():
            self.robot.run()

        thread = threading.Thread(target=_run)
        thread.start()
        self.robot.resume()
        thread.join(0.5)

        self.assertEquals(thread.is_alive(), False)
        self.assertEqual(len(self.robot._commands), 2)

        self.robot.clear_commands()
        self.assertEqual(len(self.robot._commands), 0)

        self.robot.move_to((Deck(), (100, 0, 0)), enqueue=True)
        self.robot.move_to((Deck(), (101, 0, 0)), enqueue=True)

        def _run():
            self.robot.run()

        self.robot.pause()

        thread = threading.Thread(target=_run)
        thread.start()
        thread.join(0.01)

        self.assertEquals(thread.is_alive(), True)
        self.assertEqual(len(self.robot._commands) > 0, True)

        self.robot.resume()

        thread.join(1)
        self.assertEqual(len(self.robot._commands), 2)

    def test_versions(self):
        res = self.robot.versions()
        expected = {
            'config': {
                'version': 'v1.2.0',
                'compatible': True
            },
            'firmware': {
                'version': 'v1.0.5',
                'compatible': True
            },
            'ot_version': {
                'version': 'one_pro',
                'compatible': True
            }
        }
        self.assertDictEqual(res, expected)

    def test_diagnostics(self):
        res = self.robot.diagnostics()
        expected = {
            'axis_homed': {
                'x': True, 'y': True, 'z': True, 'a': True, 'b': True
            },
            'switches': {
                'x': False,
                'y': False,
                'z': False,
                'a': False,
                'b': False
            },
            'steps_per_mm': {
                'x': 80.0,
                'y': 80.0
            }
        }
        self.assertDictEqual(res, expected)

        self.robot.disconnect()
        self.robot.connect()
        self.assertRaises(RuntimeWarning, self.robot.move_head, x=-199)
        res = self.robot.diagnostics()
        expected = {
            'axis_homed': {
                'x': False, 'y': False, 'z': False, 'a': False, 'b': False
            },
            'switches': {
                'x': True,
                'y': False,
                'z': False,
                'a': False,
                'b': False
            },
            'steps_per_mm': {
                'x': 80.0,
                'y': 80.0
            }
        }
        self.assertDictEqual(res, expected)

        self.robot.home('x', enqueue=False)
        res = self.robot.diagnostics()
        expected = {
            'axis_homed': {
                'x': True, 'y': False, 'z': False, 'a': False, 'b': False
            },
            'switches': {
                'x': False,
                'y': False,
                'z': False,
                'a': False,
                'b': False
            },
            'steps_per_mm': {
                'x': 80.0,
                'y': 80.0
            }
        }
        self.assertDictEqual(res, expected)

    def test_get_motor(self):
        a_motor = self.robot.get_motor('a')
        self.assertEqual(
            a_motor,
            self.robot.get_motor('a')
        )

        b_motor = self.robot.get_motor('b', mosfet_index=1)
        self.assertEqual(
            b_motor,
            self.robot.get_motor('a', mosfet_index=1)
        )

    def test_send_to_app_with_unconfigured_robot(self):
        self.robot.send_to_app()

    def test_send_to_app_with_configured_robot(self):
        plate = containers.load('96-flat', 'A1')
        p200 = instruments.Pipette(axis='b', max_volume=200)

        for well in plate:
            p200.aspirate(well).delay(5).dispense(well)

        self.robot.send_to_app()
<commit_msg>adds test for motor/mosfet caching<commit_after>import threading
import unittest

from opentrons.robot.robot import Robot
from opentrons.containers.placeable import Deck
from opentrons import instruments, containers
from opentrons.util.vector import Vector

class RobotTest(unittest.TestCase):
    def setUp(self):
        Robot.reset_for_tests()
        self.robot = Robot.get_instance()

        self.robot.reset()
        self.robot.connect()
        self.robot.home(enqueue=False)

    def test_add_container(self):
        c1 = self.robot.add_container('96-flat', 'A1')
        res = self.robot.containers()
        expected = {
            '96-flat': c1
        }
        self.assertEquals(res, expected)

        c2 = self.robot.add_container('96-flat', 'A2', 'my-special-plate')
        res = self.robot.containers()
        expected = {
            '96-flat': c1,
            'my-special-plate': c2
        }
        self.assertEquals(res, expected)

    def test_comment(self):
        self.robot.clear_commands()
        self.robot.comment('hello')
        self.assertEquals(len(self.robot.commands()), 1)
        self.assertEquals(self.robot._commands[0].description, 'hello')

    def test_home_after_disconnect(self):
        self.robot.disconnect()
        self.assertRaises(RuntimeError, self.robot.home)

    def test_simulate(self):
        self.robot.disconnect()
        p200 = instruments.Pipette(axis='b', name='my-fancy-pancy-pipette')
        p200.aspirate().dispense()
        self.robot.simulate()
        self.assertEquals(len(self.robot._commands), 2)
        self.assertEquals(self.robot.connections['live'], None)

    def test_stop_run(self):
        p200 = instruments.Pipette(axis='b', name='my-fancy-pancy-pipette')
        p200.calibrate_plunger(top=0, bottom=5, blow_out=6, drop_tip=7)

        for i in range(1000):
            p200.aspirate().dispense()

        res = None

        def _run():
            nonlocal res
            res = self.robot.run()

        thread = threading.Thread(target=_run)
        thread.start()

        self.robot.stop()

        thread.join()

        self.assertEquals(
            res[-1], 'Received a STOP signal and exited from movements')

    def test_calibrated_max_dimension(self):

        expected = self.robot._deck.max_dimensions(self.robot._deck)
        res = self.robot._calibrated_max_dimension()
        self.assertEquals(res, expected)

        p200 = instruments.Pipette(axis='b', name='my-fancy-pancy-pipette')
        plate = containers.load('96-flat', 'A1')
        self.robot.move_head(x=10, y=10, z=10)
        p200.calibrate_position((plate, Vector(0, 0, 0)))

        res = self.robot._calibrated_max_dimension()

        expected = Vector(plate.max_dimensions(plate)) + Vector(10, 10, 10)
        self.assertEquals(res, expected)

    def test_create_arc(self):
        p200 = instruments.Pipette(axis='b', name='my-fancy-pancy-pipette')
        plate = containers.load('96-flat', 'A1')
        plate2 = containers.load('96-flat', 'B1')

        self.robot.move_head(x=10, y=10, z=10)
        p200.calibrate_position((plate, Vector(0, 0, 0)))
        self.robot.move_head(x=10, y=10, z=100)
        p200.calibrate_position((plate2, Vector(0, 0, 0)))

        res = self.robot._create_arc((0, 0, 0), plate[0])
        expected = [
            {'z': 100},
            {'x': 0, 'y': 0},
            {'z': 0}
        ]
        self.assertEquals(res, expected)

        res = self.robot._create_arc((0, 0, 0), plate[0])
        expected = [
            {'z': 20.5 + 5},
            {'x': 0, 'y': 0},
            {'z': 0}
        ]
        self.assertEquals(res, expected)

    def test_disconnect(self):
        self.robot.disconnect()
        res = self.robot.is_connected()
        self.assertEquals(bool(res), False)

    def test_get_connected_port(self):
        res = self.robot.get_connected_port()
        self.assertEquals(res, self.robot.VIRTUAL_SMOOTHIE_PORT)

    def test_robot_move_to(self):
        self.robot.move_to((Deck(), (100, 0, 0)))
        self.robot.run()
        position = self.robot._driver.get_head_position()['current']
        self.assertEqual(position, (100, 0, 0))

    def test_move_head(self):
        self.robot.move_head(x=100, y=0, z=20)
        current = self.robot._driver.get_head_position()['current']
        self.assertEquals(current, (100, 0, 20))

    def test_home(self):

        self.robot.disconnect()
        self.robot.connect()

        self.assertDictEqual(self.robot.axis_homed, {
            'x': False, 'y': False, 'z': False, 'a': False, 'b': False
        })

        self.robot.clear_commands()
        self.robot.home('xa', enqueue=True)
        self.assertDictEqual(self.robot.axis_homed, {
            'x': False, 'y': False, 'z': False, 'a': False, 'b': False
        })
        self.assertEquals(len(self.robot._commands), 1)
        self.robot.run()
        self.assertDictEqual(self.robot.axis_homed, {
            'x': True, 'y': False, 'z': False, 'a': True, 'b': False
        })

        self.robot.clear_commands()
        self.robot.home(enqueue=False)
        self.assertEquals(len(self.robot._commands), 0)

        self.assertDictEqual(self.robot.axis_homed, {
            'x': True, 'y': True, 'z': True, 'a': True, 'b': True
        })

    def test_robot_pause_and_resume(self):
        self.robot.move_to((Deck(), (100, 0, 0)), enqueue=True)
        self.robot.move_to((Deck(), (101, 0, 0)), enqueue=True)
        self.assertEqual(len(self.robot._commands), 2)

        self.robot.pause()

        def _run():
            self.robot.run()

        thread = threading.Thread(target=_run)
        thread.start()
        self.robot.resume()
        thread.join(0.5)

        self.assertEquals(thread.is_alive(), False)
        self.assertEqual(len(self.robot._commands), 2)

        self.robot.clear_commands()
        self.assertEqual(len(self.robot._commands), 0)

        self.robot.move_to((Deck(), (100, 0, 0)), enqueue=True)
        self.robot.move_to((Deck(), (101, 0, 0)), enqueue=True)

        def _run():
            self.robot.run()

        self.robot.pause()

        thread = threading.Thread(target=_run)
        thread.start()
        thread.join(0.01)

        self.assertEquals(thread.is_alive(), True)
        self.assertEqual(len(self.robot._commands) > 0, True)

        self.robot.resume()

        thread.join(1)
        self.assertEqual(len(self.robot._commands), 2)

    def test_versions(self):
        res = self.robot.versions()
        expected = {
            'config': {
                'version': 'v1.2.0',
                'compatible': True
            },
            'firmware': {
                'version': 'v1.0.5',
                'compatible': True
            },
            'ot_version': {
                'version': 'one_pro',
                'compatible': True
            }
        }
        self.assertDictEqual(res, expected)

    def test_diagnostics(self):
        res = self.robot.diagnostics()
        expected = {
            'axis_homed': {
                'x': True, 'y': True, 'z': True, 'a': True, 'b': True
            },
            'switches': {
                'x': False,
                'y': False,
                'z': False,
                'a': False,
                'b': False
            },
            'steps_per_mm': {
                'x': 80.0,
                'y': 80.0
            }
        }
        self.assertDictEqual(res, expected)

        self.robot.disconnect()
        self.robot.connect()
        self.assertRaises(RuntimeWarning, self.robot.move_head, x=-199)
        res = self.robot.diagnostics()
        expected = {
            'axis_homed': {
                'x': False, 'y': False, 'z': False, 'a': False, 'b': False
            },
            'switches': {
                'x': True,
                'y': False,
                'z': False,
                'a': False,
                'b': False
            },
            'steps_per_mm': {
                'x': 80.0,
                'y': 80.0
            }
        }
        self.assertDictEqual(res, expected)

        self.robot.home('x', enqueue=False)
        res = self.robot.diagnostics()
        expected = {
            'axis_homed': {
                'x': True, 'y': False, 'z': False, 'a': False, 'b': False
            },
            'switches': {
                'x': False,
                'y': False,
                'z': False,
                'a': False,
                'b': False
            },
            'steps_per_mm': {
                'x': 80.0,
                'y': 80.0
            }
        }
        self.assertDictEqual(res, expected)

    def test_get_motor_caching(self):
        a_motor = self.robot.get_motor('a')
        self.assertEqual(a_motor, self.robot.get_motor('a'))

        b_motor = self.robot.get_motor('b')
        self.assertEqual(b_motor, self.robot.get_motor('b'))

    def test_get_mosfet_caching(self):
        m0 = self.robot.get_mosfet(0)
        self.assertEqual(m0, self.robot.get_mosfet(0))

        m1 = self.robot.get_mosfet(1)
        self.assertEqual(m1, self.robot.get_mosfet(1))

    def test_send_to_app_with_unconfigured_robot(self):
        self.robot.send_to_app()

    def test_send_to_app_with_configured_robot(self):
        plate = containers.load('96-flat', 'A1')
        p200 = instruments.Pipette(axis='b', max_volume=200)

        for well in plate:
            p200.aspirate(well).delay(5).dispense(well)

        self.robot.send_to_app()
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest

from Bluebird import *

import re
import os
from time import sleep
from subprocess import Popen

def parse_proc_status(pid, field):
    proc_pid_path = '/proc/{}/status'.format(pid)
    with open(proc_pid_path) as f:
        status_raw = f.read()
    status_field = re.findall('{}:\t(.+)\n'.format(field), status_raw)
    return int(status_field[0])

class BlueBirdTest(unittest.TestCase):

    def setUp(self):
        self.test_proc_filename = 'alt_print.txt'
        self.stdout = open(self.test_proc_filename, 'x')
        self.test_proc = Popen('./alt_print', stdout=self.stdout)
        self.test_proc_pid = self.test_proc.pid
        self.bluebird = Bluebird(self.test_proc_pid)
        self.bluebird.start()
        sleep(1)

    def tearDown(self):
        if self.test_proc.stdout is not None:
            self.test_proc.stdout.close()
        else:
            self.stdout.close()
        self.test_proc.kill()
        os.unlink(self.test_proc_filename)

    def test_attach(self):
        tracer_pid = parse_proc_status(self.test_proc_pid, 'TracerPid')
        self.assertEqual(test_pid, tracer_pid)

    def test_writestring(self):
        # XXX using address from objdump -s alt_print
        # find a way to universally calculate address reading the binary
        test_proc_addr = 0x400764
        test_proc_word = 'Potatoe'
        test_proc_output = 'Process <{}> is running!'.format(self.test_proc_pid)
        test_proc_newoutput = '{} <{}> is running!'.format(test_proc_word,
                                                           self.test_proc_pid)
        self.bluebird.write(test_proc_addr, test_proc_word)
        sleep(2)
        with open(self.test_proc_filename) as test_file:
            proc_output = test_file.read()
        proc_output_lines = list(filter(None, proc_output.split('\n')))
        before_write = proc_output_lines[0]
        after_write = proc_output_lines[-1]
        self.assertEqual(after_write, test_proc_newoutput)
        self.assertNotEqual(after_write, test_proc_output)

    def test_readstring(self):
        # XXX using address from objdump -s alt_print
        # find a way to universally calculate address reading the binary
        test_proc_addr = 0x400764
        test_proc_word = 'Process'
        word = self.bluebird.read(test_proc_addr, 1)
        self.assertEqual(test_proc_word, word)

    def test_get_syscall(self):
        syscall = self.bluebird.get_current_call()
        self.assertIn(syscall, test_proc_syscalls)

    def test_get_syscalls(self):
        test_syscalls = self.bluebird.get_ranged_syscalls(4)
        calls = test_proc_syscalls * 2
        self.assertCountEqual(test_syscalls, calls)

    def test_find_syscall(self):
        getsid = 124
        test_find = self.bluebird.get_call(getsid, non_blocking=True)
        while self.bluebird.tracing:
            sleep(1)
        self.assertIsNone(test_find)

    def test_find_syscall_timeout(self):
        foo_syscall = 404
        test_find = self.bluebird.get_call(foo_syscall, timeout=5)
        self.assertIsNone(test_find)

    def test_bbrk(self):
        self.bluebird.get_heap()
        limit_before = self.bluebird.heap_bounds[1]
        brk_inc_size = 0xffff
        self.bluebird.expand_heap(brk_inc_size)
        sleep(1)
        limit_after = self.bluebird.heap_bounds[1]
        self.assertEqual(limit_before + brk_inc_size + 1, limit_after)

    def test_bmmap_anon(self):
        self.bluebird.get_heap()
        self.bluebird.create_mmap(0, PAGESIZE, PROT_EXEC | PROT_WRITE,
                MAP_ANONYMOUS | MAP_SHARED, 0)
        self.bluebird.get_maps()
        self.assertIsNotNone(self.bluebird.maps.get('(deleted)'))

    def test_bmmap_file(self):
        self.bluebird.get_heap()
        self.bluebird.create_mmap(0, PAGESIZE, PROT_EXEC | PROT_WRITE,
                MAP_ANONYMOUS | MAP_SHARED, 0, path='/tmp/bluebird')
        self.bluebird.get_maps()
        sleep(1)
        self.assertIsNotNone(self.bluebird.maps.get('(deleted)'))

    def test_get_trace_dir(self):
        curr_dir = os.getcwd()
        self.bluebird.get_heap()
        self.assertEqual(curr_dir, self.bluebird.get_trace_dir())

    def test_detach(self):
        tracer_pid = parse_proc_status(self.test_proc_pid, 'TracerPid')
        self.assertEqual(test_pid, tracer_pid)
        self.bluebird.stop()
        sleep(1)
        tracer_pid = parse_proc_status(self.test_proc_pid, 'TracerPid')
        self.assertEqual(0, tracer_pid)

if __name__ == '__main__':
    # XXX these syscalls are defined in /usr/include/asm/unistd_64.h
    # rewrite to allow compatibility for 32 too.
    test_pid = os.getpid()
    test_proc_syscalls = (1, 35)
    unittest.main(verbosity=3)
<commit_msg>replace old function name<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest

from Bluebird import *

import re
import os
from time import sleep
from subprocess import Popen

def parse_proc_status(pid, field):
    proc_pid_path = '/proc/{}/status'.format(pid)
    with open(proc_pid_path) as f:
        status_raw = f.read()
    status_field = re.findall('{}:\t(.+)\n'.format(field), status_raw)
    return int(status_field[0])

class BlueBirdTest(unittest.TestCase):

    def setUp(self):
        self.test_proc_filename = 'alt_print.txt'
        self.stdout = open(self.test_proc_filename, 'x')
        self.test_proc = Popen('./alt_print', stdout=self.stdout)
        self.test_proc_pid = self.test_proc.pid
        self.bluebird = Bluebird(self.test_proc_pid)
        self.bluebird.start()
        sleep(1)

    def tearDown(self):
        if self.test_proc.stdout is not None:
            self.test_proc.stdout.close()
        else:
            self.stdout.close()
        self.test_proc.kill()
        os.unlink(self.test_proc_filename)

    def test_attach(self):
        tracer_pid = parse_proc_status(self.test_proc_pid, 'TracerPid')
        self.assertEqual(test_pid, tracer_pid)

    def test_writestring(self):
        # XXX using address from objdump -s alt_print
        # find a way to universally calculate address reading the binary
        test_proc_addr = 0x400764
        test_proc_word = 'Potatoe'
        test_proc_output = 'Process <{}> is running!'.format(self.test_proc_pid)
        test_proc_newoutput = '{} <{}> is running!'.format(test_proc_word,
                                                           self.test_proc_pid)
        self.bluebird.write(test_proc_addr, test_proc_word)
        sleep(2)
        with open(self.test_proc_filename) as test_file:
            proc_output = test_file.read()
        proc_output_lines = list(filter(None, proc_output.split('\n')))
        before_write = proc_output_lines[0]
        after_write = proc_output_lines[-1]
        self.assertEqual(after_write, test_proc_newoutput)
        self.assertNotEqual(after_write, test_proc_output)

    def test_readstring(self):
        # XXX using address from objdump -s alt_print
        # find a way to universally calculate address reading the binary
        test_proc_addr = 0x400764
        test_proc_word = 'Process'
        word = self.bluebird.read(test_proc_addr, 1)
        self.assertEqual(test_proc_word, word)

    def test_get_syscall(self):
        syscall = self.bluebird.get_current_call()
        self.assertIn(syscall, test_proc_syscalls)

    def test_get_syscalls(self):
        test_syscalls = self.bluebird.get_ranged_syscalls(4)
        calls = test_proc_syscalls * 2
        self.assertCountEqual(test_syscalls, calls)

    def test_find_syscall(self):
        getsid = 124
        test_find = self.bluebird.find_call(getsid, non_blocking=True)
        while self.bluebird.tracing:
            sleep(1)
        self.assertIsNone(test_find)

    def test_find_syscall_timeout(self):
        foo_syscall = 404
        test_find = self.bluebird.find_call(foo_syscall, timeout=5)
        self.assertIsNone(test_find)

    def test_bbrk(self):
        self.bluebird.get_heap()
        limit_before = self.bluebird.heap_bounds[1]
        brk_inc_size = 0xffff
        self.bluebird.expand_heap(brk_inc_size)
        sleep(1)
        limit_after = self.bluebird.heap_bounds[1]
        self.assertEqual(limit_before + brk_inc_size + 1, limit_after)

    def test_bmmap_anon(self):
        self.bluebird.get_heap()
        self.bluebird.create_mmap(0, PAGESIZE, PROT_EXEC | PROT_WRITE,
                MAP_ANONYMOUS | MAP_SHARED, 0)
        self.bluebird.get_maps()
        self.assertIsNotNone(self.bluebird.maps.get('(deleted)'))

    def test_bmmap_file(self):
        self.bluebird.get_heap()
        self.bluebird.create_mmap(0, PAGESIZE, PROT_EXEC | PROT_WRITE,
                MAP_ANONYMOUS | MAP_SHARED, 0, path='/tmp/bluebird')
        self.bluebird.get_maps()
        sleep(1)
        self.assertIsNotNone(self.bluebird.maps.get('(deleted)'))

    def test_get_trace_dir(self):
        curr_dir = os.getcwd()
        self.bluebird.get_heap()
        self.assertEqual(curr_dir, self.bluebird.get_trace_dir())

    def test_detach(self):
        tracer_pid = parse_proc_status(self.test_proc_pid, 'TracerPid')
        self.assertEqual(test_pid, tracer_pid)
        self.bluebird.stop()
        sleep(1)
        tracer_pid = parse_proc_status(self.test_proc_pid, 'TracerPid')
        self.assertEqual(0, tracer_pid)

if __name__ == '__main__':
    # XXX these syscalls are defined in /usr/include/asm/unistd_64.h
    # rewrite to allow compatibility for 32 too.
    test_pid = os.getpid()
    test_proc_syscalls = (1, 35)
    unittest.main(verbosity=3)
<|endoftext|>


<commit_before>""" Full system test suite. """

from math import floor
import shutil
from pathlib import Path

from difflib import unified_diff
import numpy as np
import pytest
import openmc
from openmc.data import JOULE_PER_EV
import openmc.deplete

from tests.regression_tests import config
from example_geometry import generate_problem

@pytest.fixture(scope="module")
def problem():
    n_rings = 2
    n_wedges = 4

    # Load geometry from example
    return generate_problem(n_rings, n_wedges)

@pytest.mark.parametrize("multiproc", [True, False])
def test_full(run_in_tmpdir, problem, multiproc):
    """Full system test suite.

    Runs an entire OpenMC simulation with depletion coupling and verifies
    that the outputs match a reference file.  Sensitive to changes in
    OpenMC.

    This test runs a complete OpenMC simulation and tests the outputs.
    It will take a while.

    """

    geometry, lower_left, upper_right = problem

    # OpenMC-specific settings
    settings = openmc.Settings()
    settings.particles = 100
    settings.batches = 10
    settings.inactive = 0
    space = openmc.stats.Box(lower_left, upper_right)
    settings.source = openmc.Source(space=space)
    settings.seed = 1
    settings.verbosity = 1

    # Create operator
    chain_file = Path(__file__).parents[2] / 'chain_simple.xml'
    op = openmc.deplete.Operator(geometry, settings, chain_file)
    op.round_number = True

    # Power and timesteps
    dt1 = 15.*24*60*60  # 15 days
    dt2 = 1.5*30*24*60*60  # 1.5 months
    N = floor(dt2/dt1)
    dt = np.full(N, dt1)
    power = 2.337e15*4*JOULE_PER_EV*1e6  # MeV/second cm from CASMO

    # Perform simulation using the predictor algorithm
    openmc.deplete.pool.USE_MULTIPROCESSING = multiproc
    openmc.deplete.PredictorIntegrator(op, dt, power).integrate()

    # Get path to test and reference results
    path_test = op.output_dir / 'depletion_results.h5'
    path_reference = Path(__file__).with_name('test_reference.h5')

    # If updating results, do so and return
    if config['update']:
        shutil.copyfile(str(path_test), str(path_reference))
        return

    # Load the reference/test results
    res_test = openmc.deplete.ResultsList.from_hdf5(path_test)
    res_ref = openmc.deplete.ResultsList.from_hdf5(path_reference)

    # Assert same mats
    for mat in res_ref[0].mat_to_ind:
        assert mat in res_test[0].mat_to_ind, \
            "Material {} not in new results.".format(mat)
    for nuc in res_ref[0].nuc_to_ind:
        assert nuc in res_test[0].nuc_to_ind, \
            "Nuclide {} not in new results.".format(nuc)

    for mat in res_test[0].mat_to_ind:
        assert mat in res_ref[0].mat_to_ind, \
            "Material {} not in old results.".format(mat)
    for nuc in res_test[0].nuc_to_ind:
        assert nuc in res_ref[0].nuc_to_ind, \
            "Nuclide {} not in old results.".format(nuc)

    tol = 1.0e-6
    for mat in res_test[0].mat_to_ind:
        for nuc in res_test[0].nuc_to_ind:
            _, y_test = res_test.get_atoms(mat, nuc)
            _, y_old = res_ref.get_atoms(mat, nuc)

            # Test each point
            correct = True
            for i, ref in enumerate(y_old):
                if ref != y_test[i]:
                    if ref != 0.0:
                        correct = np.abs(y_test[i] - ref) / ref <= tol
                    else:
                        correct = False

            assert correct, "Discrepancy in mat {} and nuc {}\n{}\n{}".format(
                mat, nuc, y_old, y_test)

    # Compare statepoint files with depletion results

    t_test, k_test = res_test.get_eigenvalue()
    t_ref, k_ref = res_ref.get_eigenvalue()
    k_state = np.empty_like(k_ref)

    n_tallies = np.empty(N + 1, dtype=int)

    # Get statepoint files for all BOS points and EOL
    for n in range(N + 1):
        statepoint = openmc.StatePoint("openmc_simulation_n{}.h5".format(n))
        k_n = statepoint.k_combined
        k_state[n] = [k_n.nominal_value, k_n.std_dev]
        n_tallies[n] = len(statepoint.tallies)
    # Look for exact match pulling from statepoint and depletion_results
    assert np.all(k_state == k_test)
    assert np.allclose(k_test, k_ref)

    # Check that no additional tallies are loaded from the files
    assert np.all(n_tallies == 0)

def test_depletion_results_to_material(run_in_tmpdir, problem):
    """Checks openmc.Materials objects can be created from depletion results"""
    # Load the reference/test results
    path_reference = Path(__file__).with_name('test_reference.h5')
    res_ref = openmc.deplete.ResultsList.from_hdf5(path_reference)

    # Firstly need to export materials.xml file for the initial simulation state
    geometry, lower_left, upper_right = problem
    materials = openmc.Materials()
    for mat in geometry.root_universe.get_all_materials().values():
        materials.append(mat)
    materials.export_to_xml()

    # Export last step of depletion to its own openmc.Materials object,
    # using only nuclides available in the current nuclear data library
    last_step_materials = res_ref.export_to_materials(-1)

    # Check that the conversion of the final step depleted materials XML
    # file hashes to what we expect.
    output_xml_file = 'last_step_materials.xml'
    last_step_materials.export_to_xml(path=output_xml_file)
    with open(output_xml_file, 'r') as result_file:
        result_file_lines = result_file.readlines()

    # If updating results, do so and return. We write out the last-step
    # depleted materials as an XML, hash the file, and save the hash to
    # the reference file.
    reference_file = Path(__file__).with_name('last_step_reference_materials.xml')
    if config['update']:
        with open(reference_file, 'w') as ref_file:
            ref_file.writelines(result_file_lines)
        return

    # Check text of final depletion point material XML matches reference
    with open(reference_file) as ref_file:
        reference_lines = ref_file.readlines()
    diff_vs_expected = unified_diff(reference_lines, result_file_lines)

    # Check all lines match, printing along the way
    success = True
    for line in diff_vs_expected:
        if line:
            success = False
            print(line)
    assert success
<commit_msg>remove unnecessary newline<commit_after>""" Full system test suite. """

from math import floor
import shutil
from pathlib import Path

from difflib import unified_diff
import numpy as np
import pytest
import openmc
from openmc.data import JOULE_PER_EV
import openmc.deplete

from tests.regression_tests import config
from example_geometry import generate_problem

@pytest.fixture(scope="module")
def problem():
    n_rings = 2
    n_wedges = 4

    # Load geometry from example
    return generate_problem(n_rings, n_wedges)

@pytest.mark.parametrize("multiproc", [True, False])
def test_full(run_in_tmpdir, problem, multiproc):
    """Full system test suite.

    Runs an entire OpenMC simulation with depletion coupling and verifies
    that the outputs match a reference file.  Sensitive to changes in
    OpenMC.

    This test runs a complete OpenMC simulation and tests the outputs.
    It will take a while.

    """

    geometry, lower_left, upper_right = problem

    # OpenMC-specific settings
    settings = openmc.Settings()
    settings.particles = 100
    settings.batches = 10
    settings.inactive = 0
    space = openmc.stats.Box(lower_left, upper_right)
    settings.source = openmc.Source(space=space)
    settings.seed = 1
    settings.verbosity = 1

    # Create operator
    chain_file = Path(__file__).parents[2] / 'chain_simple.xml'
    op = openmc.deplete.Operator(geometry, settings, chain_file)
    op.round_number = True

    # Power and timesteps
    dt1 = 15.*24*60*60  # 15 days
    dt2 = 1.5*30*24*60*60  # 1.5 months
    N = floor(dt2/dt1)
    dt = np.full(N, dt1)
    power = 2.337e15*4*JOULE_PER_EV*1e6  # MeV/second cm from CASMO

    # Perform simulation using the predictor algorithm
    openmc.deplete.pool.USE_MULTIPROCESSING = multiproc
    openmc.deplete.PredictorIntegrator(op, dt, power).integrate()

    # Get path to test and reference results
    path_test = op.output_dir / 'depletion_results.h5'
    path_reference = Path(__file__).with_name('test_reference.h5')

    # If updating results, do so and return
    if config['update']:
        shutil.copyfile(str(path_test), str(path_reference))
        return

    # Load the reference/test results
    res_test = openmc.deplete.ResultsList.from_hdf5(path_test)
    res_ref = openmc.deplete.ResultsList.from_hdf5(path_reference)

    # Assert same mats
    for mat in res_ref[0].mat_to_ind:
        assert mat in res_test[0].mat_to_ind, \
            "Material {} not in new results.".format(mat)
    for nuc in res_ref[0].nuc_to_ind:
        assert nuc in res_test[0].nuc_to_ind, \
            "Nuclide {} not in new results.".format(nuc)

    for mat in res_test[0].mat_to_ind:
        assert mat in res_ref[0].mat_to_ind, \
            "Material {} not in old results.".format(mat)
    for nuc in res_test[0].nuc_to_ind:
        assert nuc in res_ref[0].nuc_to_ind, \
            "Nuclide {} not in old results.".format(nuc)

    tol = 1.0e-6
    for mat in res_test[0].mat_to_ind:
        for nuc in res_test[0].nuc_to_ind:
            _, y_test = res_test.get_atoms(mat, nuc)
            _, y_old = res_ref.get_atoms(mat, nuc)

            # Test each point
            correct = True
            for i, ref in enumerate(y_old):
                if ref != y_test[i]:
                    if ref != 0.0:
                        correct = np.abs(y_test[i] - ref) / ref <= tol
                    else:
                        correct = False

            assert correct, "Discrepancy in mat {} and nuc {}\n{}\n{}".format(
                mat, nuc, y_old, y_test)

    # Compare statepoint files with depletion results

    t_test, k_test = res_test.get_eigenvalue()
    t_ref, k_ref = res_ref.get_eigenvalue()
    k_state = np.empty_like(k_ref)

    n_tallies = np.empty(N + 1, dtype=int)

    # Get statepoint files for all BOS points and EOL
    for n in range(N + 1):
        statepoint = openmc.StatePoint("openmc_simulation_n{}.h5".format(n))
        k_n = statepoint.k_combined
        k_state[n] = [k_n.nominal_value, k_n.std_dev]
        n_tallies[n] = len(statepoint.tallies)
    # Look for exact match pulling from statepoint and depletion_results
    assert np.all(k_state == k_test)
    assert np.allclose(k_test, k_ref)

    # Check that no additional tallies are loaded from the files
    assert np.all(n_tallies == 0)

def test_depletion_results_to_material(run_in_tmpdir, problem):
    """Checks openmc.Materials objects can be created from depletion results"""
    # Load the reference/test results
    path_reference = Path(__file__).with_name('test_reference.h5')
    res_ref = openmc.deplete.ResultsList.from_hdf5(path_reference)

    # Firstly need to export materials.xml file for the initial simulation state
    geometry, lower_left, upper_right = problem
    materials = openmc.Materials()
    for mat in geometry.root_universe.get_all_materials().values():
        materials.append(mat)
    materials.export_to_xml()

    # Export last step of depletion to its own openmc.Materials object,
    # using only nuclides available in the current nuclear data library
    last_step_materials = res_ref.export_to_materials(-1)

    # Check that the conversion of the final step depleted materials XML
    # file hashes to what we expect.
    output_xml_file = 'last_step_materials.xml'
    last_step_materials.export_to_xml(path=output_xml_file)
    with open(output_xml_file, 'r') as result_file:
        result_file_lines = result_file.readlines()

    # If updating results, do so and return. We write out the last-step
    # depleted materials as an XML, hash the file, and save the hash to
    # the reference file.
    reference_file = Path(__file__).with_name('last_step_reference_materials.xml')
    if config['update']:
        with open(reference_file, 'w') as ref_file:
            ref_file.writelines(result_file_lines)
        return

    # Check text of final depletion point material XML matches reference
    with open(reference_file) as ref_file:
        reference_lines = ref_file.readlines()
    diff_vs_expected = unified_diff(reference_lines, result_file_lines)

    # Check all lines match, printing along the way
    success = True
    for line in diff_vs_expected:
        if line:
            success = False
            print(line.rstrip())
    assert success
<|endoftext|>


<commit_before>import logging

class ConcurrentScheduler:

    def __init__(self, toProcess, numProcesses):
        self.numProcesses = numProcesses
        self.jobsUnprocessed = toProcess
        self.jobsProcessing = []
        self.jobsComplete = []

    def processJobs(self):
        print "In process jobs."

        return self.jobsComplete
<commit_msg>Finished concurrent scheduler.<commit_after>import logging
import time
import psutil

class ConcurrentScheduler:

    # Number of seconds to wait after spawning processes before
    # querying PID list.
    __CHECK_DELAY = 2

    def __init__(self, toProcess, numProcesses):
        self.numProcesses = numProcesses
        self.jobsUnprocessed = toProcess
        self.jobsProcessing = []
        self.jobsComplete = []
        logging.info("Concurrent Scheduler instantiated. Contains %d jobs. Number of concurrent processes: %d." % (len(self.jobsUnprocessed), self.numProcesses))

    def processJobs(self):
        logging.info("Concurrent scheduler beginning jobs.")
        self.__jobLoop()
        return self.jobsComplete

    def __jobLoop(self):
        while True:

            for processing in self.jobsProcessing:
                print "Waiting on job with PID %d" % processing.pid

            if len(self.jobsUnprocessed) == 0 and len(self.jobsProcessing) == 0:
                logging.info("All jobs processed. Breaking out of job loop.")
                return

            while len(self.jobsProcessing) < self.numProcesses and len(self.jobsUnprocessed) > 0:
                logging.info("Spawning an additional job. Number of active jobs before is %d." % len(self.jobsProcessing))
                toRun = self.jobsUnprocessed.pop()
                self.jobsProcessing.append(toRun)
                toRun.startJob()

            time.sleep(self.__CHECK_DELAY)

            self.__checkProcesses()

    def __checkProcesses(self):
        completed = []

        for activeProc in self.jobsProcessing:
            proc = psutil.Process(activeProc.pid)
            if proc.status() == psutil.STATUS_ZOMBIE:
                logging.info("Process with ID %d is now a zombie process. Mark it as complete." % activeProc.pid)
                completed.append(activeProc)

        for completeProc in completed:
            self.jobsProcessing.remove(completeProc)
            self.jobsComplete.append(completeProc)
<|endoftext|>


<commit_before>#!/usr/bin/env python

import re

def reduce_region(lines):
  out = []
  take = False
  for line in lines:
    if not take:
      if re.match("^ *TRIGGER .*$", line):
        take = True
        out += [line]
    elif take:
      if re.match("^Mode:.*$", line) or re.match("^ *EVENT LOOP.*$", line):
        take = False
      else:
        out += [line]
  return out

def group_triggers(lines):
  out = []
  group = []
  for line in lines:
    if re.match("^ *TRIGGER .*$", line):
      if group != []:
        out += [group]
      group = [line]
    else:
      group += [line]
  if group != []:
    out += [group]
  return out

# Take a group of lines representing a trigger and convert them to proper output
def lines_of_trig(trig):
  mobj =  re.match(r'^TRIGGER (.+) (.+) {', trig[0])
  if mobj:
    name, addr = mobj.group(1), mobj.group(2)
    if name and addr:
      mobj = re.match(r'^Args: (\(.*\))$', trig[1])
      args = mobj.group(1)
      if args:
        pairs = [("args", args)]
        for l in trig[2:]:
          mobj = re.match(r'^(.*) => (.*)$', l)
          if mobj:
            pairs.append((mobj.group(1), mobj.group(2)))
        # convert pairs to lines
        out = ['/'.join([addr, name, pair[0], pair[1]]) for pair in pairs]
        return out

# clean a line by removing initial whitespace, \n, long whitespace
def clean(line):
  line = line.replace('\n','')
  line = re.sub(r'\s+', ' ', line)
  line = re.sub(r'^ ', '', line)
  return line

def main():
  with open("results.txt", "r") as f:
    if f:
      lines = f.readlines()
      lines = [clean(l) for l in lines]
      lines = reduce_region(lines)
      trigs = group_triggers(lines)
      trigs = [lines_of_trig(t) for t in trigs]
      out = []
      for t in trigs:
        out += t
      out = '\n'.join(out)
      print(out)

if __name__ == '__main__':
  main()

<commit_msg>Fixed up sanitize_log for multi-line values<commit_after>#!/usr/bin/env python

import re

def reduce_region(lines):
  out = []
  take = False
  for line in lines:
    if not take:
      if re.match("^ *TRIGGER .*$", line):
        take = True
        out += [line]
    elif take:
      if re.match("^Mode:.*$", line) or re.match("^ *EVENT LOOP.*$", line):
        take = False
      else:
        out += [line]
  return out

def group_triggers(lines):
  out = []
  group = []
  for line in lines:
    if re.match("^ *TRIGGER .*$", line):
      if group != []:
        out += [group]
      group = [line]
    else:
      group += [line]
  if group != []:
    out += [group]
  return out

# Take a group of lines representing a trigger and convert them to proper output
def lines_of_trig(trig):
  mobj =  re.match(r'^TRIGGER (.+) (.+) {', trig[0])
  if mobj:
    name, addr = mobj.group(1), mobj.group(2)
    if name and addr:
      pairs = []
      lastval = None
      lastkey = None
      for i, line in enumerate(trig):
        if i == 1:
          mobj = re.match(r'^(Args): (.*)$', trig[1])
        else:
          mobj = re.match(r'^(.*) => (.*)$', line)
        if mobj:
          if lastkey and lastval:
            pairs.append((lastkey, lastval))
          lastkey = mobj.group(1)
          lastval = mobj.group(2)
        else: # maybe a continued line?
          mobj = re.match(r'^.. (.*)$', line)
          if mobj:
            # grow our value
            if lastkey and lastval:
              lastval += mobj.group(1)
            else:
              raise ValueError("Continued line without first line: \n" + line)

      # last members if we missed them
      if lastkey and lastval:
        pairs.append((lastkey, lastval))

      # convert pairs to lines
      out = ['/'.join([addr, name, pair[0], pair[1]]) for pair in pairs]
      return out

# clean a line by removing initial whitespace, \n, long whitespace
def clean(line):
  line = line.replace('\n','')
  line = re.sub(r'\s+', ' ', line)
  line = re.sub(r'^ ', '', line)
  return line

def main():
  with open("results.txt", "r") as f:
    if f:
      lines = f.readlines()
      lines = [clean(l) for l in lines]
      lines = reduce_region(lines)
      trigs = group_triggers(lines)
      trigs = [lines_of_trig(t) for t in trigs]
      out = []
      for t in trigs:
        out += t
      out = '\n'.join(out)
      print(out)

if __name__ == '__main__':
  main()

<|endoftext|>


<commit_before># encoding: utf-8
r"""
Module contains routines implementing call back functions needed for a single
time step.

*before_step* - Checks for negative depths, sets the wind, and calculates kappa
                and checks against the Richardson tolerance.

*friction_source* - Implements Manning's-N type friction source term
"""

import numpy as np

import pyclaw.solution as solution
from aux import set_no_wind,kappa_index

class NegativeDepthError(Exception):
    r"""Error raised when depth becomes negative in a layer"""
    def __init__(self,layer,location):
        self.layer = layer
        self.location = location
        msg = "Negative depth found in layer %s at %s" % (layer,location)
        super(NegativeDepthError,self).__init__(msg)

class RichardsonExceededError(Exception):
    r"""Error raised when the Richardson tolerance has been exceeded"""

    def __init__(self,indices,solution):
        self.indices = indices
        self.solution = solution
        msg = "Richardson tolerance exceeded at indices %s" % indices
        super(RichardsonExceededError,self).__init__(msg)

def before_step(solver,state,wind_func=set_no_wind,dry_tolerance=1e-3,
                    richardson_tolerance=0.95,raise_on_negative=False,
                    raise_on_richardson=False):
    r"""
    Sets data fields and performs calculations needed before a time
    step is taken.

    :Input:
     - *solver* (:class:pyclaw.solver.Solver)
     - *solution* (:class:pyclaw.solution.Solution)
     - *wind_func* (func)
     - *dry_tolerance* (float)
     - *richardson_tolerance* (float)
     - *raise_on_negative* (bool)
     - *raise_on_richardson* (bool)

    :Output:

    :Raises:
      - (Exception) - Richardson tolerance exceeded.  Only raised if
        raise_on_fail is set to True.
    """

    # Extract relevant data
    num_layers = state.problem_data['num_layers']
    rho = state.problem_data['rho']
    g = state.problem_data['g']
    one_minus_r = state.problem_data['one_minus_r']
    x = state.grid.dimensions[0].centers

    # State arrays
    q = state.q
    aux = state.aux

    # Zero out negative values
    for layer in xrange(num_layers):
        m = num_layers * layer
        negative_indices = (q[m,:] < 0.0).nonzero()[0]
        q[m,negative_indices] = 0.0
        q[m+1,negative_indices] = 0.0

        if raise_on_negative:
            if len(negative_indices) < 0:
                locations = x[negative_indices]
                raise NegativeDepthError(layer,locations)

    # Set wind field
    wind_func(state)

    # Calculate kappa
    h = np.zeros((num_layers,q.shape[1]))
    u = np.zeros(h.shape)
    for layer in xrange(num_layers):
        layer_index = 2*layer
        h[layer,:] = state.q[layer_index,:] / rho[layer]
        wet_index = h[layer,:] > dry_tolerance
        u[layer,wet_index] = state.q[layer_index+1,wet_index] / state.q[layer_index,wet_index]
    aux[kappa_index,:] = (u[0,:] - u[1,:])**2 / (g * one_minus_r * (h[0,:] + h[1,:]))
    if np.any(aux[kappa_index,wet_index] > richardson_tolerance):
        # Actually calculate where the indices failed
        bad_indices = (aux[kappa_index,wet_index] > richardson_tolerance).nonzero()[0]
        if raise_on_richardson:
            state.aux = aux
            raise RichardsonExceededError(bad_indices,state)
        else:
            print "Hyperbolicity may have failed at the following points:"
            for i in bad_indices:
                print "\tkappa(%s) = %s" % (i,aux[kappa_index,i])

def friction_source(solver,state,dt,TOLERANCE=1e-30):
    r""""""
    manning = state.problem_data['manning']
    g = state.problem_data['g']
    rho = state.problem_data['rho']
    dry_tolerance = state.problem_data['dry_tolerance']

    if manning > TOLERANCE:
        for i in xrange(state.q.shape[1]):
            h = state.q[2,i] / rho[1]
            if h < dry_tolerance:
                h = state.q[0,i] / rho[0]
                u = state.q[1,i] / rho[0]
                layer_index = 0
            else:
                u = state.q[2,i] / rho[1]
                layer_index = 1

            gamma = u * g * manning**2 / h**(4/3)
            dgamma = 1.0 + dt * gamma
            hu_index = 2 * (layer_index) + 1
            state.q[hu_index,i] = state.q[hu_index,i] / dgamma * rho[layer_index]<commit_msg>Bug fix for sloped shelf test case and support for SharpClaw.<commit_after># encoding: utf-8
r"""
Module contains routines implementing call back functions needed for a single
time step.

*before_step* - Checks for negative depths, sets the wind, and calculates kappa
                and checks against the Richardson tolerance.

*friction_source* - Implements Manning's-N type friction source term
"""

import numpy as np

from aux import set_no_wind,kappa_index

class NegativeDepthError(Exception):
    r"""Error raised when depth becomes negative in a layer"""
    def __init__(self,layer,location):
        self.layer = layer
        self.location = location
        msg = "Negative depth found in layer %s at %s" % (layer,location)
        super(NegativeDepthError,self).__init__(msg)

class RichardsonExceededError(Exception):
    r"""Error raised when the Richardson tolerance has been exceeded"""

    def __init__(self,indices,solution):
        self.indices = indices
        self.solution = solution
        msg = "Richardson tolerance exceeded at indices %s" % indices
        super(RichardsonExceededError,self).__init__(msg)

def before_step(solver,state,wind_func=set_no_wind,dry_tolerance=1e-3,
                    richardson_tolerance=0.95,raise_on_negative=False,
                    raise_on_richardson=False):
    r"""
    Sets data fields and performs calculations needed before a time
    step is taken.

    :Input:
     - *solver* (:class:pyclaw.solver.Solver)
     - *solution* (:class:pyclaw.solution.Solution)
     - *wind_func* (func)
     - *dry_tolerance* (float)
     - *richardson_tolerance* (float)
     - *raise_on_negative* (bool)
     - *raise_on_richardson* (bool)

    :Output:

    :Raises:
      - (Exception) - Richardson tolerance exceeded.  Only raised if
        raise_on_fail is set to True.
    """

    # Extract relevant data
    num_layers = state.problem_data['num_layers']
    rho = state.problem_data['rho']
    g = state.problem_data['g']
    one_minus_r = state.problem_data['one_minus_r']
    x = state.grid.dimensions[0].centers

    # State arrays
    q = state.q
    aux = state.aux

    # Zero out negative values
    for layer in xrange(num_layers):
        m = num_layers * layer
        negative_indices = (q[m,:] < 0.0).nonzero()[0]
        q[m,negative_indices] = 0.0
        q[m+1,negative_indices] = 0.0

        if raise_on_negative:
            if len(negative_indices) < 0:
                locations = x[negative_indices]
                raise NegativeDepthError(layer,locations)

    # Set wind field
    wind_func(state)

    # Calculate kappa
    h = np.zeros((num_layers,q.shape[1]))
    u = np.zeros(h.shape)
    for layer in xrange(num_layers):
        layer_index = 2*layer
        h[layer,:] = state.q[layer_index,:] / rho[layer]
        wet_index = h[layer,:] > dry_tolerance
        u[layer,wet_index] = state.q[layer_index+1,wet_index] / state.q[layer_index,wet_index]
    aux[kappa_index,:] = (u[0,:] - u[1,:])**2 / (g * one_minus_r * (h[0,:] + h[1,:]))
    if np.any(aux[kappa_index,wet_index] > richardson_tolerance):
        # Actually calculate where the indices failed
        bad_indices = (aux[kappa_index,wet_index] > richardson_tolerance).nonzero()[0]
        if raise_on_richardson:
            state.aux = aux
            raise RichardsonExceededError(bad_indices,state)
        else:
            print "Hyperbolicity may have failed at the following points:"
            for i in bad_indices:
                print "\tkappa(%s) = %s" % (i,aux[kappa_index,i])

def friction_source(solver,state,dt,TOLERANCE=1e-30):
    r""""""

    if state.problem_data['manning'] != 0.0:
        if isinstance(solver, ClawSolver):
            manning = state.problem_data['manning']
            g = state.problem_data['g']
            rho = state.problem_data['rho']
            dry_tolerance = state.problem_data['dry_tolerance']

            if manning > TOLERANCE:
                for i in xrange(state.q.shape[1]):
                    h = state.q[2,i] / rho[1]
                    if h < dry_tolerance:
                        h = state.q[0,i] / rho[0]
                        u = state.q[1,i] / rho[0]
                        layer_index = 0
                    else:
                        u = state.q[2,i] / rho[1]
                        layer_index = 1

                    gamma = u * g * manning**2 / h**(4/3)
                    dgamma = 1.0 + dt * gamma
                    hu_index = 2 * (layer_index) + 1
                    state.q[hu_index,i] = state.q[hu_index,i] / dgamma * rho[layer_index]
        elif isinstance(solver, SharpClawSolver):
            pass
        else:
            raise ValueError("Solver type %s not supported." % type(solver))
<|endoftext|>


<commit_before>from unittest import TestCase

import numpy as np
import numpy.testing as npt

from nimble import Events

class TestAsArrayMethod(TestCase):
    def setUp(self):
        conditional_array = np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1])
        condition = (conditional_array > 0)
        self.events = Events(condition)

    def test_default_parameters(self):
        """Test as_array() with default settings"""
        validation_array = np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1])
        npt.assert_array_equal(validation_array, self.events.as_array())

    def test_as_array_false_value(self):
        """Test as_array() with low value"""
        validation_array = np.array([-1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1])
        npt.assert_array_equal(validation_array, self.events.as_array(
            false_values=-1))

    def test_as_array_true_value(self):
        """Test as_array() with high value"""
        validation_array = np.array([0, 5, 5, 5, 0, 0, 0, 5, 5, 0, 5, 5])
        npt.assert_array_equal(validation_array, self. events.as_array(
            true_values=5))

    def test_as_array_false_and_true_value(self):
        """Test as_array() with low and high values"""
        validation_array = np.array([-1, 5, 5, 5, -1, -1, -1, 5, 5, -1, 5, 5])
        npt.assert_array_equal(validation_array, self.events.as_array(
            false_values=-1,
            true_values=5))

class TestEventDetection(TestCase):
    def test_default_parameters(self):
        """Test event detection with only a supplied condition"""
        np.random.seed(10)
        validation_array = np.random.random_integers(0, 1, 100)
        condition = (validation_array > 0)
        events = Events(condition)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_no_events_found(self):
        """Test arrays that have no active events"""
        conditional_array = np.ones(10, dtype='i1')
        validation_array = np.zeros(10, dtype='i1')
        condition = (conditional_array > 5)
        events = Events(condition)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_event_always_active(self):
        """Test arrays that has an event active throughout entire array"""
        validation_array = np.ones(10, dtype='i1')
        condition = (validation_array > 0)
        events = Events(condition)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_array_with_event_active_at_start(self):
        """Test arrays that have events active at the start"""
        validation_array = np.zeros(10, dtype='i1')
        validation_array[:1] = 1
        condition = (validation_array > 0)

        events = Events(condition)
        npt.assert_array_equal(validation_array, events.as_array())

    def test_array_with_event_active_at_end(self):
        """Test arrays that have events active at the end"""
        validation_array = np.zeros(10, dtype='i1')
        validation_array[-1:] = 1
        condition = (validation_array > 0)

        events = Events(condition)
        npt.assert_array_equal(validation_array, events.as_array())

    def test_multi_input_condition_event(self):
        """Test arrays that have multi-input conditions"""
        x = np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 0])
        y = np.array([0, 0, 1, 1, 1, 0, 0, 1, 0, 1])

        validation_array = np.array([0, 0, 1, 1, 0, 0, 0, 1, 0, 0])
        condition = ((x > 0) & (y > 0))

        events = Events(condition)
        npt.assert_array_equal(validation_array, events.as_array())

class TestEventDebounce(TestCase):
    def setUp(self):
        conditional_array = np.array([0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1])
        self.condition = (conditional_array > 0)

    def test_event_entry_debounce(self):
        validation_array = np.array([0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0])
        events = Events(self.condition, entry_debounce=2)
        npt.assert_array_equal(validation_array, events.as_array())

    def test_event_exit_debounce(self):
        validation_array = np.array([0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1])
        events = Events(self.condition, exit_debounce=2)
        npt.assert_array_equal(validation_array, events.as_array())

    def test_entry_and_exit_debounce(self):
        validation_array = np.array([0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1])
        events = Events(self.condition, entry_debounce=2, exit_debounce=2)
        npt.assert_array_equal(validation_array, events.as_array())

class TestEventLengthFilter(TestCase):
    def setUp(self):
        condition_array = np.array([0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1])
        self.condition = (condition_array > 0)

    def test_min_event_window_length(self):
        validation_array = np.array([0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0])
        events = Events(self.condition, min_event_length=2)
        npt.assert_array_equal(validation_array, events.as_array())

    def test_max_event_window_length(self):
        validation_array = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1])
        events = Events(self.condition, max_event_length=3)
        npt.assert_array_equal(validation_array, events.as_array())

    def test_max_and_min_event_window_length(self):
        validation_array = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0])
        events = Events(self.condition, min_event_length=2, max_event_length=3)
        npt.assert_array_equal(validation_array, events.as_array())

class TestSampleRates(TestCase):
    def setUp(self):
        condition_array = np.array([1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1,
                                    0, 0, 0, 1, 0, 0])
        self.condition = (condition_array > 0)

    def test_entry_and_exit_debounce(self):
        validation_array = np.array([0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
                                     0, 0, 0, 0, 0, 0])

        events = Events(self.condition, sample_rate=3,
                        entry_debounce=0.5, exit_debounce=1)
        npt.assert_array_equal(validation_array, events.as_array())

    def test_max_and_min_event_window_length(self):
        validation_array = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
                                     0, 0, 0, 0, 0, 0])
        events = Events(self.condition, sample_rate=3,
                        min_event_length=0.5, max_event_length=1)
        npt.assert_array_equal(validation_array, events.as_array())<commit_msg>Add start and stop offset integration tests<commit_after>from unittest import TestCase

import numpy as np
import numpy.testing as npt

from nimble import Events

class TestAsArrayMethod(TestCase):
    def setUp(self):
        conditional_array = np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1])
        condition = (conditional_array > 0)
        self.events = Events(condition)

    def test_default_parameters(self):
        """Test as_array() with default settings"""
        validation_array = np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1])
        npt.assert_array_equal(validation_array, self.events.as_array())

    def test_as_array_false_value(self):
        """Test as_array() with low value"""
        validation_array = np.array([-1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1])
        npt.assert_array_equal(validation_array, self.events.as_array(
            false_values=-1))

    def test_as_array_true_value(self):
        """Test as_array() with high value"""
        validation_array = np.array([0, 5, 5, 5, 0, 0, 0, 5, 5, 0, 5, 5])
        npt.assert_array_equal(validation_array, self. events.as_array(
            true_values=5))

    def test_as_array_false_and_true_value(self):
        """Test as_array() with low and high values"""
        validation_array = np.array([-1, 5, 5, 5, -1, -1, -1, 5, 5, -1, 5, 5])
        npt.assert_array_equal(validation_array, self.events.as_array(
            false_values=-1,
            true_values=5))

class TestEventDetection(TestCase):
    def test_default_parameters(self):
        """Test event detection with only a supplied condition"""
        np.random.seed(10)
        validation_array = np.random.random_integers(0, 1, 100)
        condition = (validation_array > 0)
        events = Events(condition)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_no_events_found(self):
        """Test arrays that have no active events"""
        conditional_array = np.ones(10, dtype='i1')
        validation_array = np.zeros(10, dtype='i1')
        condition = (conditional_array > 5)
        events = Events(condition)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_event_always_active(self):
        """Test arrays that has an event active throughout entire array"""
        validation_array = np.ones(10, dtype='i1')
        condition = (validation_array > 0)
        events = Events(condition)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_array_with_event_active_at_start(self):
        """Test arrays that have events active at the start"""
        validation_array = np.zeros(10, dtype='i1')
        validation_array[:1] = 1
        condition = (validation_array > 0)
        events = Events(condition)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_array_with_event_active_at_end(self):
        """Test arrays that have events active at the end"""
        validation_array = np.zeros(10, dtype='i1')
        validation_array[-1:] = 1
        condition = (validation_array > 0)
        events = Events(condition)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_multi_input_condition_event(self):
        """Test arrays that have multi-input conditions"""
        x = np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 0])
        y = np.array([0, 0, 1, 1, 1, 0, 0, 1, 0, 1])

        validation_array = np.array([0, 0, 1, 1, 0, 0, 0, 1, 0, 0])
        condition = ((x > 0) & (y > 0))
        events = Events(condition)

        npt.assert_array_equal(validation_array, events.as_array())

class TestEventDebounce(TestCase):
    def setUp(self):
        conditional_array = np.array([0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1])
        self.condition = (conditional_array > 0)

    def test_event_entry_debounce(self):
        validation_array = np.array([0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0])
        events = Events(self.condition, entry_debounce=2)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_event_exit_debounce(self):
        validation_array = np.array([0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1])
        events = Events(self.condition, exit_debounce=2)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_entry_and_exit_debounce(self):
        validation_array = np.array([0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1])
        events = Events(self.condition, entry_debounce=2, exit_debounce=2)

        npt.assert_array_equal(validation_array, events.as_array())

class TestEventLengthFilter(TestCase):
    def setUp(self):
        condition_array = np.array([0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1])
        self.condition = (condition_array > 0)

    def test_min_event_window_length(self):
        validation_array = np.array([0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0])
        events = Events(self.condition, min_event_length=2)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_max_event_window_length(self):
        validation_array = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1])
        events = Events(self.condition, max_event_length=3)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_max_and_min_event_window_length(self):
        validation_array = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0])
        events = Events(self.condition, min_event_length=2, max_event_length=3)

        npt.assert_array_equal(validation_array, events.as_array())

class TestEventOffsets(TestCase):
    def setUp(self):
        condition_array = np.array([1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1])
        self.condition = (condition_array > 0)

    def test_start_index_offset(self):
        validation_array = np.array([1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1])
        validation_starts_index = np.array([0, 2, 7, 11])
        events = Events(self.condition, start_offset=-1)

        npt.assert_array_equal(validation_array, events.as_array())
        npt.assert_array_equal(validation_starts_index, events.starts)

    def test_stop_index_offset(self):
        validation_array = np.array([1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1])
        validation_stops_index = np.array([2, 7, 11, 13])
        events = Events(self.condition, stop_offset=1)

        npt.assert_array_equal(validation_array, events.as_array())
        npt.assert_array_equal(validation_stops_index, events.stops)

    def test_start_and_stop_index_offset(self):
        validation_array = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
        validation_starts_index = np.array([0, 2, 7, 11])
        validation_stops_index = np.array([2, 7, 11, 13])
        events = Events(self.condition, start_offset=-1, stop_offset=1)

        npt.assert_array_equal(validation_array, events.as_array())
        npt.assert_array_equal(validation_stops_index, events.stops)
        npt.assert_array_equal(validation_starts_index, events.starts)

class TestSampleRates(TestCase):
    def setUp(self):
        condition_array = np.array([1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1,
                                    0, 0, 0, 1, 0, 0])
        self.condition = (condition_array > 0)

    def test_entry_and_exit_debounce(self):
        validation_array = np.array([0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
                                     0, 0, 0, 0, 0, 0])

        events = Events(self.condition, sample_rate=3,
                        entry_debounce=0.5, exit_debounce=1)

        npt.assert_array_equal(validation_array, events.as_array())

    def test_max_and_min_event_window_length(self):
        validation_array = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0,
                                     0, 0, 0, 0, 0, 0])
        events = Events(self.condition, sample_rate=3,
                        min_event_length=0.5, max_event_length=1)

        npt.assert_array_equal(validation_array, events.as_array())
<|endoftext|>