import unittest

import numpy

import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition


@testing.parameterize(*testing.product({
    'shape': [(3, 4), ()],
}))
class TestHardSigmoid(unittest.TestCase):

    shape = (3, 4)

    def setUp(self):
        self.x = numpy.random.uniform(-1, 1, self.shape).astype(numpy.float32)
        self.g = numpy.random.uniform(-1, 1, self.shape).astype(numpy.float32)

    def check_forward(self, x_data):
        x = chainer.Variable(x_data)
        y = functions.hard_sigmoid(x)
        self.assertIs(y.data.dtype, x_data.dtype)
        expect = numpy.minimum(1.0, numpy.maximum(0.0, self.x * 0.2 + 0.5))
        gradient_check.assert_allclose(y.data, expect)

    @condition.retry(3)
    def test_forward_cpu(self):
        self.check_forward(self.x)

    @attr.gpu
    @condition.retry(3)
    def test_forward_gpu(self):
        self.check_forward(cuda.to_gpu(self.x))

    def check_backward(self, x_data, grad):
        gradient_check.check_backward(
            functions.HardSigmoid(), x_data, grad)

    @condition.retry(3)
    def test_backward_cpu(self):
        self.check_backward(self.x, self.g)

    @attr.gpu
    @condition.retry(3)
    def test_backward_gpu(self):
        self.check_backward(cuda.to_gpu(self.x),
                            cuda.to_gpu(self.g))


testing.run_module(__name__, __file__)

@@ -298,16 +298,75 @@
 ), ()%5D,%0A
+    'dtype': %5Bnumpy.float16, numpy.float32, numpy.float64%5D%0A
 %7D))%0Aclas
@@ -509,29 +509,26 @@
 .astype(
-numpy.float32
+self.dtype
 )%0A      
@@ -589,22 +589,308 @@
 ype(
-numpy.float32)
+self.dtype)%0A%0A        self.check_forward_option = %7B%7D%0A        self.check_backward_option = %7B%7D%0A        if self.dtype is numpy.float16:%0A            self.check_forward_option = %7B'atol': 1e-3, 'rtol': 1e-3%7D%0A            self.check_backward_option = %5C%0A                %7B'eps': 0.1, 'atol': 1e-3, 'rtol': 1e-3%7D
 %0A%0A  
@@ -1164,16 +1164,29 @@
 llclose(
+%0A            
 y.data, 
@@ -1191,16 +1191,45 @@
 , expect
+, **self.check_forward_option
 )%0A%0A    @
@@ -1517,16 +1517,16 @@
 ckward(%0A
-
         
@@ -1566,16 +1566,58 @@
 ta, grad
+,%0A            **self.check_backward_option
 )%0A%0A    @

Test all floating point types