-
Notifications
You must be signed in to change notification settings - Fork 0
/
X.hs
766 lines (663 loc) · 32.7 KB
/
X.hs
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
{-# language RecordWildCards
, TypeFamilies
, BlockArguments
, TypeApplications
, ScopedTypeVariables
, DeriveGeneric
, FlexibleInstances
, FlexibleContexts
#-}
{-# options_ghc -fdefer-typed-holes #-}
module Main where
import Control.Monad
import Data.Function (on)
import Data.Foldable (null, toList)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map, (!))
import qualified Data.Map as Map
import Data.Matrix (Matrix, matrix)
import qualified Data.Matrix as Matrix
import qualified Data.List as List
import Data.Tuple (swap)
import Test.Tasty.QuickCheck hiding (classify)
import Test.Tasty.HUnit
import qualified Test.Tasty.QuickCheck as QuickCheck
import Test.Tasty
import Data.Proxy
import Control.DeepSeq
import GHC.Generics (Generic)
import Willem
inverseLookup :: Eq v => Map k v -> v -> [k]
inverseLookup m v = fmap snd . filter ((== v) . fst) . fmap swap . Map.assocs $ m
classify :: Ord a => Set a -> Set (Set a)
classify = classifyBy (==)
classifyBy :: Ord a => (a -> a -> Bool) -> Set a -> Set (Set a)
classifyBy eq = Set.fromList . Map.elems . List.foldl' f Map.empty . Set.toList
where
f m x = case List.find (`eq` x) (Map.keys m) of
Just k -> Map.insertWith Set.union k (Set.singleton x) m
Nothing -> Map.insert x (Set.singleton x) m
normalize :: Ord a => Set (Interval a) -> Set (Interval a)
normalize u | Set.null u = Set.empty
| otherwise = let rel = closure (relation u joins)
classes = classifyBy (curry (rel ?)) u
in Set.map (bounds . flatten) classes
normalizeList :: Ord a => [Interval a] -> [Interval a]
normalizeList = Set.toList . normalize . Set.fromList
flatten :: Ord a => Set (Interval a) -> Set a
flatten = let deconstruct (Interval x y) = Set.fromList [x, y]
deconstruct (Point x) = Set.singleton x
in Set.unions . Set.map deconstruct
bounds :: Ord a => Set a -> Interval a
bounds xs = interval (Set.findMin xs) (Set.findMax xs)
data Relation a = Relation { table :: Matrix Binary, indices :: Map Int a } -- Invariant: square.
deriving Eq
instance Show a => Show (Relation a) where
show = show . table
blank :: Ord a => Set a -> Relation a
blank set = relation set ((const.const) False)
complete :: Ord a => Set a -> Relation a
complete set = relation set ((const.const) True)
equality :: Ord a => Set a -> Relation a
equality set = (blank set) { table = Matrix.diagonalList (Set.size set) No (repeat Yes) }
elementwise :: Eq a => (Binary -> Binary -> Binary) -> Relation a -> Relation a -> Relation a
elementwise f u v
| indices u /= indices v = error "Elementwise only works on relations over the same set."
| otherwise = Relation { table = Matrix.elementwise f (table u) (table v), indices = indices u }
relation :: Ord a => Set a -> (a -> a -> Bool) -> Relation a
relation u f = Relation{..} where
n = Set.size u
table = matrix n n (\(i, j) -> fromBool $ (indices ! i) `f` (indices ! j))
indices = Map.fromDistinctAscList $ zip [1..] (Set.toAscList u)
(?) :: Eq a => Relation a -> (a, a) -> Bool
Relation{..} ? (x, y) = let { [i] = inverseLookup indices x ; [j] = inverseLookup indices y }
in toBool $ Matrix.getElem i j table
isEmpty :: Relation a -> Bool
isEmpty = null . indices
randomIndex :: Relation a -> Gen a
randomIndex = oneof . fmap return . Map.elems . indices
isReflexive, isSymmetric, isAntisymmetric, isTransitive, isTotal
:: (Eq a, Show a) => Relation a -> Property
isReflexive r = if isEmpty r then property True else
forAll (randomIndex r) \x ->
r ? (x, x) == True
isSymmetric r = if isEmpty r then property True else
forAll (randomIndex r) \x ->
forAll (randomIndex r) \y ->
r ? (x, y) == r ? (y, x)
isAntisymmetric r = if isEmpty r then property True else
forAll (randomIndex r) \x ->
forAll (randomIndex r) \y ->
if r ? (x, y) && r ? (y, x) && x /= y then False else True
isTransitive r = if isEmpty r then property True else
forAll (randomIndex r) \x ->
forAll (randomIndex r) \y ->
forAll (randomIndex r) \z ->
r ? (x, y) && r ? (y, z) ==> r ? (x, z)
isTotal r = if isEmpty r then property True else
forAll (randomIndex r) \x ->
forAll (randomIndex r) \y ->
r ? (x, y) || r ? (y, x)
data Binary = No | Yes deriving (Eq, Ord, Bounded, Enum)
fromBool :: Bool -> Binary
fromBool True = Yes
fromBool False = No
toBool :: Binary -> Bool
toBool Yes = True
toBool No = False
instance Show Binary where
show Yes = "#"
show No = "."
instance Num Binary where
No + Yes = Yes
Yes + No = Yes
_ + _ = No
Yes * Yes = Yes
_ * _ = No
negate = id
abs = id
signum = id
fromInteger = fromBool . odd
instance Arbitrary Binary where
arbitrary = arbitraryBoundedEnum
reflexiveClosure :: Relation a -> Relation a
reflexiveClosure Relation{..} = Relation{ table = Matrix.elementwise (+*) table d, ..}
where d = Matrix.diagonalList (Map.size indices) No (repeat Yes)
symmetricClosure :: Relation a -> Relation a
symmetricClosure Relation{..} = Relation{ table = Matrix.elementwise (+*) table t, ..}
where t = Matrix.transpose table
transitiveClosure :: Relation a -> Relation a
transitiveClosure Relation{..} = Relation { table = f table, .. }
where f = last . converge . scanl1 g . repeat
g' x y = Matrix.elementwise (+) x (x `Matrix.multStd` y)
g = throughInteger g'
throughInteger :: (Matrix Integer -> Matrix Integer -> Matrix Integer)
-> Matrix Binary -> Matrix Binary -> Matrix Binary
throughInteger h x y = fmap (toEnum . fromInteger . signum) $ h (fmap convert x) (fmap convert y)
convert = (fromIntegral :: Int -> Integer) . fromEnum
closure :: Relation a -> Relation a
closure = transitiveClosure . symmetricClosure . reflexiveClosure
converge :: Eq a => [a] -> [a]
converge = convergeBy (==)
convergeBy :: (a -> a -> Bool) -> [a] -> [a]
convergeBy _ [ ] = [ ]
convergeBy _ [x] = [x]
convergeBy eq (x: xs@(y: _))
| x `eq` y = [x]
| otherwise = x : convergeBy eq xs
data Interval a = Interval a a -- Invariant: ordered.
| Point a
deriving (Eq, Ord, Show, Generic)
instance NFData a => NFData (Interval a)
instance Arbitrary (Interval Int) where
arbitrary = do
x <- arbitrary @(Interval Float)
return case x of
Point y -> Point (floor y)
Interval y z -> interval (floor y) (floor z)
instance {-# overlappable #-} (Arbitrary a, Fractional a, Ord a) => Arbitrary (Interval a) where
arbitrary = do
d6 <- fmap (`mod` 6) (arbitrary @Int)
if d6 == 0
then do
spread <- scale (* 5) arbitrary
return $ point (spread + 100)
else do
size <- arbitrary
spread <- scale (* 5) arbitrary
return $ interval (spread - size / 2) (spread + size / 2 + 100)
shrink (Point 0) = [ ]
shrink (Interval 0 0) = [ ]
shrink i = resizeTo0 i
where
nudge x | abs x < abs (signum x) = 0
| otherwise = x - signum x
resizeTo0 (Interval x y)
| abs x > abs y = [ interval (nudge x) y ]
| abs x < abs y = [ interval x (nudge y) ]
| abs x == abs y = [ interval x (nudge y)
, interval (nudge x) y
, interval (nudge x) (nudge y) ]
| otherwise = error "resizeTo0: Error: Interval is a pair without relation!"
resizeTo0 (Point x) = [ point (nudge x) ]
interval :: Ord a => a -> a -> Interval a
interval x y | x == y = Point x
| x < y = Interval x y
| x > y = Interval y x
| otherwise = error "interval: Error: Order on the underlying type is not total!"
(~~) :: Ord a => a -> a -> Interval a
(~~) = interval
point :: Ord a => a -> Interval a
point = Point
left, right :: Interval a -> a
left (Interval x _) = x
left (Point x) = x
right (Interval _ y) = y
right (Point y) = y
isWithin :: Ord a => a -> Interval a -> Bool
y `isWithin` (Interval x z) = x <= y && y <= z
y `isWithin` (Point x) = x == y
isWithinOneOf :: Ord a => a -> Set (Interval a) -> Bool
x `isWithinOneOf` s = or . Set.map (x `isWithin`) $ s
countWithin :: Ord a => Set (Interval a) -> a -> Int
countWithin s x = sum . fmap (fromEnum . (x `isWithin`)) . Set.toList $ s
displayIntervals :: forall a. (RealFrac a, Eq a)
=> Set (Interval a) -> String
displayIntervals xs =
let (Interval leftBound rightBound) = (bounds . flatten) xs
leftBound' = floor leftBound
rightBound' = floor rightBound
displayOne :: Interval a -> String
displayOne (Interval x y) =
let x' = floor x
y' = floor y
in replicate (x' - leftBound') '.'
++ (if x' == y' then "*" else "*" ++ replicate (y' - x' - 1) '-' ++ "*")
++ replicate (rightBound' - y') '.' ++ pure '\n'
displayOne (Point x) =
let x' = floor x
in replicate (x' - leftBound') '.'
++ "*"
++ replicate (rightBound' - x') '.' ++ pure '\n'
in concatMap displayOne xs
instance Num Bool where
(+) = (/=)
(*) = (&&)
negate = id
abs = id
signum = id
fromInteger = toEnum . fromInteger
-- instance {-# overlappable #-} Num (Interval a -> Bool) where
-- p + q = \i -> p i /= q i
-- p * q = \i -> p i && q i
-- negate = id
-- abs = id
-- signum = id
-- fromInteger = error "`fromInteger` is not defined for the ring of functions."
instance Num b => Num (Interval a -> b) where
p + q = \i -> p i + q i
p * q = \i -> p i * q i
negate = id
abs = id
signum = id
fromInteger = error "`fromInteger` is not defined for the ring of functions."
instance CoArbitrary a => CoArbitrary (Interval a)
instance (Show a, Ord a, Num a, Enum a) => Show (Interval a -> Interval a -> Bool) where
show p = let xs = Set.fromList [ interval i (i + 3) | i <- [1, 3.. 7] ]
in show (relation xs p)
instance (Ord a, Num a, Enum a) => Eq (Interval a -> Interval a -> Bool) where
p == q = let xs = Set.fromList [ interval i (i + 3) | i <- [1, 3.. 7] ]
in relation xs p == relation xs q
infixl 8 +*
(+*) :: Num a => a -> a -> a
x +* y = x + y + (x * y)
precedes, meets, overlaps, isFinishedBy, contains, starts
:: Ord a => Interval a -> Interval a -> Bool
precedes = \ i j -> right i < left j
meets = \ i j -> right i == left j && left i /= left j && right i /= right j
overlaps = \ i j -> left i < left j && right i < right j && right i > left j
isFinishedBy = \ i j -> left i < left j && right i == right j
contains = \ i j -> left i < left j && right i > right j
starts = \ i j -> left i == left j && right i < right j
absorbs, isDisjointWith, joins, touches, isRightwardsOf
:: Ord a => Interval a -> Interval a -> Bool
absorbs = isFinishedBy +* contains +* flip starts +* (==)
isDisjointWith = precedes +* flip precedes
joins = (fmap . fmap) not isDisjointWith
touches = meets +* overlaps
isRightwardsOf = flip (precedes +* touches)
subsume :: Ord a => Set (Interval a) -> Interval a -> Bool
xs `subsume` x = any (`absorbs` x) (normalize xs)
coveringChains
:: forall a. (Ord a, Num a)
=> Interval a -> [Interval a] -> [[Interval a]]
coveringChains base intervals = coveringChains' base intervals initial
where
initial = interval ((\z -> z - 1) . left . bounds . flatten . Set.fromList $ intervals) (left base)
coveringChains'
:: forall a. (Ord a, Num a)
=> Interval a -> [Interval a] -> Interval a -> [[Interval a]]
coveringChains' base intervals initial = nonRecursive ++ recursive
where
nonRecursive :: [[Interval a]]
nonRecursive = do
x <- filter ((initial `touches`) +* (initial `isFinishedBy`)) intervals
if x `absorbs` base then return (pure x) else fail ""
recursive :: [[Interval a]]
recursive = do
x <- filter (\y -> (y `overlaps` base || y `starts` base) && initial `touches` y) intervals
xs <- coveringChains'
(interval (right x) (right base))
((filter (`isRightwardsOf` x)) intervals)
(interval (right initial) (right x))
return $ x: xs
coveringMinimalChains :: forall a. (Ord a, Num a)
=> Interval a -> [Interval a] -> [[Interval a]]
coveringMinimalChains x = List.nub . fmap minimizeChain . coveringChains x
chainsFromTo :: Ord a => Interval a -> Interval a -> [Interval a] -> [[Interval a]]
chainsFromTo start end xs' = case base of
Point _ -> (fmap pure . filter (`absorbs` base)) xs'
_ -> baseCase ++ recursiveCase
where
base = right start ~~ left end
xs = filter (not . isDisjointWith base) xs'
baseCase = do
x <- filter ((start `touches`) * (`touches` end)) xs
return [x]
recursiveCase = do
x <- filter ((start `touches`) * not . (`touches` end)) xs
xs <- chainsFromTo (right start ~~ right x) end (filter (`isRightwardsOf` x) xs)
return $ x: xs
coveringChainsFromTo :: forall a. (Ord a, Num a)
=> Interval a -> [Interval a] -> [[Interval a]]
coveringChainsFromTo _ [ ] = [ ]
coveringChainsFromTo base xs = chainsFromTo start end xs
where
start = (\z -> z - 1) (left reach) ~~ left base
end = right base ~~ (\z -> z + 1) (right reach)
reach = (bounds . flatten . Set.fromList) xs
isCovering :: Ord a => Interval a -> [Interval a] -> Bool
isCovering base xs = case (Set.toList . normalize . Set.fromList) xs of
[y] -> y `absorbs` base
_ -> False
isMinimalCovering :: Ord a => Interval a -> [Interval a] -> Bool
isMinimalCovering base xs = sufficient && minimal
where sufficient = isCovering base xs
minimal = List.null . filter (isCovering base)
. fmap (`deleteAt` xs) $ [0.. length xs - 1]
bruteForceCoveringChains :: forall a. (Ord a, Num a)
=> Interval a -> [Interval a] -> [[Interval a]]
bruteForceCoveringChains base xs = filter (isMinimalCovering base) (List.subsequences xs)
minimizeChain :: (Eq a, Ord a) => [Interval a] -> [Interval a]
minimizeChain xs = last . converge $ ys
where ys = iterate (join . flip cutTransitivitiesList touches) xs
transitivities :: Ord a => Set a -> (a -> a -> Bool) -> Set a
transitivities set eq =
let xs = Set.toList set
in Set.fromList [ y | x <- xs, y <- xs, z <- xs, x `eq` y, x `eq` z, y `eq` z ]
cutTransitivitiesList :: Ord a => [a] -> (a -> a -> Bool) -> [[a]]
cutTransitivitiesList set rel = Set.toList . Set.map Set.toList
$ cutTransitivities (Set.fromList set) rel
cutTransitivities :: Ord a => Set a -> (a -> a -> Bool) -> Set (Set a)
cutTransitivities set rel =
let t = transitivities set rel
in if Set.null t then Set.singleton set else Set.map (`Set.delete` set) t
-- λ traverse_ print $ coveringChains (interval 2 5) [interval 1 3, interval 2 4, interval 3 5, interval 4 6]
-- [Interval {left = 1, right = 3},Interval {left = 2, right = 4},Interval {left = 3, right = 5}]
-- [Interval {left = 1, right = 3},Interval {left = 2, right = 4},Interval {left = 4, right = 6}]
-- Definition of a covering chain:
-- 1. Sufficient: Subsumes the given interval.
-- 2. Minimal: If any element is removed, does not subsume anymore.
displayingRelation :: (Ord a, Show a, Arbitrary a, CoArbitrary a, Testable prop)
=> (Set a -> (a -> a -> Bool) -> Relation a -> prop) -> Property
displayingRelation p = forAllShrink arbitrary shrink \(Blind (MostlyNot f)) -> forAllShrink arbitrary shrink \xs ->
let rel = relation xs f in counterexample (show rel) $ (p xs f rel)
oneOfSet :: (Testable prop, Show a, Arbitrary a) => Set a -> (a -> prop) -> Property
oneOfSet set = forAll ((oneof . fmap return . Set.toList) set)
newtype MostlyNot a = MostlyNot (a -> a -> Bool)
instance (Arbitrary a, CoArbitrary a) => Arbitrary (MostlyNot a) where
arbitrary = do
f <- arbitrary
d6 <- fmap (`mod` 6) (arbitrary @Int)
return $ MostlyNot \x y -> if d6 == 0 then f x y else False
main :: IO ()
main = defaultMain $ testGroup "Properties."
[ testGroup "Cases."
[ testGroup "Relations."
[ testCaseSteps "`absorbs`" \_ -> do
assertBool "" $ interval @Int 1 4 `absorbs` point 1
assertBool "" $ interval @Int 1 4 `absorbs` interval 1 3
assertBool "" $ interval @Int 1 4 `absorbs` interval 1 4
assertBool "" $ interval @Int 1 4 `absorbs` interval 2 3
assertBool "" $ interval @Int 1 4 `absorbs` interval 2 4
assertBool "" $ interval @Int 1 4 `absorbs` point 4
, testCaseSteps "not `absorbs`" \_ -> do
assertBool "" . not $ interval @Int 1 4 `absorbs` point 0
assertBool "" . not $ interval @Int 1 4 `absorbs` interval 0 1
assertBool "" . not $ interval @Int 1 4 `absorbs` interval 0 2
assertBool "" . not $ interval @Int 1 4 `absorbs` interval 0 4
assertBool "" . not $ interval @Int 1 4 `absorbs` interval 1 5
assertBool "" . not $ interval @Int 1 4 `absorbs` interval 2 5
assertBool "" . not $ interval @Int 1 4 `absorbs` interval 4 5
assertBool "" . not $ interval @Int 1 4 `absorbs` point 5
, testCaseSteps "`isRightwardsOf`" \_ -> do
assertBool "" $ interval @Int 2 4 `isRightwardsOf` interval 1 3
, testCaseSteps "not `isRightwardsOf`" \_ -> do
assertBool "" . not $ interval @Int 2 4 `isRightwardsOf` interval 1 5
assertBool "" . not $ interval @Int 2 4 `isRightwardsOf` interval 2 5
assertBool "" . not $ interval @Int 2 4 `isRightwardsOf` interval 3 5
assertBool "" . not $ interval @Int 2 4 `isRightwardsOf` interval 4 5
]
]
, testGroup "Relations."
[ testProperty "The relation type is isomorphic to the original relation" $
displayingRelation @Int \xs f rel -> if null (xs :: Set Int) then property True else
oneOfSet xs \x -> oneOfSet xs \y -> rel ? (x, y) == x `f` y
, testProperty "A relation is not necessarily reflexive" $ expectFailure $
displayingRelation @Int \_ _ rel -> isReflexive @Int rel
, testProperty "Reflexive closure of a relation is reflexive" $
displayingRelation @Int \_ _ rel -> (isReflexive @Int . reflexiveClosure) rel
, testProperty "A relation is not necessarily symmetric" $ expectFailure $
displayingRelation @Int \_ _ rel -> isSymmetric @Int rel
, testProperty "Symmetric closure of a relation is symmetric" $
displayingRelation @Int \_ _ rel -> (isSymmetric @Int . symmetricClosure) rel
, testProperty "A relation is not necessarily transitive" $ expectFailure $
displayingRelation @Int \_ _ rel -> isTransitive @Int rel
, testProperty "Transitive closure of a relation is transitive" $
displayingRelation @Int \_ _ rel -> (isTransitive @Int . transitiveClosure) rel
]
, testGroup "Intervals."
[ testProperty "Shrinking intervals converges (Int)" \i ->
within (10 ^ (5 :: Int)) . withMaxSuccess 100
$ let _ = i :: Interval Int
nubShrink = fmap List.nub . (>=> shrink)
in List.elem [ ] . take 1000 . fmap ($ i) . iterate nubShrink $ return
, testProperty "Shrinking intervals converges (Float)" \i ->
within (10 ^ (5 :: Int)) . withMaxSuccess 100
$ let _ = i :: Interval Float
nubShrink = fmap List.nub . (>=> shrink)
in List.elem [ ] . take 1000 . fmap ($ i) . iterate nubShrink $ return
]
, testGroup "Relations on intervals."
let core = [ precedes, meets, overlaps, isFinishedBy, contains, starts ]
basic = core ++ fmap flip core ++ [(==)]
in
[ testProperty "Exhaustive" \intervals ->
let _ = intervals :: Set (Interval Float)
rels = fmap (relation intervals) basic
in List.foldl1' (elementwise (+*)) rels == complete intervals
, testProperty "Pairwise distinct" \intervals ->
let rels = fmap (relation intervals) basic
in QuickCheck.withMaxSuccess 1000 do
(s, t) <- anyTwo rels
return
$ counterexample (show s) . counterexample (show t)
$ elementwise (*) s t == blank intervals
]
, testGroup "Classification."
[ testProperty "Union inverts classification" $
displayingRelation \xs _ rel ->
let _ = xs :: Set Int
equivalence = closure rel
classes = classifyBy (curry (equivalence ?)) xs
in QuickCheck.classify (Set.size classes > 1) "Non-trivial equivalence" $
Set.unions classes == xs
, testProperty "Intersection of a classification is empty" $
displayingRelation \xs _ rel -> if Set.null xs then property True else
let _ = xs :: Set Int
equivalence = closure rel
classes = classifyBy (curry (equivalence ?)) xs
in QuickCheck.classify (Set.size classes > 1) "Non-trivial equivalence" $ property $
if Set.size classes == 1 then classes == Set.singleton xs else
foldr1 Set.intersection classes == Set.empty
, testProperty "Belonging to the same class = equivalent by the defining relation" $
displayingRelation \xs _ rel -> if Set.null xs then property True else
let _ = xs :: Set Int
equivalence = closure rel
classes = classifyBy (curry (equivalence ?)) xs
g :: Int -> Int -> Bool
g = (==) `on` \x -> Set.filter (x `Set.member`) classes
in QuickCheck.classify (Set.size classes > 1) "Non-trivial equivalence" $ property $
oneOfSet xs \x -> oneOfSet xs \y ->
counterexample (show $ Set.filter (x `Set.member`) classes) $
counterexample (show $ Set.filter (y `Set.member`) classes) $
counterexample (show equivalence) $
equivalence ? (x, y) == (x `g` y)
, testProperty "Every element belongs to exactly one class" $
displayingRelation \xs _ rel -> if Set.null xs then property True else
let _ = xs :: Set Int
equivalence = (transitiveClosure . symmetricClosure . reflexiveClosure) rel
classes = classifyBy (curry (equivalence ?)) xs
in QuickCheck.classify (Set.size classes > 1) "Non-trivial equivalence" $ property $
counterexample (show classes) $ counterexample (show equivalence) $
length (Set.unions classes) == (sum . fmap length . Set.toList) classes
]
, testGroup "Normalizer."
[ testProperty "Normal set of intervals is pairwise disjoint" \s ->
let t = normalize s :: Set (Interval Float)
in QuickCheck.classify (s /= t) "Non-trivial normalization"
. counterexample (displayIntervals s) . counterexample (displayIntervals t)
$ if Set.size t < 2 then return True else do
(i, j) <- anyTwo t
return $ i `isDisjointWith` j
, testProperty "Normalization is idempotent" \s ->
QuickCheck.classify (normalize s /= s) "Non-trivial normalization"
let t = normalize s :: Set (Interval Float)
t' = normalize t
in counterexample (displayIntervals s) . counterexample (displayIntervals t)
. counterexample (displayIntervals t')
$ t == t'
, testProperty "Preserves pointwise coverage" $ \s x ->
let t = normalize s :: Set (Interval Float)
in QuickCheck.classify (countWithin s x == 1) "Point is within exactly once"
. QuickCheck.classify (t /= s) "Non-trivial normalization"
. QuickCheck.classify (countWithin s x > 1) "Point is within more than once"
. QuickCheck.classify (not $ x `isWithinOneOf` s) "Point is without"
. counterexample (displayIntervals s) . counterexample (displayIntervals t)
$ (countWithin s x >= 1) == (countWithin t x == 1)
]
, checkCommutativeRingAxioms (Proxy @Binary) "Binary"
, checkCommutativeRingAxioms (Proxy @(Interval Float -> Interval Float -> Bool))
"Interval a -> Interval a -> Bool"
, testGroup "Chains."
[ caseSolution bruteForceCoveringChains (Proxy @Int)"bruteForceCoveringChains (Int)"
, caseSolution bruteForceCoveringChains (Proxy @Float)"bruteForceCoveringChains (Float)"
, checkSolution coveringChains (Proxy @Int) "`coveringChains` (Int)"
, checkSolution coveringChains (Proxy @Float) "`coveringChains` (Float)"
, checkSolution coveringChainsFromTo (Proxy @Int) "`coveringChainsFromTo` (Int)"
, checkSolution coveringChainsFromTo (Proxy @Float) "`coveringChainsFromTo` (Float)"
, checkSolution willemPaths (Proxy @Int) "`willemPaths` (Int)"
, checkSolution willemPaths (Proxy @Float) "`willemPaths` (Float)"
]
, testGroup "Total order of chains."
[ testProperty "Antisymmetric overall" \intervals ->
let _ = intervals :: [Interval Int]
in isAntisymmetric (relation (Set.fromList intervals) touches)
, testProperty "Refl/trans closure not total overall" \intervals ->
let _ = intervals :: [Interval Int]
in expectFailure $ (isTotal . transitiveClosure . reflexiveClosure)
(relation (Set.fromList intervals) touches)
, testProperty "Refl/trans closure is total on chains" \base intervals ->
let _ = intervals :: [Interval Int]
xs = coveringChains base intervals
in (not . null) xs ==> do
x <- (oneof . fmap return) xs
return $ (isTotal . transitiveClosure . reflexiveClosure)
(relation (Set.fromList x) touches)
]
]
checkSolution :: forall a. (Show a, NFData a, Arbitrary (Interval a), Num a, Ord a)
=> (Interval a -> [Interval a] -> [[Interval a]]) -> Proxy a -> String -> TestTree
checkSolution solution Proxy solutionName = testGroup ("Chains: " ++ show solutionName ++ ".")
[ caseSolution solution Proxy solutionName
, propSolution solution Proxy solutionName
]
caseSolution :: forall a. (Show a, NFData a, Arbitrary (Interval a), Num a, Ord a)
=> (Interval a -> [Interval a] -> [[Interval a]]) -> Proxy a -> String -> TestTree
caseSolution solution Proxy solutionName = testGroup ("Cases for " ++ solutionName ++ ".")
[ testCase "Simple covering chains"
$ solution
(interval 1 3) [interval 0 3, interval 0 4, interval 1 3, interval 1 4]
@?= [[interval 0 3], [interval 0 4], [interval 1 3], [interval 1 4]]
, testCaseSteps "Non-covering interval set" \_ -> do
solution
(interval 2 4)
[ interval 0 2, point 1, interval 1 2, interval 1 3
, point 2, interval 2 3
]
@?= [ ]
solution
(interval 2 4)
[ point 3, interval 3 4, interval 3 5
, point 4, interval 4 5
]
@?= [ ]
solution
(interval 2 5)
[ interval 0 2, point 1, interval 1 2, interval 1 3
, point 2, interval 2 3
, point 3
, point 4, interval 4 5, interval 4 6
, point 5, interval 5 6
]
@?= [ ]
, testCase "A set with extra intervals and point join"
$ solution
(interval 2 5)
[interval 1 3, interval 2 4, interval 3 6]
@?= [ [interval 1 3, interval 3 6], [interval 2 4, interval 3 6] ]
, testCase "A set with extra intervals and extended join"
$ solution
(interval 2 7)
[interval 1 4, interval 2 5, interval 3 7]
@?= [ [interval 1 4, interval 3 7], [interval 2 5, interval 3 7] ]
]
propSolution :: forall a. (Show a, NFData a, Arbitrary (Interval a), Num a, Ord a)
=> (Interval a -> [Interval a] -> [[Interval a]]) -> Proxy a -> String -> TestTree
propSolution solution Proxy solutionName = testGroup ("Properties for " ++ solutionName ++ ".")
[ testProperty "A chain terminates" \base intervals ->
let _ = intervals :: [Interval a]
chains = solution base intervals
in within (10 ^ (4 :: Int)) . withMaxSuccess 1000
$ chains `deepseq` True
, testProperty "A normalized chain is a singleton" \base intervals ->
let _ = intervals :: [Interval a]
normalChains = fmap normalizeList (solution base intervals)
in counterexample (show normalChains)
$ and . fmap ((1 ==) . length) $ normalChains
, testProperty "A chain is a cover" \base intervals ->
let _ = intervals :: [Interval a]
chains = Set.fromList . fmap (normalize . Set.fromList) $ solution base intervals
in and . Set.map (`subsume` base) $ chains
, testProperty "A chain is minimal" \base intervals ->
let _ = intervals :: [Interval a]
chains = solution base intervals
subchains = List.nub (chains >>= dropOne)
in within (10 ^ (6 :: Int)) $ (or . fmap ((`subsume` base) . Set.fromList)
$ fmap normalizeList subchains) == False
, testProperty "Brute force search on null chain situations is fruitless"
\base intervals3 ->
let intervals2 = getInfiniteList intervals3 :: [[Interval a]]
f = List.null . solution base
g = \xs -> length xs < 10
Just intervals = List.find f . filter g . take 100 $ intervals2
in counterexample (show intervals)
$ length intervals > 5 ==> List.null (bruteForceCoveringChains base intervals)
, testProperty "Equivalent to brute force search" \base intervals' ->
let intervals = take 9 intervals' :: [Interval a]
s = List.sort . fmap List.sort $ solution base intervals
t = List.sort . fmap List.sort $ bruteForceCoveringChains base intervals
in s === t
]
willemPaths :: Ord a => Interval a -> [Interval a] -> [[Interval a]]
willemPaths u us = (fmap.fmap) fromTuple $ paths' (toTuple u) (fmap toTuple us)
where
toTuple (Interval x y) = (x, y)
toTuple (Point x) = (x, x)
fromTuple = uncurry interval
-- Example errors:
-- λ paths' (0, 2) [(-2, 1), (-1, 2)]
-- [[(-2,1),(-1,2)],[(-1,2)]]
-- λ paths' (-2, 1) [(-2, 1), (-3, -1)]
-- [[(-3,-1),(-2,1)],[(-2,1)]]
dropOne :: [a] -> [[a]]
dropOne [ ] = [ ]
dropOne xs = do
index <- [0.. length xs - 1]
let ys = deleteAt index xs
return ys
checkCommutativeRingAxioms :: forall a. (Eq a, Num a, Show a, Arbitrary a) => Proxy a -> String -> TestTree
checkCommutativeRingAxioms Proxy typeName = testGroup ("Ring axioms for " ++ typeName ++ ".")
[ testProperty "Addition is associative" \x y z ->
let _ = (x :: a) in (x + y) + z == x + (y + z)
, testProperty "Addition is commutative" \x y ->
let _ = (x :: a) in x + y == y + x
, testProperty "Multiplication is associative" \x y z ->
let _ = (x :: a) in (x * y) * z == x * (y * z)
, testProperty "Multiplication is commutative" \x y ->
let _ = (x :: a) in x * y == y * x
, testProperty "Negation is compatible with zero" \x ->
let _ = (x :: a) in (x + negate x) + x == x
, testProperty "There is only one zero" \x y ->
let _ = (x :: a) in x + negate x == y + negate y
, testProperty "Left distribution" \x y z ->
let _ = (x :: a) in x * (y + z) == (x * y) + (x * z)
, testProperty "Right distribution" \x y z ->
let _ = (x :: a) in (y + z) * x == (y * x) + (z * x)
]
deleteAt :: Int -> [a] -> [a]
deleteAt idx xs = lft ++ rgt
where (lft, (_:rgt)) = splitAt idx xs
anyTwo :: (Show (f a), Foldable f) => f a -> Gen (a, a)
anyTwo set
| length set > 1 = do
let list = toList set
x <- choose (0, length list - 1)
let s = list !! x
list' = deleteAt x list
y <- choose (0, length list' - 1)
let t = list' !! y
return (s, t)
| otherwise = error $ "anyTwo cannot find two distinct elements: \
\set " ++ show set ++ " is too small."