File: Generators.hs

package info (click to toggle)
haskell-cborg 0.2.10.0-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 808 kB
  • sloc: haskell: 8,273; ansic: 14; makefile: 3
file content (261 lines) | stat: -rw-r--r-- 8,124 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
{-# LANGUAGE CPP                        #-}
{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE TypeFamilies               #-}
{-# LANGUAGE DeriveFunctor              #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Tests.Reference.Generators (
    -- * Integer with a large range
    LargeInteger(..)

    -- * Floats with NaNs
  , FloatNaN(..)
  , canonicaliseNaN

    -- * Floats with special values
  , HalfSpecials(..)
  , FloatSpecials(..)
  , DoubleSpecials(..)

    -- * Floating types to bit representation conversion
  , halfToWord
  , floatToWord
  , doubleToWord
  , wordToHalf
  , wordToFloat
  , wordToDouble
  ) where

import           Data.Word
import           Numeric (showHex)
import           Numeric.Half as Half
import           GHC.Float (float2Double)
import           Data.Proxy

import           Foreign
import           System.IO.Unsafe
import           System.Random (Random)

import           Test.QuickCheck

#if !MIN_VERSION_base(4,8,0)
import           Control.Applicative
#endif

-- | QuickCheck generator for large integers
--
newtype LargeInteger = LargeInteger { getLargeInteger :: Integer }
  deriving (Show, Eq)

instance Arbitrary LargeInteger where
  arbitrary =
    sized $ \n ->
      oneof $ take (1 + n `div` 10)
        [ LargeInteger .          fromIntegral <$> (arbitrary :: Gen Int8)
        , LargeInteger .          fromIntegral <$> choose (minBound, maxBound :: Int64)
        , LargeInteger . bigger . fromIntegral <$> choose (minBound, maxBound :: Int64)
        ]
    where
      bigger n = n * abs n

----------------------------------------
-- Float <-> Integral conversions
--

wordToHalf :: Word16 -> Half
wordToHalf = Half.Half . fromIntegral

wordToFloat :: Word32 -> Float
wordToFloat = toFloat

wordToDouble :: Word64 -> Double
wordToDouble = toFloat

toFloat :: (Storable word, Storable float) => word -> float
toFloat w =
    unsafeDupablePerformIO $ alloca $ \buf -> do
      poke (castPtr buf) w
      peek buf

halfToWord :: Half -> Word16
halfToWord (Half.Half w) = fromIntegral w

floatToWord :: Float -> Word32
floatToWord = fromFloat

doubleToWord :: Double -> Word64
doubleToWord = fromFloat

fromFloat :: (Storable word, Storable float) => float -> word
fromFloat float =
    unsafeDupablePerformIO $ alloca $ \buf -> do
            poke (castPtr buf) float
            peek buf

---------------------------------------------------
-- Floats with NaNs
--

class RealFloat n => FloatNaN n where
  canonicalNaN :: n

canonicaliseNaN :: FloatNaN n => n -> n
canonicaliseNaN n | isNaN n   = canonicalNaN
                  | otherwise = n

instance FloatNaN Half where
  canonicalNaN = Half 0x7e00

instance FloatNaN Float where
  canonicalNaN = Half.fromHalf canonicalNaN

instance FloatNaN Double where
  canonicalNaN = float2Double canonicalNaN


---------------------------------------------------
-- Generators for float types with special values
--

instance Arbitrary Half where
  arbitrary = getHalfSpecials <$> arbitrary
  shrink    = shrinkRealFrac

newtype HalfSpecials   = HalfSpecials   { getHalfSpecials   :: Half }
  deriving (Ord, Num, Fractional, RealFrac, Real, Floating, RealFloat, FloatNaN)

newtype FloatSpecials  = FloatSpecials  { getFloatSpecials  :: Float }
  deriving (Ord, Num, Fractional, RealFrac, Real, Floating, RealFloat, FloatNaN)

newtype DoubleSpecials = DoubleSpecials { getDoubleSpecials :: Double }
  deriving (Ord, Num, Fractional, RealFrac, Real, Floating, RealFloat, FloatNaN)

instance Eq HalfSpecials where
  HalfSpecials a == HalfSpecials b = halfToWord a == halfToWord b

instance Eq FloatSpecials where
  FloatSpecials a == FloatSpecials b = floatToWord a == floatToWord b

instance Eq DoubleSpecials where
  DoubleSpecials a == DoubleSpecials b = doubleToWord a == doubleToWord b

instance Show HalfSpecials where
  showsPrec p (HalfSpecials n)
    | isNaN n   = showString "NaN{-0x" . showHex (halfToWord n) . showString "-}"
    | otherwise = showsPrec p n

instance Show FloatSpecials where
  showsPrec p (FloatSpecials n)
    | isNaN n   = showString "NaN{-0x" . showHex (floatToWord n) . showString "-}"
    | otherwise = showsPrec p n

instance Show DoubleSpecials where
  showsPrec p (DoubleSpecials n)
    | isNaN n   = showString "NaN{-0x" . showHex (doubleToWord n) . showString "-}"
    | otherwise = showsPrec p n

instance Arbitrary HalfSpecials where
  arbitrary = HalfSpecials <$> frequency [ (2, arbitraryFloating)
                                         , (1, arbitraryFloatSpecials) ]
  shrink (HalfSpecials n) = [ HalfSpecials n' | n' <- shrinkRealFrac n ]

instance Arbitrary FloatSpecials where
  arbitrary = FloatSpecials <$> frequency [ (2, arbitraryFloating)
                                          , (1, arbitraryFloatSpecials) ]
  shrink (FloatSpecials n) = [ FloatSpecials n' | n' <- shrinkRealFrac n ]

instance Arbitrary DoubleSpecials where
  arbitrary = DoubleSpecials <$> frequency [ (2, arbitraryFloating)
                                           , (1, arbitraryFloatSpecials) ]
  shrink (DoubleSpecials n) = [ DoubleSpecials n' | n' <- shrinkRealFrac n ]


-- | Generate a float from a uniformly random bit pattern
--
arbitraryFloating :: forall n. RealFloatIEEE n => Gen n
arbitraryFloating = wordToFloating <$> arbitraryBoundedIntegral

-- | Generate float special values, see 'IeeeSpecials',
--
-- In particular we generate more than a single NaN bit pattern so that we can
-- test non-canonical representations. The other special values have a single
-- bit pattern.
--
arbitraryFloatSpecials :: forall n. (RealFloatIEEE n, Random (FloatWord n))
                       => Gen n
arbitraryFloatSpecials =
    frequency
      [ (1, pure (wordToFloating positiveInfinity))
      , (1, pure (wordToFloating negativeInfinity))
      , (1, pure (wordToFloating negativeZero))
      , (3, wordToFloating <$> choose nanRange)
      ]
  where
    IeeeSpecials {..} = floatIeeeSpecials (Proxy :: Proxy n)

-- | Special values for IEEE float types, including negative 0,
-- positive and negative infinity and a range of NaN values.
--
data IeeeSpecials n = IeeeSpecials {
       positiveInfinity :: n,
       negativeInfinity :: n,
       negativeZero     :: n,
       nanRange         :: (n, n)
     }
  deriving (Eq, Functor, Show)

-- | The 'IeeeSpecials' values for 'RealFloatIEEE' types (i.e. 'Half', 'Float'
-- and 'Double').
--
-- To make sense of the bit-twiddling here, see
--
-- <https://en.wikipedia.org/wiki/Single-precision_floating-point_format>
-- <https://en.wikipedia.org/wiki/Half-precision_floating-point_format>
-- <https://en.wikipedia.org/wiki/Double-precision_floating-point_format>
--
floatIeeeSpecials :: RealFloatIEEE n => Proxy n -> IeeeSpecials (FloatWord n)
floatIeeeSpecials p =
    IeeeSpecials {..}
  where
    positiveInfinity = (setBit 0 (exponentBits p)    - 1)
                       `shiftL` significandBits p
    negativeInfinity = (setBit 0 (exponentBits p +1) - 1)
                       `shiftL` significandBits p
    negativeZero     =  setBit 0 (exponentBits p + significandBits p)
    nanRange         = (positiveInfinity, negativeZero - 1)

class (RealFloat n, Integral (FloatWord n), Show (FloatWord n),
       Bounded (FloatWord n), Bits (FloatWord n))
   => RealFloatIEEE n where
  exponentBits    :: Proxy n -> Int
  significandBits :: Proxy n -> Int

  type FloatWord n :: *
  wordToFloating  :: FloatWord n -> n
--floatingToWord  :: n -> FloatWord n

instance RealFloatIEEE Half where
  exponentBits    _ = 5
  significandBits _ = 10

  type FloatWord Half = Word16
  wordToFloating      = wordToHalf
--floatingToWord      = halfToWord

instance RealFloatIEEE Float where
  exponentBits    _ = 8
  significandBits _ = 23

  type FloatWord Float = Word32
  wordToFloating       = wordToFloat
--floatingToWord       = floatToWord

instance RealFloatIEEE Double where
  exponentBits    _ = 11
  significandBits _ = 52

  type FloatWord Double = Word64
  wordToFloating        = wordToDouble
--floatingToWord        = doubleToWord