Don't enter gnuplot terminal - haskell

Using the gnuplot module, after I plot a graph I get put into the gnuplot console. Is there a way to stop this happening? I never use it, and it's annoying to have to type exit after closing each graph, especially when I'm testing a sequence of plots.
For example:
module Main where
import Graphics.Gnuplot.Simple
main = do
let xs = linearScale 100 (-10, 10) :: [Float]
plotFunc [] xs sin
plotFunc [] xs cos
I'm using Windows 7 x64 and the Haskell Platform 2013.2.0.0 if that makes a difference.

Try the following:
bind Close "exit gnuplot"
It should do the trick!
See here for bind details if you aren't familiar: bind reference

Related

Using Z3 with parallelization from SBV

I'd like to use Z3 via SBV using multiple cores. Based on this answer I should be able to do that just by passing parallel.enable=true to the z3 executable on the command line. Since I am using SBV, I need to go through SBV's interface to various SMTLib solvers, so here's what I tried:
foo = runSMTWith z3par $ do
...
where
z3par = z3
{ SBV.solver = (SBV.solver z3)
{ SBV.options = \cfg -> SBV.options (SBV.solver z3) cfg ++ ["parallel.enable=true"]
}
}
However, I am not seeing any signs of Z3 running with parallelization enabled:
CPU usage doesn't go above one core
No speedup compared to running without this flag
How do I enable Z3 parallelization, when going via SBV?
What you're doing is essentially how it is done from SBV. You might want to increase verbosity of z3 and output the diagnostics to a file to inspect later. Something like:
import Data.SBV
import Data.SBV.Control
foo :: IO (Word64, Word64)
foo = runSMTWith z3{solver = par} $ do
x <- sWord64 "x"
y <- sWord64 "y"
setOption $ DiagnosticOutputChannel "diagnostic_output"
constrain $ x * y .== 13
constrain $ x .> 1
constrain $ y .> 1
query $ do ensureSat
(,) <$> getValue x <*> getValue y
where par = (solver z3) {options = \cfg -> options (solver z3) cfg ++ extras}
extras = [ "parallel.enable=true"
, "-v:3"
]
Here, we're not only setting z3's parallel-mode, but we're also telling it to increase verbosity and put all the diagnostics in a file. (Side note: There are many other settings in the parallel section of z3 config, you can see what they are by issuing z3 -pd in your command line and looking at the output. You can set any other parameters from there by adding it to the extras variable above.)
When I run the above, I get:
*Main> foo
(6379316565415788539,3774100875216427415)
But I also get a file named diagnostic_output created in the current directory, which contains the following lines, amongst others:
(tactic.parallel :progress 0% :open 1)
(tactic.parallel :split-cube 0)
(parallel.tactic simplify-1)
(tactic.parallel :progress 100.00% :status sat :open 0)
So z3 is indeed in the parallel mode and things are happening. Of course, what exactly it does is more or less a black-box, and it's impossible to interpret the above output without inspecting z3 internals. (I don't think the meaning of these stats nor the strategies for the parallel solver are that well documented. If you find a good documentation on the details, please do report!)
Update
As of this commit, you can now simply say:
runSMTWith z3{extraArgs = ["parallel.enable=true"]} $ do ...
simplifying the programming a bit further.
Solver agnostic concurrency directly from SBV
Note that SBV also has combinators for running things concurrently directly from Haskell. See the functions:
satConcurrentWithAny
satConcurrentWithAll
proveConcurrentWithAny
proveConcurrentWithAll
These functions are solver agnostic, you can use them with any solver of your choosing. Of course, they require you to restructure your problem and do a manual decomposition to take advantage of the multiple-cores in your computer and stitch the solutions together yourself. But they also give you full control over how you want to structure your expensive search.

Why does my program exit immediately after playing a gloss animation?

I am learning how to use the Gloss library to make some animations in Haskell.
Consider the code below which animates a circle that shrinks and expands its radius with time.
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Game
type Radius = Float
type RealTime = Float
data World = World Radius RealTime
main :: IO ()
main
= do let initWorld = World 100.0 0
let windowSize = (800,800)
let windowPosition = (200,200)
putStrLn "Before play"
play (InWindow "Wobbling Circle" windowSize windowPosition)
white 40 initWorld renderWorld handleEvent stepWorld
putStrLn "After play"
renderWorld :: World -> Picture
renderWorld (World rad rtime ) = Pictures [ Circle rad ]
handleEvent :: Event -> World -> World
handleEvent _ = id
stepWorld :: Float -> World -> World -- wobbling circle
stepWorld _ (World _ rtime) = World (100 * sin rtime) (rtime+0.1)
I compiled this code with ghc --make -O2 -threaded Main.hs on an Ubuntu 14.04 machine.
When I run the code, the "Before play" statement is printed out and then the animation starts as expected. However, when I close the animation window, the code terminates immediately without printing the "After Play" statement. Why is that?
Presumably you are using the GLUT backend (the default). Take a look at some of the source code for gloss (exactly as it appears with comments):
instance Backend GLUTState where
initBackendState = glutStateInit
initializeBackend = initializeGLUT
-- non-freeglut doesn't like this: (\_ -> GLUT.leaveMainLoop)
exitBackend = (\_ -> System.exitWith System.ExitSuccess)
....
When it exits the main loop, gloss will call exitBackend, whatever it is. For GLUT, that simply calls System.exitWith which naturally will terminate your program. The more sensible thing to do would be to call leaveMainLoop but as the comment in the code says, implementations of glut other than freeglut don't work well with that function (why? who knows. This is what the authors of gloss claim).
Your potential solutions are to use freeglut specifically and modify the source code of gloss to change exitBackend; or use the GLFW backend, which doesn't have this problem.

How to create this simple gif animation with Diagrams

I am trying to understand how to use Diagrams library in Haskell.
Here is my attempt at making a simple gif animation which switches between two circles of radii 1 and 2. I tried to mimic what I saw on
Here is the code, I tried.
{-# LANGUAGE NoMonomorphismRestriction #-}
import Diagrams.Backend.SVG.CmdLine
import Diagrams.Prelude
delays = take 2 (repeat 3)
gif :: [(Diagram B, Int)]
gif = zip [circle 1, circle 2] delays
main = mainWith $ gif
But this fails to compile! The errors I get are
[1 of 1] Compiling Main ( maze.hs, maze.o )
maze.hs:10:8:
No instance for (Diagrams.Backend.CmdLine.Parseable
(Diagrams.Backend.CmdLine.MainOpts
[(QDiagram B V2 Double Any, Int)]))
arising from a use of ‘mainWith’
In the expression: mainWith
In the expression: mainWith $ gif
In an equation for ‘main’: main = mainWith $ gif
Where am I going wrong in the code above?
It took me a moment to figure it out, because the error message is not obvious at all, but it's a backend problem. The documentation states that the cairo backend can create animated gif. However, you are using the svg backend (which is unable to understand what [(Diagram B, Int)] is.
To solve this, make sure you have the diagrams-cairo package installed, and change the line
import Diagrams.Backend.SVG.CmdLine
to
import Diagrams.Backend.Cairo.CmdLine
I'll explain the other steps necessary, since this is one of the first search results for doing animations in diagrams. Diagrams rescales the viewport to the image size for each circle, so that circle 1 and circle 2 are equivalent. To solve this you can lay the circles on invisible squares of the same size as circle 2.
Also the delays are given in 1/100 seconds. The correct code would then be:
{-# LANGUAGE NoMonomorphismRestriction #-}
import Diagrams.Backend.Cairo.CmdLine
import Diagrams.Prelude
gif :: [(Diagram B, Int)]
gif = map (\x -> (x # lc white <> square 4 # lw none,300)) [circle 1,circle 2]
main = mainWith gif

how to correctly perform this sequence of matrices multiplications?

This is probably very easy but I can not seem to figure it out. I have attempted to implement a Mahalanobis distance calculation below, but are performing illegal matrix operations (numRows a' andnumCols b' don't match). The calculation should be [1.0, 2.2] * [[0.95,-0.15] [-0.15 0.55]] * [[1.0],[2.2]], and give 2.952 as an answer. Does anybody see what I am going wrong?
import Numeric.Matrix as M
import Data.Maybe
create :: [[Float]] -> Matrix Float
create m = M.fromList m
mahalanobisDistance mu x = (transpose (minus x mu))
`times` (fromJust (M.inv coVarMatrix))
`times` (minus x mu)
where
coVarMatrix = create [[1.1, 0.3], [0.3, 1.9]]
distanceW1 = mahalanobisDistance (create [[1.0], [1.0]])
distanceW2 = mahalanobisDistance (create [[1.5], [1.5]])
main = do
let x = create [[1.0], [2.2]]
print $ distanceW1 x
Your code will work unmodified if you use bed-and-breakfast-0.4.3.
When I used version 0.1.2 I get index out of bounds errors.
However, to get 0.4.3 to compile using GHC 7.10.2 requires some hacking of the source. I can provide the details if you are interested.
build instructions for 0.5
Start with version "0.5" from the github repo:
https://github.com/scravy/bed-and-breakfast
In src/Numeric/Matrix.hs add foldMap to the list of imports to hide from the Prelude:
-import Prelude hiding (any, all, read, map)
+import Prelude hiding (any, all, read, map, foldMap)
Install as usual, e.g. with stack:
stack init && stack install
or with cabal:
cabal install

Dynamically updating a plot in Haskell

I have a program which performs a long-going calculation where the result is shown as a plot.
I am currently using Chart-0.14 for this. I want to show the partial results, and update during calculations.
Graphics.Rendering.Chart.Gtk.updateCanvas :: Renderable a -> DrawingArea -> IO Bool seems to do that, but I do not find any way to get a DrawingArea from the plot. The function renderableToWindow :: Renderable a -> Int -> Int -> IO () does not return anything (and furthermore it does not return before the window is closed).
I would like to do something like the following:
main = do
drawingArea = forkRenderableToWindow (toRenderable $ plotLayout $
plot [0,0.1..10] sin "sin(x)") 640 480
updateCanvas (toRenderable $ plotLayout $ plot [0,0.1..10] sin "sin(x)") drawingArea
How should I do this? Would I need to reimplement the functions in Graphics.Rendering.Chart.Gtk with a version that returns the DrawingArea and in some way (how would I do this? forkIO?) returns immediately without closing the window?
You are looking for createRenderableWindow and then you need to use the GTK operations to work on the given Window - I don't think the Chart package exports any higher level operations on Windows.
EDIT2: So ignore the below - it doesn't work even with GUI initilization. My comment was a guess based on types.
EDIT:
Here is some example code. Understand, I'm just piecing things together based on the types. There might be better ways to do things if you ask someone who actually knows the library.
Below we use:
createRenderableWindow - this was the crux of my answer
castToDrawingArea - This is needed to get a DrawingArea from the Window type provided by GTK. These casts are taking place of C++ OO inheritance, I think.
widgetShowAll - because we haven't actually displayed the window, we best do that. I stole this function after looking at the source for renderableToWindow.
updateCanvas - I just saw this in the haddock documentation and figured it is why you wanted a DrawingArea in the first place.
Now for the code:
import Graphics.Rendering.Chart.Gtk
import Graphics.Rendering.Chart.Renderable
import Graphics.UI.Gtk.Misc.DrawingArea
import qualified Graphics.UI.Gtk as G
main = do
win <- createRenderableWindow emptyRenderable 400 400
let draw = castToDrawingArea win
G.widgetShowAll win
updateCanvas emptyRenderable draw

Resources