]> gitweb.michael.orlitzky.com - spline3.git/blob - src/Grid.hs
Fix all orphan instances.
[spline3.git] / src / Grid.hs
1 -- | The Grid module just contains the Grid type and two constructors
2 -- for it. We hide the main Grid constructor because we don't want
3 -- to allow instantiation of a grid with h <= 0.
4 module Grid
5 where
6
7 import Test.QuickCheck (Arbitrary(..), Gen, Positive(..))
8
9 import Cube (Cube(Cube))
10 import FunctionValues
11 import Misc (flatten)
12 import Point (Point)
13 import ThreeDimensional (contains_point)
14
15
16 -- | Our problem is defined on a Grid. The grid size is given by the
17 -- positive number h. The function values are the values of the
18 -- function at the grid points, which are distance h from one
19 -- another in each direction (x,y,z).
20 data Grid = Grid { h :: Double, -- MUST BE GREATER THAN ZERO!
21 function_values :: [[[Double]]] }
22 deriving (Eq, Show)
23
24
25 instance Arbitrary Grid where
26 arbitrary = do
27 (Positive h') <- arbitrary :: Gen (Positive Double)
28 fvs <- arbitrary :: Gen [[[Double]]]
29 return (make_grid h' fvs)
30
31
32 -- | The constructor that we want people to use. If we're passed a
33 -- non-positive grid size, we throw an error.
34 make_grid :: Double -> [[[Double]]] -> Grid
35 make_grid grid_size values
36 | grid_size <= 0 = error "grid size must be positive"
37 | otherwise = Grid grid_size values
38
39
40 -- | Creates an empty grid with grid size 1.
41 empty_grid :: Grid
42 empty_grid = Grid 1 [[[]]]
43
44
45 -- | Returns a three-dimensional list of cubes centered on the grid
46 -- points of g with the appropriate 'FunctionValues'.
47 cubes :: Grid -> [[[Cube]]]
48 cubes g
49 | fvs == [[[]]] = [[[]]]
50 | head fvs == [[]] = [[[]]]
51 | otherwise =
52 [[[ Cube (h g) i j k (make_values fvs i j k) | i <- [0..xsize]]
53 | j <- [0..ysize]]
54 | k <- [0..zsize]]
55 where
56 fvs = function_values g
57 zsize = (length fvs) - 1
58 ysize = length (head fvs) - 1
59 xsize = length (head $ head fvs) - 1
60
61
62 -- | Takes a grid and a position as an argument and returns the cube
63 -- centered on that position. If there is no cube there (i.e. the
64 -- position is outside of the grid), it will return 'Nothing'.
65 cube_at :: Grid -> Int -> Int -> Int -> Maybe Cube
66 cube_at g i j k
67 | i < 0 = Nothing
68 | j < 0 = Nothing
69 | k < 0 = Nothing
70 | i >= length (cubes g) = Nothing
71 | j >= length ((cubes g) !! i) = Nothing
72 | k >= length (((cubes g) !! i) !! j) = Nothing
73 | otherwise = Just $ (((cubes g) !! i) !! j) !! k
74
75
76 -- | Takes a 'Grid', and returns all 'Cube's belonging to it that
77 -- contain the given 'Point'.
78 find_containing_cubes :: Grid -> Point -> [Cube]
79 find_containing_cubes g p =
80 filter contains_our_point all_cubes
81 where
82 all_cubes = flatten $ cubes g
83 contains_our_point = flip contains_point p