<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Overfloater &#187; ocaml</title>
	<atom:link href="http://blog.thejit.org/category/ocaml/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.thejit.org</link>
	<description>Data Visualization, JavaScript and Computer Science related stuff</description>
	<lastBuildDate>Sun, 18 Jul 2010 13:38:10 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using OCaml to visualize Radiohead&#8217;s HoC music video (part 3)</title>
		<link>http://blog.thejit.org/2008/12/06/using-ocaml-to-visualize-radioheads-hoc-music-video-part-3/</link>
		<comments>http://blog.thejit.org/2008/12/06/using-ocaml-to-visualize-radioheads-hoc-music-video-part-3/#comments</comments>
		<pubDate>Sat, 06 Dec 2008 17:11:32 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[hoc]]></category>
		<category><![CDATA[ocaml]]></category>
		<category><![CDATA[visualization]]></category>
		<category><![CDATA[ocaml visualization opengl radiohead]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=156</guid>
		<description><![CDATA[Update 10/2009: The project is currently hosted at GitHub.
Update 01/2009: Created a new hoc3.zip file and some documentation.
A while ago Radiohead published their House of Cards video data in form of CSV files. Each CSV file contains information about the 3D position of the points for each frame.
I wrote a couple of previous posts that [...]]]></description>
			<content:encoded><![CDATA[<p><em>Update 10/2009:</em> The project is currently hosted at <a href="http://github.com/philogb/hoc">GitHub</a>.<br />
<em>Update 01/2009:</em> Created a new hoc3.zip file and some <a href="/wp-content/hoc/doc/index.html">documentation</a>.</p>
<p>A while ago Radiohead <a href="http://code.google.com/creative/radiohead/#data-visualization" target="_blank">published</a> their <em>House of Cards</em> video data in form of CSV files. Each CSV file contains information about the 3D position of the points for each frame.</p>
<p>I wrote a couple of previous posts that covered  <a href="http://blog.thejit.org/2008/11/27/using-ocaml-to-visualize-radioheads-hoc-music-video-part-1/">how to render and save that data with OpenGL and OCaml</a> and also <a href="http://blog.thejit.org/2008/12/02/using-ocaml-to-visualize-radioheads-hoc-music-video-part-2/">how to customize camera movement in OpenGL</a>.</p>
<p>This post shows how to customize particle animations for Radiohead&#8217;s House of Cards video.<br />
A proof of concept for camera movement + particle animation is shown in this youtube video:</p>
<p><object width="500" height="344" data="http://www.youtube.com/v/ZRqKIljnvd4&amp;hl=en&amp;fs=1&amp;rel=0&amp;color1=0x3a3a3a&amp;color2=0x999999" type="application/x-shockwave-flash"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/ZRqKIljnvd4&amp;hl=en&amp;fs=1&amp;rel=0&amp;color1=0x3a3a3a&amp;color2=0x999999" /><param name="allowfullscreen" value="true" /></object></p>
<p>If you want to generate the video, you have to download Radiohead&#8217;s HoC music video data <a href="http://code.google.com/creative/radiohead/#data-visualization" target="_blank">here</a>. Also, you can download the source code for this project <a href="/wp-content/hoc3.zip" target="_blank">here</a>.</p>
<p>This small project is organized in a way that is easy to add new features, camera animations and particle transformations in order to easily code new videos with different effects using the HoC data.</p>
<p>Radiohead&#8217;s HoC data is a set of CSV files. Those files are rendered in OpenGL with OCaml and then saved in <em>bmp</em> or <em>jpeg</em> files to be merged into a video using <em>ffmpeg</em>. If you want to know more about this you should probably read <a href="http://blog.thejit.org/2008/11/27/using-ocaml-to-visualize-radioheads-hoc-music-video-part-1/">part 1</a> of this &#8220;trilogy&#8221;.</p>
<p>The <em>Camera Model</em> class allows you to make custom camera movements that can be handled and defined in a <em>Timeline</em> object in the <em>main.ml</em> file. If you like to know more about this, you can read <a href="http://blog.thejit.org/2008/12/02/using-ocaml-to-visualize-radioheads-hoc-music-video-part-2/">part 2</a> of this &#8220;trilogy&#8221;.</p>
<p>This last post shows how to customize particle interpolation and movement by using the <em>Particle Model</em> class, the <em>ParticleTrans</em> module and the <em>Timeline</em> object.</p>
<h4>Particle Model</h4>
<p>The <em>particle_model</em> class handles particle animations.<br />
Somewhat like the camera class, <em>particle_model</em> stores the initial frame and the last frame along with some extra information about the timing of the animation.<br />
The <em>particle_model</em> then performs an interpolation from the initial_frame to the last_frame, rendering the state of the transformation in the <em>draw</em> function.</p>
<p>A possible interface for the particle model could be something like this:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">class particle_model :
  object
    (* starting frame *)
    val mutable start_frame : VertexType.depth_vertex list
    (* ending frame *)
    val mutable last_frame : VertexType.depth_vertex list
    (* currently loaded frame *)
    val mutable loaded_frame : VertexType.depth_vertex list
    (* if setted to true, it will load a new frame for each
    step of the animation *)
    val mutable refresh_frames : bool
    (* same as the camera_model -check that post *)
    val mutable time : float
    val mutable total_frames : float
    val mutable transition : Transition.trans * Transition.ease
    (* extend start_frame or last_frame in order to
    have same number of points *)
    method balance : unit
    (* equivalent to the camera methods *)
    method step : unit
    method draw : float -&gt; unit
    (* set the type of the animation you want
    to perform *)
    method set_animation :
      float -&gt;
      bool * bool *
      (ParticleTrans.transformation * float *
       (Transition.trans * Transition.ease)) -&gt;
      unit
  end</pre>
<p>Particle animations have a special type, that ressembles the camera model transition type.<br />
This type is defined as follows:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">type animation_op =
    ParticleTrans.transformation * float *
    (Transition.trans * Transition.ease)</pre>
<p>Just to make a comparison, the camera model transition type is:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
type camera_op_list = (camera_op list) * float * (trans * ease)</pre>
<p>This type can be divided into three main parts:</p>
<ul>
<li> The <em>float</em> value is the total number of frames the animation will use.</li>
<li> The (trans * ease) value allows you to customize different type of transitions, from <em>Linear, None</em> to <em>Quad, EaseInOut</em>. More information about this is in the <em>camera_model</em> post.</li>
<li> <em>ParticleTrans.transformation</em> is a function that applies a transformation to a frame. You can define custom functions in that module and then apply them to the visualization.<br />
I only defined a couple of functions, but you can define any other animation you like. You just have to define a function that receives a frame as input and returns a frame as output.<br />
The interface for ParticleTrans is:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">type transformation =
	| Idle
	| Project of float * float * float
	| Random

val idle : 'a -&gt; 'a

val project :
  transformation -&gt;
  VertexType.depth_vertex list -&gt;
	VertexType.depth_vertex list

val random : VertexType.depth_vertex list -&gt;
	VertexType.depth_vertex list

val get_trans :
  transformation -&gt;
  VertexType.depth_vertex list -&gt;
	VertexType.depth_vertex list</pre>
</li>
</ul>
<h4>Putting it all together</h4>
<p>The timeline object (described in the <a href="http://blog.thejit.org/2008/12/02/using-ocaml-to-visualize-radioheads-hoc-music-video-part-2/">previous post</a>) holds information about the camera and particle transformations beeing applied at each stage of the animation.<br />
This class-less object is defined in the main.ml file and looks like this:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">let timeline =
  object (self)
    val mutable frame = 0.
    val camera_timeline = [
    (* operations defined in the
    camera model post *)
    ]

    val particle_timeline = [
      (* frame number,  (invert, refresh frames, instruction) *)
      (1., (true, true, (Random, 120., (Elastic, EaseOut))));
      (420., (false, false, (Random, 50., (Quad, EaseOut))));
      (471., (false, true, (Idle, 80., (Quad, EaseIn))))
      ]

    method get_frame = frame

    method tick =
      frame &lt;- frame +. 1.;
      self#update_camera;
      self#update_animation

    method update_camera =
      try
        let camera_anim = List.assoc frame camera_timeline in
          cam#set_animations camera_anim;
        with
          | Not_found -&gt; ()

    method update_animation =
      try
        let anim = List.assoc frame particle_timeline in
          part#set_animation frame anim;
      with
          | Not_found -&gt; ()
end</pre>
<p>The <em>particle_timeline</em> and <em>camera_timeline</em> variables hold the transformations to be performed at different stages of the animation.</p>
<h4>Download and Use</h4>
<p>You can download the project <a href="/wp-content/hoc3.zip" target="_blank">here</a>.<br />
You can compile the project by typing:</p>
<pre class="ocaml-pre">ocamlc -g str.cma -I +camlimages ci_core.cma ci_jpeg.cma ci_bmp.cma
-I +lablGL lablglut.cma lablgl.cma interpolate.ml transition.ml camera.ml
 loader.ml particleTrans.ml particle.ml main.ml -o main</pre>
<p>Any comment about the Video or the OpenGL/OCaml implementation is very welcome!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2008/12/06/using-ocaml-to-visualize-radioheads-hoc-music-video-part-3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using OCaml to visualize Radiohead&#8217;s HoC music video (part 2)</title>
		<link>http://blog.thejit.org/2008/12/02/using-ocaml-to-visualize-radioheads-hoc-music-video-part-2/</link>
		<comments>http://blog.thejit.org/2008/12/02/using-ocaml-to-visualize-radioheads-hoc-music-video-part-2/#comments</comments>
		<pubDate>Tue, 02 Dec 2008 00:44:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[hoc]]></category>
		<category><![CDATA[ocaml]]></category>
		<category><![CDATA[visualization]]></category>
		<category><![CDATA[opengl]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=109</guid>
		<description><![CDATA[This post is about performing advanced camera movement in OpenGL.
We&#8217;ll use the same Radiohead&#8217;s HoC dataset we used in the previous post.
Once again, the quality of the youtube video is pretty lame. You can right click here and save link as&#8230; to download a high quality version of the video (~100MB).
I strongly recommend you to [...]]]></description>
			<content:encoded><![CDATA[<p>This post is about performing advanced camera movement in OpenGL.<br />
We&#8217;ll use the same Radiohead&#8217;s HoC dataset we used in the <a href="http://blog.thejit.org/2008/11/27/using-ocaml-to-visualize-radioheads-hoc-music-video-part-1/">previous post</a>.</p>
<p>Once again, the quality of the youtube video is pretty lame. You can right click <a href="/wp-content/static/img/hoc2.mpg">here</a> and <em>save link as&#8230;</em> to download a high quality version of the video (~100MB).<br />
I <b>strongly recommend</b> you to see the high quality video <img src='http://blog.thejit.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><object width="500" height="344"><param name="movie" value="http://www.youtube.com/v/UEJqrmEWV-Q&#038;hl=en&#038;fs=1&#038;rel=0&#038;color1=0x3a3a3a&#038;color2=0x999999"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/UEJqrmEWV-Q&#038;hl=en&#038;fs=1&#038;rel=0&#038;color1=0x3a3a3a&#038;color2=0x999999" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="500" height="344"></embed></object></p>
<h4>Camera Instructions</h4>
<p>Camera movement is made of Translations and/or Rotations.<br />
We want to provide our camera model with instructions of the type:</p>
<ul>
<li><b>[ Translate <em>from</em> <em>to</em> ]</b></li>
<li><b>[ Rotate <em>from</em> <em>to</em> <em>rotation_axis</em> ]</b></li>
<li><b>[ Translate ...; Rotate ... ]</b></li>
</ul>
<p>As the last example shows, multiple transformations can be done at the same time (translations and rotations).</p>
<p>The definition for a transformation type is:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
type camera_op =
  | Translate of Gl.point3 * Gl.point3
  | Rotate of float * float * Gl.vect3
</pre>
<p>A camera instruction is a list of these operations (<em>camera_op</em>) and a number specifying the number of frames this transformation should take (i.e the duration of the transformation).</p>
<p>So, for example, this instruction:<br />
<b>( [ Translate( (100., 100., 100.), (0., 0., 0.) ) ], 300. )</b><br />
translates the camera from (100, 100, 100) to (0, 0, 0) in 300 frames, that is in 10 seconds (at 30 frames per second).</p>
<p>Translation is done by simple interpolation. The interpolation formula for translating from <b>A</b> to <b>B</b> is something like this:<br />
<b>A + (B &#8211; A) * delta</b> with <b>delta</b> in (0, 1).</p>
<h4>Transitions</h4>
<p>It would be nice if camera movement, besides being linear, could also perform other advanced transitions, like the ones used in <a href="http://docs111.mootools.net/Effects/Fx-Transitions.js#Fx.Transitions.linear">Fx.Transitions</a> by Mootools.<br />
Some of these transitions are: Quadratic, EaseIn, EaseOut, EaseInOut, Back, Sine, etc&#8230;</p>
<p>These effects are achieved by applying functions to the <b>delta</b> value, changing the way it increases or descreases its value.<br />
A possible interface for a Transition module is:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
type trans = Linear | Quart
type ease = None | EaseOut | EaseIn | EaseInOut

val linear : 'a -> 'a
val quart : float -> float

val ease_in : ('a -> 'b) -> 'a -> 'b
val ease_out : (float -> float) -> float -> float
val ease_in_out : (float -> float) -> float -> float

val get_transition : trans -> float -> float
val get_ease : ease -> (float -> float) -> float -> float

val get_animation : trans -> ease -> float -> float
</pre>
<p>By using <b>Transition.get_animation Quad EaseInOut delta</b> we can change the timing of our animation from this:<br />
<img src="/wp-content/static/img/Linear.png" style="margin-left:30px;" /></p>
<p>into this:<br />
<img src="/wp-content/static/img/Quad.png" style="margin-left:30px;" /></p>
<p>Our camera instructions are then defined as:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">

type camera_op_list = (camera_op list) * float * (trans * ease)
</pre>
<p>For example:<br />
<b>( [ Translate( (100., 100., 100.), (0., 0., 0.) ) ], 300. (Quad, EaseOut))</b></p>
<h4>The Camera Model</h4>
<p>A possible interface for the camera model is:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
class camera_model :
  object
    val mutable animations : camera_op list
    val mutable time : float
    val mutable total_frames : float
    val mutable transition : Transition.trans * Transition.ease

    method get_time : float
    method step : unit
    method draw : unit
    method translate : Gl.point3 -> Gl.point3 -> float -> unit
    method rotate : float -> float -> Gl.vect3 -> float -> unit
    method set_animations :
      camera_op list * float * (trans * ease) -> unit
  end
</pre>
<p>The camera_model instance variables contain the destructured <em>camera_op_list</em> type elements: <em>animations</em>, <em>total_frames</em> and <em>transition</em>.<br />
We also provide individual methods for handling translations and rotations. These methods simply compute a delta value, apply the interpolation and then call <em>GlMat.translate3</em> or <em>GlMat.rotate3</em>.</p>
<p>The 40 line implementation looks like this:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
class camera_model =
 object (self)
  val mutable total_frames = 0.
  val mutable time = 0.
  val mutable transition = (Linear, None)
  val mutable animations = []

  method get_time = time

  method set_animations ans =
    let (x, y, z) = ans in
      animations <- x;
      total_frames <- y;
      transition <- z;
      time <- 0.

  method step =
    if time < total_frames then
      time <- time +. 1.

  method translate start last delta =
    let (trans, ease) = transition in
    let delta_val = Transition.get_animation trans ease delta in
    let (x, y, z) = start in
    let (x', y', z') = last in
    let DVertex(a, b, c, d) = Interpolate.cartesian
                                (DVertex(x, y, z, 0.))
                                (DVertex(x', y', z', 0.))
                                delta_val
    in
      GlMat.translate3 (a, b, c)

  method rotate start last vec delta =
    let (trans, ease) = transition in
    let delta_val = Transition.get_animation trans ease delta in
    let ang = Interpolate.cartesian_float start last delta_val in
    GlMat.rotate3 ang vec 

    method draw =
      let delta = time /. total_frames in
        List.iter (fun anim ->
          match anim with
            | Translate(start, last) ->
               self#translate start last delta
            | Rotate(start, last, vec) ->
               self#rotate start last vec delta ) animations
end
</pre>
<h4>Timeline</h4>
<p>Now that we have our camera model, we need a &#8220;timeline&#8221; object that can pass intructions to the camera at different stages of the animation.<br />
We define a class-less object <em>timeline</em> that holds a list of camera transformations to be executed at a specific frame of the animation:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
let timeline =
  object (self)
    val mutable frame = 0.
    (* Starting frame number, camera_instructions *)
    val camera_timeline = [
      (1.,   (* camera_instructions *));
      (310., (* camera_instructions *));
      (631., (* camera_instructions *) ]

    method get_frame = frame

    method tick =
      frame <- frame +. 1.;
      self#update_camera;

    method update_camera =
      try
        let camera_anim = List.assoc frame camera_timeline in
          cam#set_animations camera_anim;
        with
          | Not_found -> ()
end
</pre>
<h4>Download and Use</h4>
<p>This is all I&#8217;ve done to handle camera movement.<br />
I&#8217;m not an advanced OpenGL/OCaml developer, so any comment/suggestion about my understanding of OCaml/OpenGL is very welcome.<br />
You can download the source <a href="/wp-content/hoc2.zip" target="_blank">here</a>.<br />
You can compile the source with:</p>
<pre name="ocaml" class="ocaml-pre">
ocamlc -g str.cma -I +camlimages ci_core.cma ci_jpeg.cma ci_bmp.cma
-I +lablGL lablglut.cma lablgl.cma interpolate.ml transition.ml
camera.ml loader.ml main.ml -o main
</pre>
<p>Last part of this &#8220;trilogy&#8221; will be about particle transformations in OpenGL.<br />
Hope you enjoyed it!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2008/12/02/using-ocaml-to-visualize-radioheads-hoc-music-video-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using OCaml to visualize Radiohead&#8217;s HoC music video (part 1)</title>
		<link>http://blog.thejit.org/2008/11/27/using-ocaml-to-visualize-radioheads-hoc-music-video-part-1/</link>
		<comments>http://blog.thejit.org/2008/11/27/using-ocaml-to-visualize-radioheads-hoc-music-video-part-1/#comments</comments>
		<pubDate>Thu, 27 Nov 2008 15:22:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[hoc]]></category>
		<category><![CDATA[ocaml]]></category>
		<category><![CDATA[visualization]]></category>
		<category><![CDATA[opengl]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=49</guid>
		<description><![CDATA[So I was looking for some excuse to learn OCaml + OpenGL, and I run into Radiohead&#8217;s House of Cards video dataset hosted at google code.
The dataset is made of many CSV files, one for each frame of the HoC video.
The data is also shipped with an application that uses Processing to create an image [...]]]></description>
			<content:encoded><![CDATA[<p>So I was looking for some excuse to learn OCaml + OpenGL, and I run into Radiohead&#8217;s House of Cards video dataset hosted at <a href="http://code.google.com/p/radiohead/downloads/list" target="_blank">google code</a>.<br />
The dataset is made of many CSV files, one for each frame of the HoC video.<br />
The data is also shipped with an application that uses <a href="http://processing.org/" target="_blank">Processing</a> to create an image for each frame of the video.</p>
<p>I decided to do the same program in OCaml + OpenGL: for each CSV file, the program loads it, renders it in OpenGL, and then saves that rendered data into a jpg (or bmp) image.</p>
<p>You can merge the generated image frames with the sample mp3 provided at google code, by using <b>ffmpeg</b>: </p>
<pre name="ocaml" class="ocaml-pre">
ffmpeg -f image2 -r 30 -i ./img%d.jpg -sameq -i 1.mp3 ./out.mpeg -pass 2
</pre>
<p>Anyway, the result is quite interesting, and it gives us a good ground to build better visualizations:</p>
<p>(This youtube video quality is pretty lame, I&#8217;d recommend you to right click <a href="/wp-content/static/img/hoc.mpeg">here</a> and <em>save link as&#8230;</em>).<br />
<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/4M4578jg8rI&#038;hl=en&#038;fs=1&#038;rel=0&#038;color1=0x3a3a3a&#038;color2=0x999999"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/4M4578jg8rI&#038;hl=en&#038;fs=1&#038;rel=0&#038;color1=0x3a3a3a&#038;color2=0x999999" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></p>
<div style="clear:both"></div>
<p>This post is going to be about the making of this simple application.<br />
Further posts on this &#8220;project&#8221; will cover advanced camera movement and particle transformations.</p>
<h4>The Code</h4>
<p>This app was made in one single file, but it contains two important parts:</p>
<p>A <em>data</em> object containing information about the location of the CSV and generated image files, along with some methods to load CSV files and save OpenGL rendered pictures into image files (bmp and jpeg formats).<br />
This object uses <a href="http://pauillac.inria.fr/camlimages/" target="_blank">camlimages</a> for saving images in different formats, and the OpenGL/GLUT bindings provided by <a href="http://wwwfun.kurims.kyoto-u.ac.jp/soft/lsl/lablgl.html" target="_blank">lablGL</a>.</p>
<pre name="code" class="ocaml:nogutter">
(* Loads csv frames and saves the rendered OpenGL image *)
let data =
  object (self)
    val path_to_file = "path_to_folder_containing_csv_files"
    val path_to_image_file = "path_to_folder_that_will_contain_imgs"
    val mutable current_frame = 1
    val total_frames = 2101
    val time_interval = 33

    method get_time_interval =   time_interval

    method load_file filename =
      let channel = open_in (path_to_file ^ filename) in
      let ans = ref [] in
        try
          while true do
            let line = input_line channel in
            let sp = split (regexp ",")
                        (sub line 0 (pred (length line))) in
            match List.map float_of_string sp with
              | [ x; y; z; d ] ->
                ans := DVertex (x, y, z, d) :: !ans
              | _ -> raise (Invalid_argument "not a depth vertex")
          done;
          !ans
        with End_of_file | Invalid_argument _ ->
                 close_in_noerr channel; !ans

    method save_image =
        let img_rgb = new OImages.rgb24 600 400 in
        let pixels = GlPix.read
          ~x:0 ~y:0
          ~width:600 ~height:400
          ~format:`rgb ~kind:`ubyte
        in
        let praw = GlPix.to_raw pixels in
        let raw = Raw.gets ~pos:0 ~len:(Raw.byte_size praw) praw in
        let w = GlPix.width pixels in
        let h = GlPix.height pixels in
        for i = 0 to pred (w * h) do
          let color_rgb = { r = raw.(i * 3 + 2);
                                  g = raw.(i * 3 + 1);
                                  b = raw.(i * 3 + 0) }
          in
            img_rgb#set (i mod w) (i / w) color_rgb;
        done;
        img_rgb#save (path_to_image_file ^ "img" ^ (string_of_int current_frame) ^ ".jpg")
                              None []

    method next_frame =
      current_frame <- (current_frame + 1) mod total_frames;
      if current_frame = 0 then
        current_frame <- total_frames;
      self#load_file ((string_of_int current_frame) ^ ".csv")
end
</pre>
<p>This object is included in the <em>main.ml</em> file, which is the main entry point for the OpenGL application.<br />
This file defines functions for initializing and binding events to the main openGL app. You'll find this code familiar if you know some OpenGL.</p>
<pre name="code" class="ocaml:nogutter">
open Str
open String
open Color
open VertexType

(* Initializes openGL scene components*)
let init width height =
    GlDraw.shade_model `smooth;
    GlClear.color (0.0, 0.0, 0.0);
    GlClear.depth 1.0;
    GlClear.clear [`color; `depth];
    Gl.enable `depth_test;
    GlFunc.depth_func `lequal;
    GlMisc.hint `perspective_correction `nicest

(*  Draws the image*)
let draw () =
  GlClear.clear [`color; `depth];
  GlMat.load_identity ();
  GlMat.translate3 (-150.0, -150.0, -400.0);
  GlDraw.begins `points;
  List.iter (fun (DVertex (x, y, z, d)) ->
    let color = d /. 255. in
      GlDraw.color (color, color, color);
      GlDraw.vertex ~x:x ~y:y ~z:z ()) data#next_frame;
  GlDraw.ends ();
  Glut.swapBuffers ();
  data#save_image

(* Handle window resize *)
let reshape_cb ~w ~h =
  let
    ratio = (float_of_int w) /. (float_of_int h)
  in
    GlDraw.viewport 0 0 w h;
    GlMat.mode `projection;
    GlMat.load_identity ();
    GluMat.perspective 45.0 ratio (0.1, 1300.0);
    GlMat.mode `modelview;
    GlMat.load_identity ()

(* Handle keyboard events *)
let keyboard_cb ~key ~x ~y =
  match key with
    | 27 (* ESC *) -> exit 0
    | _ -> ()

(* A timer function setted to draw a new frame each time_interval ms *)
let rec timer value =
  Glut.postRedisplay ();
  Glut.timerFunc ~ms:data#get_time_interval
                 ~cb:(fun ~value:x -> (timer x))
                 ~value:value

(*  Main program function*)
let main () =
  let
    width = 640 and
    height = 480
  in
    ignore (Glut.init Sys.argv);
    Glut.initDisplayMode ~alpha:true ~depth:true ~double_buffer:true ();
    Glut.initWindowSize width height;
    ignore (Glut.createWindow "Radiohead HoC");
    Glut.displayFunc draw;
    Glut.keyboardFunc keyboard_cb;
    Glut.reshapeFunc reshape_cb;
    Glut.timerFunc ~ms:data#get_time_interval
                   ~cb:(fun ~value:x -> (timer x))
                   ~value:1;
    init width height;
    Glut.mainLoop ()

let _ = main ()
</pre>
<p>You can download the source <a href="/wp-content/hoc1.zip" target="_blank">here</a>.<br />
You can compile the files with the bytecode compiler:</p>
<pre name="ocaml" class="ocaml-pre">
ocamlc -g str.cma -I +camlimages ci_core.cma ci_bmp.cma ci_jpeg.cma
-I +lablGL lablglut.cma lablgl.cma main.ml -o main
</pre>
<p>.<br />
Just remember that you have to install OCaml + lablGL + camlimages to be able to use this.</p>
<p>Any comment about the code will be well appreciated, since I'm an OCaml beginner <img src='http://blog.thejit.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  .</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2008/11/27/using-ocaml-to-visualize-radioheads-hoc-music-video-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
<enclosure url="http://blog.thejit.org/wp-content/static/img/hoc.mpeg" length="49025024" type="video/mpeg" />
		</item>
		<item>
		<title>Memoization in JavaScript</title>
		<link>http://blog.thejit.org/2008/09/05/memoization-in-javascript/</link>
		<comments>http://blog.thejit.org/2008/09/05/memoization-in-javascript/#comments</comments>
		<pubDate>Fri, 05 Sep 2008 19:08:59 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[ocaml]]></category>
		<category><![CDATA[memoization]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=27</guid>
		<description><![CDATA[While reading Jason Hickey&#8217;s Introduction to Objectve Caml I ran into some memoization examples that I found pretty interesting, and I wondered how memoization could be used/implemented in JavaScript.
What is memoization?
Memoization is a technique that uses side-effects to improve -at runtime- the performance of a function without altering its behavior. Roughly speaking, you can do [...]]]></description>
			<content:encoded><![CDATA[<p>While reading Jason Hickey&#8217;s <em>Introduction to Objectve Caml</em> I ran into some <em>memoization</em> examples that I found pretty interesting, and I wondered how memoization could be used/implemented in JavaScript.</p>
<p><b>What is memoization?</b><br />
Memoization is a technique that uses side-effects to improve -at runtime- the performance of a function without altering its behavior. Roughly speaking, you can do <em>memoization</em> by storing function values that were returned in previous calls, and returning these values in further calls to the function instead of actually calling the function.</p>
<p><b>Where can I use memoization?</b><br />
Not all functions can be memoized. In particular, <em>pure</em> functions can be memoized.<br />
A function is said to be <em>pure</em> when it behaves in a predictable way, in the sense that for each <em>x</em>, the function will always return the same associated <em>y</em> value (i.e a single-valued map).</p>
<p>An example of a function that can be memoized is:</p>
<pre name="code" class="js:nocontrols:nogutter">
function square(x) {
     return x * x;
}
</pre>
<p>An example of a function that <em>can&#8217;t</em> be memoized could be:</p>
<pre name="code" class="js:nogutter:nocontrols">
var index = 1;
function not_mem(x) {
     index = index + 1;
     return x + index;
}
</pre>
<p>By introducing <em>side-effects</em> we alter the inner state of the function, having different return values for the same input. In this particular case, one could say that <em>not_mem(0) != not_mem(0)</em> is always true!</p>
<p><b>A somewhat generic way to do memoization</b><br />
In OCaml we can define a higher order function <em>memo</em> that takes a function <b>f</b> as parameter and returns a memoized function that is perhaps faster than the input function.</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
   let memo f =
      let table = ref [] in
      let rec find_or_apply entries x =
         match entries with
            (x’, y) :: _ when x’ = x -> y
          | _ :: entries -> find_or_apply entries x
          | [] ->
             let y = f x in
             table := (x, y) :: !table;
             y
      in
      (fun x -> find_or_apply !table x)
</pre>
<p>We can see that the <em>memo</em> function has a <em>table</em> structure where it stores the <em>f</em> function results as <em>(x, y)</em> pairs. For each call to the memoized <em>f</em> function, <em>memo</em> will search in the <em>table</em> structure for an <em>(x, y)</em> pair that matches in <em>x</em> the input value. If found, it will return the associated <em>y</em> value:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
         match entries with
            (x’, y) :: _ when x’ = x -> y
</pre>
<p>If not found, it will partially apply <em>x</em> to the original <em>f</em> function, and store the result in <em>table</em> as an <em>(x, y)</em> pair, to be used on further calls. It will finally return the computed value just as the orginial <em>f</em> function would have done:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
             let y = f x in
             table := (x, y) :: !table;
             y
</pre>
<p>A simple timing shows the performance improvements on further calls for the memoized fibonacci <em>memo_fib</em> function:</p>
<pre name="ocaml" class="ocaml-pre">
#  time memo_fib 40;;
Elapsed time: 14.581937 seconds
- : int = 102334155
# time memo_fib 40;;
Elapsed time: 0.000009 seconds
- : int = 102334155
</pre>
<p><b>Achieving the same thing in JavaScript</b><br />
For unary functions a simple definition of memo could be:</p>
<pre name="code" class="js:nogutter">
function memo(f) {
  return function (x) {
      f.memo = f.memo || {};
      return (x in f.memo)? f.memo[x] : f.memo[x] = f(x);
  };
}
</pre>
<p>A couple of differences to notice for this version and the OCaml version are:</p>
<ul>
<li>
I&#8217;m not using a list of <em>(x, y)</em> pairs. Instead, I&#8217;m using a hashtable (or object) <em>{}</em>. This way, response time for the memoized function will not be proportional to the <em>f</em> function domain (as opposed to the OCaml <em>memo</em> function implementation).</p>
</li>
<li>
I&#8217;m not using a local <em>table</em> variable to store previous calls. Instead, I&#8217;m using a property of the <em>f</em> function, <em>f.memo</em>.
</li>
<li>
In this particular case, the JS <em>memo</em> function behaves like the OCaml <em>memo</em> function for unary functions, since <em>let y = f x</em> for unary functions will evaluate <em>f</em> as opposed to currying the function. However, for (n > 1)-ary functions the OCaml version will return a curried function when called with less formal parameters than &#8220;expected&#8221;.
</li>
</ul>
<p>Lets do some profiling. For this I&#8217;ll be using the <em>console.time</em> and <em>console.timeEnd</em> firebug methods:</p>
<pre name="code" class="js:nogutter">
function memo(f) {
  return function (x) {
      f.memo = f.memo || {};
      return (x in f.memo)? f.memo[x] : f.memo[x] = f(x);
  };
}

function fib(x) {
    if(x < 2) return 1; else return fib(x-1) + fib(x-2);
}

var memo_fib = memo(fib);
//first call
console.time("first call");
console.log(memo_fib(30));
console.timeEnd("first call");

//console will output:
//first call: 17264ms
//1346269

//second call (memoized)
console.time("memoized call");
console.log(memo_fib(30));
console.timeEnd("memoized call");

//console will output:
//memoized call: 4ms
//1346269
</pre>
<p><b>Beyond unary functions memoization in JavaScript</b><br />
The Ocaml and JavaScript versions of <em>memo</em> lack support for (n>1)-ary functions.<br />
If the OCaml <em>memo</em> function is applied to a binary function, it will only memoize the first partial application for this function.</p>
<p>Lets define a function sum_fib and memo_sum_fib:</p>
<pre name="ocaml" class="ocaml-pre">
# let sum_fib a b = (fib a) + (fib b);;
<em>val sum_fib : int -> int -> int = &lt;fun></em>
# let memo_sum_fib = memo sum_fib;;
<em>val memo_sum_fib : int -> int -> int = &lt;fun></em>
</pre>
<p>Timing the memoized function might lead to some unexpected results:</p>
<pre name="ocaml" class="ocaml-pre">
# time memo_sum_fib 30 40;;
Elapsed time: 18.753172 seconds
- : int = 166926410
# time memo_sum_fib 30 40;;
Elapsed time: 18.753172 seconds
- : int = 166926410
</pre>
<p>This problem happens because the memoization happens at the first partial application level. That means that the <em>table</em> structure will hold (int, int -> int) elements, as opposed of a mapping from a pair of formal parameters to the returned value: (int * int, int).</p>
<p>In JavaScript we have a bigger problem. Since partial application is not a "natural" feature of the language and the memo function is not designed to handle n-ary functions, this will lead to an error or unexpected results. At least the OCaml version returned the expected values <img src='http://blog.thejit.org/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> . </p>
<p>In JavaScript we can solve this problem by using the <em>arguments</em> object as the key to our <em>f.memo</em> hashtable. Our new <em>memo</em> function would now look like this:</p>
<pre name="code" class="js:nogutter">
function memo(f) {
  return function () {
      var args = Array.prototype.slice.call(arguments);
      f.memo = f.memo || {};
      return (args in f.memo)? f.memo[args] :
                     f.memo[args] = f.apply(this, args);
  };
}
</pre>
<p>Not only this function supports n-ary functions to be memoized, but also it performs a correct memoization, in the sense that it will store all formal parameters in <em>f.memo</em>, as the key to the value returned by this function. </p>
<p>Lets do some profiling!</p>
<pre name="code" class="js:nogutter">
function memo(f) {
  return function () {
      var args = Array.prototype.slice.call(arguments);
      f.memo = f.memo || {};
      return (args in f.memo)? f.memo[args] :
                     f.memo[args] = f.apply(this, args);
  };
}

function fib(x) {
    if(x < 2) return 1; else return fib(x-1) + fib(x-2);
}

function sum_fib(a, b) {
    return fib(a) + fib(b);
}

var memo_sum_fib = memo(sum_fib);
console.time("first call");
console.log(memo_sum_fib(20, 30));
console.timeEnd("first call");

//console will output:
//first call: 17165ms
//1357215

console.time("memoized call");
console.log(memo_sum_fib(20, 30));
console.timeEnd("memoized call");

//console will output:
//memoized call: 5ms
//1357215
</pre>
<p>Finally, a nice trick you can do is to call the memoized function the same a the function passed in as a formal parameter. Repeating the last example will show a lot of improvements!</p>
<pre name="code" class="js:nogutter">
function memo(f) {
  return function (x) {
      f.memo = f.memo || {};
      return (x in f.memo)? f.memo[x] : f.memo[x] = f(x);
  };
}

function fib(x) {
    if(x < 2) return 1; else return fib(x-1) + fib(x-2);
}

var fib = memo(fib);
//first call
console.time("first call");
console.log(fib(30));
console.timeEnd("first call");

//console will output:
//first call: 7ms
//1346269

//second call (memoized)
console.time("memoized call");
console.log(fib(30));
console.timeEnd("memoized call");

//console will output:
//memoized call: 5ms
//1346269
</pre>
<p>Any critique or comment will be well appreciated.<br />
Bye!.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2008/09/05/memoization-in-javascript/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Pattern matching in OCaml (and JavaScript?)</title>
		<link>http://blog.thejit.org/2008/08/11/pattern-matching-in-ocaml-and-javascript/</link>
		<comments>http://blog.thejit.org/2008/08/11/pattern-matching-in-ocaml-and-javascript/#comments</comments>
		<pubDate>Mon, 11 Aug 2008 18:05:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[ocaml]]></category>
		<category><![CDATA[pattern matching]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=26</guid>
		<description><![CDATA[I&#8217;ve been trying to learn OCaml lately.
I want to try information visualization for the &#8220;dektop&#8221; (as opposed to the web), and although I know C++ or Java would be recommended languages for this kind of thing (they have lots of libraries and pretty large communities regarding visualization in general -think about games, OpenGL, etc), I [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been trying to learn OCaml lately.<br />
I want to try information visualization for the &#8220;dektop&#8221; (as opposed to the web), and although I know C++ or Java would be recommended languages for this kind of thing (they have lots of libraries and pretty large communities regarding visualization in general -think about games, OpenGL, etc), I wouldn&#8217;t feel very comfortable doing geometric computation in C++ or Java.<br />
Although geometric computation often handles objects, there&#8217;s also the &#8220;functional side&#8221; of it that doesn&#8217;t seem to be fulfilled by C++ or Java. Ocaml felt like the right mix in of programming paradigms to do this kind of thing, so I began to read <em>Introduction to Objective Caml</em> by <em>Jason Hickey</em>.</p>
<p>One of the chapters I really enjoyed about this book is <em>Basic pattern maching</em>. I was pretty amazed about the predominance of pattern matching in OCaml. Pattern matching can be applied to (almost) any OCaml primitive type (string, Boolean, char&#8230;), it also applies to a variety of syntactic structures (like assignment, function definition, etc) and finally there&#8217;s a lot of &#8220;syntactic sugar&#8221; going on in pattern matching. </p>
<p>The basic syntax for doing pattern matching in Ocaml is:</p>
<pre name="ocaml" class="ocaml-pre">
match expression with
 | pattern1 -> expression1
 | pattern2 -> expression2
 .
 .
 .
  | patternN  -> expressionN
</pre>
<p>This way you could define a fibonacci <em>fib</em> function like this:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
let rec fib i =
   match i with
      0 -> 0
    | 1 -> 1
    | j -> fib (j - 2) + fib (j - 1);;
</pre>
<p>Since it&#8217;s quite common to define functions with <em>match</em> expressions as their body, Ocaml reserved a special keyword <em>function</em> that defines a function with a single argument treated as pattern match. For example the <em>fib</em> function could be re-defined like this:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
  let rec fib = function
     0 -> 0
   | 1 -> 1
   | i -> fib (i - 1) + fib (i - 2);;
</pre>
<p>The pattern match argument is now implicit in the function definition. That&#8217;s quite minimalistic.<br />
There&#8217;s also the <em>as</em> keyword used to bind a match to a variable. For example:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
let rec fib = function
   (0 | 1) as i -> i
 | i -> fib (i - 1) + fib (i - 2);;
</pre>
<p>The <em>when</em> keyword evaluates a condition after the pattern match. The <em>fib</em> function could now look like this:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
let rec fib = function
   i when i < 2 -> i
 | i -> fib (i - 1) + fib (i - 2);;
</pre>
<p>Pattern matching can also be applied to other Ocaml primitive types, like strings, chars, Booleans. Let&#8217;s take an example of the function <em>is_uppercase</em>:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
  let is_uppercase = function
   ’A’ | ’B’ | ’C’ | ’D’ | ’E’ | ’F’ | ’G’ | ’H’
 | ’I’ | ’J’ | ’K’ | ’L’ | ’M’ | ’N’ | ’O’ | ’P’
 | ’Q’ | ’R’ | ’S’ | ’T’ | ’U’ | ’V’ | ’W’ | ’X’
 | ’Y’ | ’Z’ ->
    true
 | c ->
    false;;
</pre>
<p>But that&#8217;s not minimalistic. It would be if we used <b>pattern ranges</b> to specify the list of letters like this:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
let is_uppercase = function
   ’A’ .. ’Z’ -> true
 | c -> false;;
</pre>
<p>The <em>c1..c2</em> notation specifies the letters range.<br />
The <em>c</em> pattern variable acts here like a <em>wildcard</em> to match all non-uppercase symbols. Since this is another commonly occurring structure, Ocaml reserves the <em>_</em> symbol to match anything:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
 let is_uppercase = function
    ’A’ .. ’Z’ -> true
  | _ -> false;;
</pre>
<p><b>Pattern matching everywhere</b><br />
What&#8217;s really interesting about pattern matching in Ocaml, is that not only pattern matching can be applied to (<em>almost</em>) any primitive type, but that pattern matching constructions are also allowed in a variety of places:</p>
<pre name="ocaml" class="ocaml-pre">
let    pattern = expression

let    identifier pattern . . . pattern =  expression

fun    pattern -> expression
</pre>
<p>So, for example, if we define a tuple like this:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
let p = 1, "Hello";;
</pre>
<p>We could access its components using pattern matching:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
let x, y = p;;
</pre>
<p>Another example with lists could be:</p>
<pre name="code" class="ocaml:nogutter:nocontrols">
let aList = [1; 2; 3];;
let hd :: tl = aList in
  Printf.printf "%d" hd;;
</pre>
<p>The latter code will print &#8220;1&#8243;.</p>
<p><b>What <em>can&#8217;t</em> be done&#8230;</b><br />
We can&#8217;t do pattern matching with one type in Ocaml, and that&#8217;s <em>functions</em>:</p>
<pre name="ocaml" class="ocaml-pre">
  match (fun i -> i + 1) with
     (fun i -> i + 1) -> true;;
      ^^^
Syntax error
</pre>
<p><b>What about JavaScript?</b><br />
Unfortunately JavaScript doesn&#8217;t have pattern matching. The closest thing to pattern matching that JavaScript has is, well, the Regexp object. In some sense that can be regarded as string pattern matching.<br />
The funniest thing about that fact, is that &#8220;string pattern matching&#8221; can be used as &#8220;function pattern matching&#8221; in JavaScript.</p>
<p>JavaScript functions have a method called <em>toSource</em>, that returns a string of the source code of the function. For example:</p>
<pre name="code" class="js:nogutter:nocontrols">
(function (formalParam1, formalParam2)
     { return formalParam1; }).toSource();
</pre>
<p>should return (at least in Firefox) the String:</p>
<pre name="code" class="js:nogutter:nocontrols">
"(function (formalParam1, formalParam2) {return formalParam1;})"
</pre>
<p>However, applying this method to the native <b>Function</b> class returns the following:</p>
<pre name="code" class="js:nogutter:nocontrols">
"function Function() {[native code]}"
</pre>
<p>You can find function pattern matching examples in JavaScript when browsing the &#8220;Class&#8221; object implementations for any JS framework. Most frameworks that provide a &#8220;Class&#8221; object to wrap prototypal inheritance in something more OO have to check all methods for calls on &#8220;super&#8221; in order to effectively call the superclass method. However, we first have to verify that the browser supports a <em>toSource</em> method that actually returns a string of the entire function body. That check is done with simple function pattern matching:</p>
<pre name="code" class="js:nogutter:nocontrols">
  /xyz/.test(function(){xyz;});
</pre>
<p>This code will return true if the &#8220;xyz&#8221; pattern is found in the anonymous function. If true, then we can &#8220;search&#8221; for <em>super</em> calls in all body functions in order to replace them with the proper superclass method call. A nice example of simple JavaScript inheritance implementation can be seen in <a href="http://ejohn.org/blog/simple-javascript-inheritance/" target="_blank">John Resig&#8217;s post</a></p>
<p>Although I know this is still a regexp match, It can also be seen as comparing a function&#8217;s body to a given pattern and thus I believe it can be called function pattern matching.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2008/08/11/pattern-matching-in-ocaml-and-javascript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
