Thursday, March 22, 2012

The great CNC project!

About two weeks ago, my good friend Jesse and I got it into our heads that we needed to start building guitars. This isn't a completely uninformed plan; I have built electric guitars before and Jesse has done some custom metalwork for a luthier before. Our plan involves some seriously interesting combinations of metal and woodwork... but more on that later ;)

Rather than sit around hoping that the plan would go somewhere, we decided to be proactive. A CNC is an excellent tool when working on guitars; you can get the rough shape cut, all the major routs done, cut the rough pockets for inlays, as well as the inlay itself. Of course, buying a CNC is not an easy thing (a CNC of any kind of reasonable size is multiple thousands of dollars - $10k+ is not uncommon for a 2'x3' industrial CNC). The obvious solution is for us to build our own CNC...obviously.

Building a CNC at home actually isn't as insane as you would think. Lots of people are doing it. And there are lots of resources. From all I've seen, you can build a quite excellent home CNC machine for well under $1000. We're still early in the process, so I will be posting some updates as we proceed in constructing our machine. So here's the rundown of what we've got so far...

Plans
Rather than making up our own construction or trying to follow some badly organized online plans, we opted to buy a set of plans for home CNC construction. We grabbed the 25"x25" plans from Solsylva, which also come with plans for a 13"x13" engraving CNC (you can use a small trim router or even Dremel, depending on what materials you want to cut) and plans for a 24"x48" CNC. The set of 3 plans runs for $35, and are excellent.






Electronics & Motors
We chose to plan only for a 3-axis machine; that's what the plans we grabbed were made for and a 4th axis doesn't seem very useful without a 5th axis too.

Instead of getting all of the electronics piece by piece and leaving their compatibility up to our own luck, we grabbed a 3-axis driver board kit from HobbyCNC, that includes the board, all electronics (aside from the actual computer you plug into and a transformer) and the stepper motors for each axis.

Man... these motors are just plain awesome. And heavy. 

The rest...
Hopefully, within the next few days, we'll have the structural materials. I'll be updating with more information when we start throwing things together.

The plan is to get this fully operational in the next week or two.

Saturday, January 21, 2012

Loop-like IO actions in Haskell

In the course of writing my imagefilters library for Haskell, I came across the need for loop-like control structures when it came to applying a transformation to every pixel in an image. Given that all of the actions relating to pixel modification are IO monad actions, things are mildly more complicated than if I were just dealing with numbers inside a pure Haskell function.

List Comprehensions?
My first thought was something with list comprehensions... (Note; some of this is pseudo-code-y... those parts are italicized)

  pixelTransform img transformFunction = do  
      (width,height) <- imageSize img  
      [ do   
                get pixel x y
                transformFunction pixel   
                set pixel to new value   
           | x <- [ 0..(imageWidth-1) ], y <- [ 0..(imageHeight-1) ]]   

Makes sense, right? For every combination of x and y, do the series of IO actions required to transform it. Turns out Haskell isn't a fan of IO inside of list comprehensions; you might get it to compile okay (if you spend time wrapping "return" calls around things), but nothing will happen.

'do' Style?
After some research, I found that Haskell supports a monadic form of list comprehension (see the update at the bottom) using do-notation

 do  
      x <- [ 0..10 ]  
      y <- [ 0..10 ]  
      return (x+y)  

Cool Right? that will give us back a list of the sums of all combinations of x and y. If that works, then I should be able to do this, right?

 pixelTransform img transformFunction = do  
      (width,height) <- imageSize img  
      x <- [ 0..(width-1) ]   
      y <- [ 0..(height-1) ]   
      get pixel x y 
      transformFunction pixel   
      set pixel to new value   
      return ()  

Well, no. This doesn't fly either. And when we think about it, it makes sense. 'do' notation is syntactic sugar for constructing monadic actions together with the >>= (bind) operator. The above is the same as doing:

 pixelTransform img transformFunction = return () >>=   
      imageSize img >>=  
      (\(width,height) -> [0..(width-1)] >>=    
      \x -> [0..(height-1) >>=    
      \y -> get pixel x y >>=    
      \pixel -> transformFunction pixel >>=   
      \new value -> set pixel to new value     

That IS kind of ugly looking, but it doesn't show what the problem *really* is until we look at the type signature for >>=

 ghci>:t ( >>= )  
 ( >>= ) :: Monad m => m a -> (a -> m b) -> m b 

Ah. So >>= takes a monad with some type a, a function which takes regular type a and returns a monad with some type b, and then applies that function to the monad with type a, which ends up returning a monad with type b.

Remember: Just because the input is m a, and the output is m b, it does not mean that they are different monads; the m is still there in both of them... it is the same monadic type, but it *may* contain a different type inside of it (if you think of the box analogy - a monad is a box which contains other values). 

If you think about what our previous example is doing, you'll realize that the big issue is that we're trying to use completely different monads together. Applying an IO monad's result to a List monad doesn't make any sense (and vice versa)! So, in order to use multiple Monadic actions together within a do, they either need to be the same type, or they need to be wrapped in calls to return to put them into the right monadic context, but that gets sort of messy. So, what's the easiest way to do what I'm trying to do?

mapM_ saves the day
mapM_ is a function that lives inside the Control.Monad. It's kind of like the regular map that we all know and love, but it's meant for use with monads. About the name of the function - the 'M' stands for the fact that it takes a regular old type value and returns a monad, and the '_' just means that instead of returning m something, it is going to return m (). In our case, that means that the return type of mapM_ is going to be IO ().

Using map makes sense; we know the dimensions of the image (by grabbing the image size), so we can build a list of all combinations of x and y values between 0 and their respective sizes, and then map our transform function over each pixel

So now, the per-pixel transform function becomes this:

 import Control.Monad (mapM_)  

 pixelTransform img transformFunction = do   
      (width,height) <- imageSize img   
      mapM_ (\(x,y) -> do   
                get pixel x y   
                transformFunction pixel   
                set pixel to new value   
           )    
           [ (x,y) | x <- [0..(width-1)], y <- [0..(height-1)] ]

Easy enough; the list comprehension at the end builds a list of tuples representing every possible x,y coordinate in the image and that is the list that we mapM_ over. The function we pass to mapM_ pattern matches the tuple, and then performs our pixel transformation there, then moves on.

As you can see, we used a list comprehension to build the list of x,y pairs. If you are a fan of Applicative Functors (like I am!), you can use the <$> and <*> operators to build the same list to pass to mapM_
 
 import Control.Monad (mapM_)  
 import Control.Applicative  

 pixelTransform img transformFunction = do   
      (width,height) <- imageSize img   
      mapM_ (\(x,y) -> do   
                get pixel x y   
                transformFunction pixel   
                set pixel to new value   
           )    
           $ (,) <$> [0..(width-1)] <*> [0..(height-1)]   

Wrap up
So far, mapM_ has been the best solution that I've found for looping over multidimensional list values with IO () actions, but if anybody else has found other/better/clearer ways of achieving the same results, I'd love to hear them

Update: I've found out that the reason why list comprehensions don't work is the exact same reason why do notation doesn't work; list comprehensions are syntactic sugar for using >>=, so it has the same requirements as a do block, in terms of Monad consistency

Sunday, January 15, 2012

imagefilters (Haskell image filters for GD) v0.1 released

I've just published the first release of my imagefilters package on Hackage. Hopefully some people will find it useful, and I can get some good feedback through the release.

Features
  •  10 image filters
    • Brightness
    • Colorize
    • Contrast
    • Edge Detect
    • Emboss
    • Gaussian Blur
    • Grayscale
    • Invert Color
    • Mean Removal
    • Smoothing
  • Filter utility functions (for custom filters)
    • pixelTransform - for applying per-pixel color adjustments 
    • convolute - for applying convolution matrices. This is used for many of the more "complicated" filters, like Emboss and Gaussian blur
What's missing
  • No pixelate filter, yet
  • No selective blur yet either
  • Filters are only compatible with the GD plugin; I would like to include filters that are compatible with other common imaging plugins
  • The code probably needs some better error handling and also some optimization/cleanup