{-# LANGUAGE OverloadedStrings, DeriveFunctor, DeriveGeneric #-}
module Graphics.Rendering.Plot.Light.Internal
(
Frame(..), mkFrame, unitFrame, mkFrameOrigin, frameToFrame, frameToFrameValue, frameFromPoints, frameFromFigData, xmin,xmax,ymin,ymax, width, height,
FigureData(..), figFWidth, figFHeight
, Point(..), mkPoint, origin
, LabeledPoint(..), mkLabeledPoint, labelPoint, mapLabel, Axis(..), axes, meshGrid, subdivSegment,
svgHeader, toPlot,
rect, rectCentered, rectCenteredMidpointBase, squareCentered,
circle,
line, tick, ticks, axis,
polyline, filledPolyline, filledBand, strokeLineJoin, LineStroke_(..), StrokeLineJoin_(..),
text, TextAnchor_(..),
pixel, pixel', plusGlyph, crossGlyph, candlestick,
pickColour, colourBar, legendBar, LegendPosition_(..),
V2(..), e1, e2, norm2, normalize2, v2fromEndpoints, v2fromPoint, (-.), pointRange
, Mat2(..), DiagMat2(..), diagMat2
, AdditiveGroup(..), VectorSpace(..), Hermitian(..), LinearMap(..), MultiplicativeSemigroup(..), MatrixGroup(..), Eps(..), movePoint, moveLabeledPointV2, moveLabeledPointBwFrames, translateSvg, toSvgFrame, toSvgFrameLP, toFloat, wholeDecimal
, blendTwo, palette
, (!#), Col(..), ShapeCol(..), col, col50, col100, shapeColBoth
, shapeColNoBorder, shapeColNoFill
, interpolateBilinear)
where
import Data.Monoid ((<>))
import qualified Data.Foldable as F (toList)
import Data.List
import Control.Monad (forM, forM_)
import Control.Monad.State
import Data.Scientific (Scientific, toRealFloat)
import qualified Data.Text as T
import Text.Blaze.Internal (Attributable(..))
import Text.Blaze.Svg
import Text.Blaze.Svg11 ((!))
import qualified Text.Blaze.Svg11 as S hiding (style)
import qualified Text.Blaze.Svg11.Attributes as SA hiding (rotate)
import Text.Blaze.Svg.Renderer.String (renderSvg)
import qualified Data.Colour as C
import qualified Data.Colour.Names as C
import qualified Data.Colour.SRGB as C
import GHC.Real
import GHC.Generics
import Data.Fixed
import Graphics.Rendering.Plot.Light.Internal.Geometry
import Graphics.Rendering.Plot.Light.Internal.Utils
data FigureData a = FigureData {
figWidth :: a
, figHeight :: a
, figLeftMFrac :: a
, figRightMFrac :: a
, figTopMFrac :: a
, figBottomMFrac :: a
, figLabelFontSize :: Int
} deriving (Eq, Show, Functor, Generic)
figureDataDefault :: Floating a => FigureData a
figureDataDefault = FigureData 400 300 0.1 0.9 0.1 0.9 10
svgHeader :: Real a =>
a
-> a
-> Svg
-> Svg
svgHeader w h =
S.docTypeSvg
! SA.version "1.1"
! SA.width (vd w)
! SA.height (vd h)
! SA.viewbox (vds [xmin fd, ymin fd, xmax fd, ymax fd]) where
fd = mkFrameOrigin w h
data Col a = Col {
cColour :: C.Colour Double
, cAlpha :: a
} deriving (Eq, Show)
col :: C.Colour Double -> a -> Col a
col = Col
col100 :: Num a => C.Colour Double -> Col a
col100 c = col c 1
col50 :: Fractional a => C.Colour Double -> Col a
col50 c = col c 0.5
data ShapeCol a =
NoBorderCol (Col a)
| NoFillCol (Col a) a
| BothCol (Col a) (Col a) a
deriving (Eq, Show)
shapeColNoBorder :: C.Colour Double -> a -> ShapeCol a
shapeColNoBorder c a = NoBorderCol $ col c a
shapeColNoFill :: C.Colour Double -> a -> a -> ShapeCol a
shapeColNoFill c a = NoFillCol $ col c a
shapeColBoth ::
C.Colour Double
-> C.Colour Double
-> a
-> a
-> ShapeCol a
shapeColBoth cs cf a = BothCol (col cs a) (col cf a)
(!#) :: (Attributable h, Real a) => h -> ShapeCol a -> h
m !# col = case col of
NoBorderCol (Col c a) ->
m ! SA.fillOpacity (vd a) ! SA.fill (colourAttr c) ! SA.stroke none
NoFillCol (Col c a) sw ->
m ! SA.strokeOpacity (vd a) ! SA.stroke (colourAttr c) ! SA.strokeWidth (vd sw) ! SA.fill none
BothCol (Col cf af) (Col cb ab) sw ->
m ! SA.fillOpacity (vd af) ! SA.fill (colourAttr cf) ! SA.strokeOpacity (vd ab) ! SA.stroke (colourAttr cb) ! SA.strokeWidth (vd sw)
none :: S.AttributeValue
none = S.toValue ("none" :: String)
rect :: Real a =>
a
-> a
-> ShapeCol a
-> Point a
-> Svg
rect wid hei col (Point x0 y0) = S.rect ! SA.x (vd x0) ! SA.y (vd y0) ! SA.width (vd wid) ! SA.height (vd hei) !# col
rectCentered :: (Show a, RealFrac a) =>
a
-> a
-> ShapeCol a
-> Point a
-> Svg
rectCentered wid hei col (Point x0 y0) =
rect wid hei col p' where
p' = Point x0c y0c
x0c = x0 - (wid / 2)
y0c = y0 - (hei / 2)
rectCenteredMidpointBase :: (Show a, RealFrac a) =>
a
-> a
-> ShapeCol a
-> Point a
-> Svg
rectCenteredMidpointBase wid hei col (Point x0 y0) =
rect wid hei col p' where
p' = Point x0c y0
x0c = x0 - (wid / 2)
squareCentered :: (Show a, RealFrac a) =>
a
-> ShapeCol a
-> Point a
-> Svg
squareCentered w = rectCentered w w
lineColourDefault :: C.Colour Double
lineColourDefault = C.blue
lineStrokeTypeDefault :: LineStroke_ a
lineStrokeTypeDefault = Continuous
data LineOptions a = LineOptions {
loStrokeWidth :: a
, loStrokeType :: LineStroke_ a
, loColour :: C.Colour Double
} deriving (Eq, Show, Generic)
lineOptionsDefault :: Num a => LineOptions a
lineOptionsDefault = LineOptions 2 lineStrokeTypeDefault lineColourDefault
lineOptionCycle :: Fractional a => a -> [LineOptions a]
lineOptionCycle lw =
let
strTys =
replicate 5 Continuous <>
replicate 5 (Dashed [0.2, 0.5]) <>
replicate 5 (Dashed [0.5, 0.2])
cols = [C.blue, C.green, C.red, C.black, C.purple]
nc = length cols
in
LineOptions <$>
repeat lw <*>
strTys <*>
cols
line :: (Show a, RealFrac a) =>
Point a
-> Point a
-> a
-> LineStroke_ a
-> C.Colour Double
-> Svg
line (Point x1 y1) (Point x2 y2) sw lstr col =
let
svg0 = S.line ! SA.x1 (vd x1) ! SA.y1 (vd y1) ! SA.x2 (vd x2) ! SA.y2 (vd y2) ! SA.stroke (colourAttr col) ! SA.strokeWidth (vd sw)
in case lstr of Continuous -> svg0
Dashed d -> svg0 ! strokeDashArray d
strokeDashArray :: Real a => [a] -> S.Attribute
strokeDashArray sz = SA.strokeDasharray (S.toValue str) where
str = intercalate ", " $ map (show . real) sz
data LineStroke_ a = Continuous | Dashed [a] deriving (Eq, Show, Generic)
tick :: (Show a, RealFrac a) => Axis -> a -> a -> C.Colour Double -> Point a -> Svg
tick ax len sw col (Point x y) = line (Point x1 y1) (Point x2 y2) sw Continuous col where
lh = len / 2
(x1, y1, x2, y2)
| ax == Y = (x, y-lh, x, y+lh)
| otherwise = (x-lh, y, x+lh, y)
plusGlyph, crossGlyph :: (Show a, RealFrac a) =>
a
-> a
-> C.Colour Double
-> Point a
-> Svg
plusGlyph w sw k (Point x y) = do
line pl pr sw Continuous k
line pt pb sw Continuous k
where
wh = w / 2
pl = Point (x-wh) y
pr = Point (x+wh) y
pt = Point x (y-wh)
pb = Point x (y+wh)
crossGlyph w sw k (Point x y) = do
line pa pb sw Continuous k
line pc pd sw Continuous k
where
wh = 1.4142 * w
pa = Point (x+wh) (x+wh)
pb = Point (x-wh) (x-wh)
pc = Point (x+wh) (x-wh)
pd = Point (x-wh) (x+wh)
labeledTick
:: (Show a, RealFrac a) =>
Axis
-> a
-> a
-> C.Colour Double
-> Int
-> a
-> TextAnchor_
-> (t -> T.Text)
-> V2 a
-> LabeledPoint t a
-> Svg
labeledTick ax len sw col fontsize lrot tanchor flab vlab (LabeledPoint p label) = do
tick ax len sw col p
text lrot fontsize col tanchor (flab label) vlab p
ticks :: (Foldable t, Show a, RealFrac a) =>
Axis
-> a
-> a
-> C.Colour Double
-> t (Point a)
-> Svg
ticks ax len sw col ps = forM_ ps (tick ax len sw col)
labeledTicks :: (Foldable t, Show a, RealFrac a) =>
Axis
-> a
-> a
-> C.Colour Double
-> Int
-> a
-> TextAnchor_
-> (t2 -> T.Text)
-> V2 a
-> t (LabeledPoint t2 a)
-> Svg
labeledTicks ax len sw col fontsize lrot tanchor flab vlab ps =
forM_ ps (labeledTick ax len sw col fontsize lrot tanchor flab vlab)
axis :: (Functor t, Foldable t, Show a, RealFrac a) =>
Point a
-> Axis
-> a
-> a
-> C.Colour Double
-> a
-> LineStroke_ a
-> Int
-> a
-> TextAnchor_
-> (l -> T.Text)
-> V2 a
-> t (LabeledPoint l a)
-> Svg
axis o@(Point ox oy) ax len sw col tickLenFrac ls fontsize lrot tanchor flab vlab ps = do
line o pend sw ls col
labeledTicks (otherAxis ax) (tickLenFrac * len) sw col fontsize lrot tanchor flab vlab (moveLabeledPoint f <$> ps)
where
pend | ax == X = Point (ox + len) oy
| otherwise = Point ox (oy + len)
f | ax == X = setPointY oy
| otherwise = setPointX ox
axes :: (Show a, RealFrac a) =>
FigureData a
-> Frame a
-> a
-> C.Colour Double
-> Int
-> Int
-> Svg
axes fdat (Frame (Point xmi ymi) (Point xma yma)) sw col nx ny = do
axis o X lenx sw col 0.01 Continuous fontsize (-45) TAEnd showlabf (V2 (-10) 0) plabx_
axis o Y (- leny) sw col 0.01 Continuous fontsize 0 TAEnd showlabf (V2 (-10) 0) plaby_
where
o = Point (figWidth fdat * figLeftMFrac fdat) (figHeight fdat * figBottomMFrac fdat)
pxend = movePoint (V2 lenx 0) o
pyend = movePoint (V2 0 (- leny)) o
plabx_ = zipWith LabeledPoint (pointRange nx o pxend) (take (nx+1) $ subdivSegment xmi xma $ fromIntegral nx)
plaby_ = zipWith LabeledPoint (pointRange ny o pyend) (take (ny+1) $ subdivSegment ymi yma $ fromIntegral ny)
fontsize = figLabelFontSize fdat
lenx = figFWidth fdat
leny = figFHeight fdat
showlabf x = T.pack $ show (fromRational x :: Fixed E2)
toPlot :: (Functor t, Foldable t, Show a, RealFrac a) =>
FigureData a
-> (l -> T.Text)
-> (l -> T.Text)
-> a
-> a
-> a
-> C.Colour Double
-> Maybe (t (LabeledPoint l a))
-> Maybe (t (LabeledPoint l a))
-> (t (LabeledPoint l a) -> Svg)
-> t (LabeledPoint l a)
-> Svg
toPlot fd flabelx flabely rotx roty sw col1 tickxe tickye plotf dat = do
axis oSvg X (width to) sw col1 0.05 Continuous fontsize rotx TAEnd flabelx (V2 (-10) 0) tickx
axis oSvg Y (negate $ height to) sw col1 0.05 Continuous fontsize roty TAEnd flabely (V2 (-10) 0) ticky
plotf dat'
where
fontsize = figLabelFontSize fd
from = frameFromPoints $ _lp <$> dat
to = frameFromFigData fd
datf = toSvgFrameLP from to False
dat' = datf <$> dat
tickDefault ti d = case ti of Just t -> datf <$> t
Nothing -> d
tickx = tickDefault tickxe dat'
ticky = tickDefault tickye dat'
oSvg = Point (xmin to) (ymax to)
frameFromFigData :: Num a => FigureData a -> Frame a
frameFromFigData fd = mkFrame oTo p2To where
fontsize = figLabelFontSize fd
wfig = figWidth fd
hfig = figHeight fd
(left, right) = (figLeftMFrac fd * wfig, figRightMFrac fd * wfig)
(top, bot) = (figTopMFrac fd * hfig, figBottomMFrac fd * hfig)
oTo = Point left top
p2To = Point right bot
figFWidth, figFHeight :: Num a => FigureData a -> a
figFWidth = width . frameFromFigData
figFHeight = height . frameFromFigData
text :: (Show a, Real a) =>
a
-> Int
-> C.Colour Double
-> TextAnchor_
-> T.Text
-> V2 a
-> Point a
-> Svg
text rot fontsize col ta te (V2 vx vy) (Point x y) = S.text_ (S.toMarkup te) ! SA.x (vd vx) ! SA.y (vd vy) ! SA.transform (S.translate (real x) (real y) <> S.rotate (real rot)) ! SA.fontSize (vi fontsize) ! SA.fill (colourAttr col) ! textAnchor ta
data TextAnchor_ = TAStart | TAMiddle | TAEnd deriving (Eq, Show)
textAnchor :: TextAnchor_ -> S.Attribute
textAnchor TAStart = SA.textAnchor (vs "start")
textAnchor TAMiddle = SA.textAnchor (vs "middle")
textAnchor TAEnd = SA.textAnchor (vs "end")
circle
:: (Real a1, Real a) =>
a
-> ShapeCol a
-> Point a1
-> Svg
circle r col (Point x y) =
S.circle ! SA.cx (vd x) ! SA.cy (vd y) ! SA.r (vd r) !# col
polyline :: (Foldable t, Show a1, Show a, RealFrac a, RealFrac a1) =>
a1
-> LineStroke_ a
-> StrokeLineJoin_
-> C.Colour Double
-> t (Point a)
-> Svg
polyline sw strTy slj col lis =
let
svg0 = S.polyline ! SA.points (S.toValue $ unwords $ map show $ F.toList lis) ! SA.fill none ! SA.stroke (colourAttr col ) ! SA.strokeWidth (vd sw) ! strokeLineJoin slj
in case strTy of Continuous -> svg0
Dashed d -> svg0 ! strokeDashArray d
filledPolyline :: (Foldable t, Show a, Real o) =>
C.Colour Double
-> o
-> t (Point a)
-> Svg
filledPolyline col opac lis = S.polyline ! SA.points (S.toValue $ unwords $ map show $ F.toList lis) ! SA.fill (colourAttr col) ! SA.fillOpacity (vd opac)
filledBand :: (Foldable t, Real o, Show a) =>
C.Colour Double
-> o
-> (l -> a)
-> (l -> a)
-> t (LabeledPoint l a)
-> Svg
filledBand col opac ftop fbot lis0 = filledPolyline col opac (lis1 <> lis2) where
lis = F.toList lis0
f1 lp = setPointY (ftop $ _lplabel lp) $ _lp lp
f2 lp = setPointY (fbot $ _lplabel lp) $ _lp lp
lis1 = f1 <$> lis
lis2 = f2 <$> reverse lis
candlestick
:: (Show a, RealFrac a) =>
(a -> a -> Bool)
-> (l -> a)
-> (l -> a)
-> (l -> a)
-> (l -> a)
-> a
-> a
-> ShapeCol a
-> ShapeCol a
-> C.Colour Double
-> LabeledPoint l a
-> Svg
candlestick fdec fboxmin fboxmax fmin fmax wid sw col1 col2 colstroke lp = do
line pmin pmax sw Continuous colstroke
rectCentered wid hei col p
where
p = _lp lp
lab = _lplabel lp
pmin = setPointY (fmin lab) p
pmax = setPointY (fmax lab) p
hei = abs $ fboxmax lab - fboxmin lab
col | fdec (fboxmax lab) (fboxmin lab) = col1
| otherwise = col2
data StrokeLineJoin_ = Miter | Round | Bevel | Inherit deriving (Eq, Show)
strokeLineJoin :: StrokeLineJoin_ -> S.Attribute
strokeLineJoin slj = SA.strokeLinejoin (S.toValue str) where
str | slj == Miter = "miter" :: String
| slj == Round = "round"
| slj == Bevel = "bevel"
| otherwise = "inherit"
translateSvg :: Show a => Point a -> Svg -> Svg
translateSvg (Point x y) svg = S.g ! SA.transform (S.translate x y) $ svg
toSvgFrame ::
Fractional a =>
Frame a
-> Frame a
-> Bool
-> Point a
-> Point a
toSvgFrame from to fliplr p = pointFromV2 v' where
v' = frameToFrame from to fliplr True (v2fromPoint p)
toSvgFrameLP ::
Fractional a => Frame a -> Frame a -> Bool -> LabeledPoint l a -> LabeledPoint l a
toSvgFrameLP from to fliplr (LabeledPoint p lab) = LabeledPoint (toSvgFrame from to fliplr p) lab
pixel :: (Show a, RealFrac a) =>
[C.Colour Double]
-> a
-> a
-> Scientific
-> Scientific
-> LabeledPoint Scientific a
-> Svg
pixel pal w h vmin vmax (LabeledPoint p l) = rect w h col p where
col = pickColour pal (toFloat vmin) (toFloat vmax) (toFloat l)
pixel'
:: (Show a, RealFrac a, RealFrac t) =>
[C.Colour Double]
-> a
-> a
-> t
-> t
-> LabeledPoint t a
-> Svg
pixel' pal w h vmin vmax (LabeledPoint p l) = rect w h col p where
col = pickColour pal vmin vmax l
pickColour :: (RealFrac t, Num a) =>
[C.Colour Double] -> t -> t -> t -> ShapeCol a
pickColour pal xmin xmax x = NoBorderCol $ Col (pal !! i) 1
where
i = floor (x01 * fromIntegral (nColors - 1))
x01 = (x - xmin) / (xmax - xmin)
nColors = length pal
data LegendPosition_ =
TopLeft | TopRight | BottomLeft | BottomRight deriving (Eq, Show)
posCoeff :: Fractional a => LegendPosition_ -> (a, a)
posCoeff pos =
case pos of
TopLeft -> (0.1, 0.1)
TopRight -> (0.83, 0.15)
BottomLeft -> (0.1, 0.9)
BottomRight -> (0.9, 0.9)
colourBar
:: (RealFrac t, RealFrac a, Show a, Enum t, Floating a) =>
FigureData (Ratio Integer)
-> [C.Colour Double]
-> a
-> t
-> t
-> Int
-> LegendPosition_
-> a
-> Svg
colourBar fdat pal w vmin vmax n legpos legh =
legendBar (fromRational <$> fdat) w vmin vmax n legpos legh (colBarPx pal)
legendBar :: (Monad m, Enum t, Fractional t, Fractional a) =>
FigureData a
-> a
-> t
-> t
-> Int
-> LegendPosition_
-> a
-> (FigureData a -> a -> a -> t -> t -> LabeledPoint t a -> m b)
-> m ()
legendBar fdat w vmin vmax n legpos legh fun = do
forM_ lps (fun fdat w h vmin vmax) where
wrect = 0.95 * (1 - figRightMFrac fdat) * figWidth fdat
hrect = 1.5 * legh
prect = movePoint (V2 (-0.5 * w) (-0.5 * w)) p2
(legx, legy) = posCoeff legpos
legendX = figWidth fdat * legx
legendY = figHeight fdat * legy
p1 = Point legendX (legendY + legh)
p2 = Point legendX legendY
lps = zipWith LabeledPoint (pointRange n p1 p2) v_
h = legh / fromIntegral n
v_ = take (n+1) [vmin, vmin + dv ..]
dv = (vmax - vmin)/fromIntegral n
colBarPx
:: (Show a, RealFrac a, RealFrac t) =>
[C.Colour Double]
-> FigureData a1
-> a
-> a
-> t
-> t
-> LabeledPoint t a
-> Svg
colBarPx pal fdat w h vmin vmax (LabeledPoint p val) = do
text 0 (figLabelFontSize fdat) C.black TAStart (T.pack $ show (rr val :: Fixed E3)) (V2 (1.1*w) (0.5*h)) p
rectCentered w h (pickColour pal vmin vmax val) p
colourAttr :: C.Colour Double -> S.AttributeValue
colourAttr = S.toValue . C.sRGB24show
vs :: String -> S.AttributeValue
vs x = S.toValue (x :: String)
vi :: Int -> S.AttributeValue
vi = S.toValue
vd0 :: Double -> S.AttributeValue
vd0 = S.toValue
vd :: Real a => a -> S.AttributeValue
vd = vd0 . real
real :: (Real a, Fractional b) => a -> b
real = fromRational . toRational
vds :: Real a => [a] -> S.AttributeValue
vds = S.toValue . unwords . map (show . real)