Harry Seldon's blog

Fractals, Chaos, and Control Systems on Rails


How to draw Mandelbrot's fractal with Rails and Open Flash Chart?

Posted by Harry Seldon on April 18, 2009

Mandelbrot set

Let us draw the Mandelbrot set with OFC. The point is to make a new example of use of OFC and it is also to have some fun with the so interesting fractal theory. To see how fashionable it is, read this post: Good news from the combat against the crisis. This post is highly inspired from this nice French page about the Mandelbrot set. I am using the algorithm given there.

Definition of the Mandelbrot set
For each point of the complex plane we associate the sequence: zn+1=zn2+A with z0=0 and A=a+ib the point affix. Iff the sequence is bounded the point A belongs to the Mandelbrot”s set. Problem is, it is not easy for a computer to say if a sequence remains bounded. It would require an infinite number of calculations. For each point, we are simply going to make a ‘large’ number of calculation on the sequence. It can be shown analytically that if the module of zn is greater than 2 the sequence will diverge. So during nmax iterations, if the sequence goes above 2, the sequence diverges and it has diverged all the quicker as the number of iteration is low. If it is quick to diverge it is far from the set. A color will be associated to each point according to its distance from the set. If the algorithm reaches nmax the probability for the point to belong to the set is maximal with respect to our computation.

To code without complex numbers we will use the real coordinates, the sequence being written equivalently as:
yn+1=2 xn yn+b

Code for Open Flash Chart
The implementation with Rails and OFC is explained hereafter. It is using a scatter chart.

in test_it_controller.rb

  def index_mandelbrot_fractal
    # from http://perso.numericable.fr/~haasjn/haasjn/AlgoMandel.txt 
    @graph = open_flash_chart_object(500,500,"/test_it/graph_code_Mandelbrot_fractal")     

Also in test_it_controller.rb

  def graph_code_Mandelbrot_fractal
    #    Algorithm to draw Mandelbrot's fractal 
    #    variables a,b,x,y,xmin,ymax,cx,cy,width,step:real
    #              i,j,nx,ny,n:int
    #              r: table
    #    cx,cy    coordinates of the image center in the complex plane
    #    xmin     image left limit 
    #    ymax     image upper limit
    #    width    image width in the complex plane
    #    nx       image horizontal resolution 
    #    ny       image vertical resolution
    #    nmax     maximum number of loops to compute the convergence of the complex sequence
    #    step     step between 2 points 
    #    r        table containing the result for each point
    #    in the loop 
    #    i,j  indices of the point 
    #    a,b  point coordinates
    #    x,y  values of the complex sequence
    #    x1   next value of x 
    #    n    indice of the complex sequence
    #    Algorithm beginning 
    #    cx,cy,width,nx,ny,nmax are given at start 
    cx = 0
    cy = 0
    width = 4.to_f
    nx = 100.to_f
    ny = 100.to_f
    nmax = 250.to_f

    xmin = cx-width/2
    ymax = cy+width/2*ny/nx
    step  = width/nx

    # Preparation of the chart
    chart = OpenFlashChart.new
    title = Title.new("Mandelbrot set")
    r = Array.new # results 

    # The loop asks : does the point (a,b) belong to the Mandelbrot set ? 
    # The bigger n, the more probable the point belongs to  the set 
    for j in 0..ny-1
      for i in 0..nx-1
        #  while x*x+y*y<4 and n<=nmax
        while x*x+y*y<4 && n<=nmax

        # Adding the point to the chart
        # Needs to associate a color according to n 
        # that is according to the time needed to converge
        amplif = 1
        c = (16.0.+n/nmax*(255.0-16.0)*amplif).to_int
        c = [255,c].min
        col_gray = (255-c).to_int.to_s(16).to_s
        col =  "#"+col_gray+col_gray+col_gray
        scatter = Scatter.new(col, 2);
        chart.add_element( scatter )

        # if you want to store the result 
      end #i
    end #j

    x_axis = XAxis.new
    chart.x_axis = x_axis

    y_axis = YAxis.new
    y_axis.set_range( -ymax, ymax )
    chart.y_axis = y_axis
    render :text => chart.to_s      

in index_mandelbrot_fractal.html.erb

<script type="text/javascript" src="/javascripts/swfobject.js"></script>
<%= @graph %>

Notice the code for the computation and the graph are made together in the controller code. This is just for simplicity to write this post. Technically, the computation is more a work for your model. Preparing the graph is also a work for the model. With a DRY code you would have one model method to prepare the data, one to prepare the chart. Then in the controller you call the method that prepares the chart and you sends the data to the view.

Here is the Mandelbrot set chart. Beware it takes about 10 seconds to load. Indeed the algorithm is computationally intensive. The code is available in the OFC test app on github. Here is the controller code.

Thanks for having read this world first: drawing the Mandelbrot set with Ruby on Rails and OFC.

Posted in , | 2 comments | Tags , , , , , | atom

Open Flash Charts examples with Rails

Posted by Harry Seldon on March 09, 2009

Posted in | no comments | Tags , , , , | atom

News from Typo edge

Posted by Harry Seldon on March 08, 2009

I have updated this blog engine in order to install the recently added Feedburner support. My recent post about Rails heroes RSS feeds clearly showed me that feedburner was a must have as everybody is using it. Feedburner gives you an idea of your RSS traffic.

Here are some more recently added features to Typo:

More info, for French readers, here

I encountered some small issues during this update. Here they are, so you can avoid them.


Since my last post about Typo installation from git, the plugin management has changed. Typo now uses gems. Therefore, to install locally Typo, the process is now:

git clone git://github.com/fdv/typo.git
sudo gem install htmlentities  coderay json  calendar_date_select
sudo gem sources -a http://gems.github.com
sudo gem install datanoise-actionwebservice mislav-will_paginate
Rake db:migrate

You can still manage the plugins such as related content or recent comments using git submodules.


Some routes have changed. Therefore, you will probably need to update your theme. For instance: in theme/views/articles_comment_form.html.erb I replaced:


For the live search: in theme/views/shared_search.html.erb I replaced:

{ :controller => 'live', :action => 'search' } 


This is about Typo edge. It is not supposed to be a stable version. So use with caution! Right now the cache needs some improvement which should be done soon. Temporarily, I have disabled it by commenting in app/model/blog_sweeper.rb the line:

observe Category, Blog, User, Article, Page, Categorization, Comment, Trackback

About recent news, Matijs van Zuijlen has joined the Typo core team.

Thanks a lot to the Typo core team, Fred, Cyril and Matijs, for their excellent work and also for their extremely reactive support.

Posted in | no comments | Tags , , , , , | atom

Rails Camp Paris 2

Posted by Harry Seldon on February 22, 2009

Organized by Ruby France and Sun Microsystems, the second RailsCamp Paris will take place on March 7th 2009 at the Sun Customer Briefing Center, 42 avenue d’Iéna, Paris (16th), France.

Due to the Rails/Merb merge, on of the main themes of this event will be Merb. Other themes are up to you.

This event is free and open to everyone, newbies to gurus. You just need to sign up here. Beware the event is limited to 100 participants and 85 people (as of writing) have already subscribed.


By the way, I have added the RSS flow of Ruby France to my Rails reading list.

I’ll be there and I am really looking forward to it as I do not know Merb and am willing to learn what all the buzz around it is about.

See you there.

Posted in | no comments | Tags , , | atom

Read your Rails Heroes

Posted by Harry Seldon on February 03, 2009

Ruby on Rails is moving fast. So you need to stay tuned to Rails news. What is best than reading RoR heroes’ blogs ? Yep, nothing.
To help you, Railsinside has on its home page a list of Rails heroes. Unfortunately, as the links link toward their blogs and not towards their RSS flow, it might be tedious to add all the flows to your reader. And sometimes it is not immediate to understand where the flow is hidden.
It is only recently that I have added all these flows to my reader. In order to facilitate you the work, here is the Railsinside list of Rails heroes with links to their RSS flow. For some of them, I have not found the flow. If you know their address, please leave it in the comments. A few more flows will be suggested as a bonus. All these flows are added to my public netvibes page. Check it to have a look at what it looks like to be so close to all these minds.

Let’s add to this RoR’s blog, Railsinside and Rubyinside:

Some other great flows I have in my list are:

[EDIT] Here is the OPML for all the previous RSS flows. Using this file you can import the links into your preferred RSS reader.

[EDIT] Thanks to Luke the list is now complete. And in case, like me, you did not know this Firefox feature, at the right of the url bar you have a star and a orange wave sign (the RSS logo). Just click on it to get the RSS flows that are ‘hidden’ (or not finally ;-) ) in the blog. Star is to fave the blog.

Then, I won’t resist to recommend you my flow ;-)

And finally for French readers:

Let me know in the comments if you see any problem with the links or if you know one of the missing links. Also, if you have a blog about Rails activities, you are welcome to leave a link to your RSS flow. I might add the best ones to this list.

Happy reading.
PS Other Rails resources
PPS Doing this, I was amazed by the number of feeds going through feedburners. But if you are interested by stats about your feed you need to use it. So, I guess I will have to use it too.

Posted in | 14 comments | Tags , , , | atom

Git and Rails: A detailed tutorial including plugins, submodules, development and production

Posted by Harry Seldon on January 14, 2009

I had started talking about setting up a development and production environment with git for Typo in this post. Because of this new version of Typo, I have finally had a very good reason to change the set up of this blog and to migrate to git. Installing Typo from its git repository, I have had the opportunity to use the git submodules. That is why in this post I will use the Typo blog engine to make a case study for the use of git with:

  • Several repos for development, production and deployment
  • Several repos for open source development
  • Use of submodules for plugin management and development

Indeed, my own aims for this new setup are to:

  • Have a test environment and a production environment for this blog
  • Be able to update the blog engine from its main repository
  • Be able to contribute to this open source blog engine
  • Manage properly rails plugins
  • Be able to contribute to these plugins

The final setup is as following, represented on the figure below:

  • I have a repository where I develop and test Typo. This repo is first created by cloning Typo’s repo. From my point of view this is the main repo. Indeed I can pull from Typo’s repo or push to it. in the same way I can push to the production repo, to deploy. Deployment can be managed easily by Capistrano in this configuration. Notice that several branches can be contained in the repo (public branch pushed to the main repo, private production branch, etc.)
  • Production repo. The actual production code is a checkout from this repo.
  • My public dev repo. It contains the changes I can propose to Typo’s dev team through a ‘pull request’.
  • Main repo. Currently it is Fred’s repo but thanks to git architecture it could be as well the public repo of who you want.
  • Fred’s private repo. He may have several dev repos, with plenty of branches, on several computers .
  • Cyril’s public repo.
  • Cyril’s private repo

git image
For each repo, the plugins are put in subrepo and managed through git submodules. That is, each plugin has its own repo and is not included in Typo’s repo. However, the beauty of the submodules is that you can really easily develop and update your plugins.

Now let’s go for a detailed tutorial to set this up.
This setup is for people willing to have a full development environment. However, if you just want to install Typo, you simply need to skip the first step, the creation of the public repo. And in this case you can consider that your public user name is ‘fdv’ but you will not be able to push to the repos.

Create your public repo
Fork Typo on github using your account. As you are doing that, also fork the plugins that interest you, for instance Recent comments, Recent posts and Related posts.

Create your dev repo
Then, clone the Typo repo from your public repo. Type this command in the local directory of your choice. Replace the user name harryseldon by your name.

git clone git://github.com/harryseldon/typo.git

To be able to update your dev repo with the latest changes, add the address of the main repo:

git remote add main_typo git://github.com/fdv/typo.git

Then to update your copy, you simply need to pull the changes:

git pull main_typo master

NB. The repo you clone from will be called ‘origin’ in your local copy. If you prefer you can initially clone from the main repo and then add the address of your github repo.

In order to run, like every Rails app, Typo requires some plugins. They are managed through the git submodules. So you just need to run:
[EDIT 3/8/2009] Typo plugins are now managed using gems, check this post.

git submodule update --init

With this command the plugins will be pulled from the addresses written in the .gitmodules file which looks like this:

[submodule "vendor/rails"]
  path = vendor/rails
  url = git://github.com/rails/rails
[submodule "vendor/actionwebservice"]
  path = vendor/actionwebservice
  url = git://github.com/datanoise/actionwebservice.git
[submodule "vendor/plugins/rspec"]
  path = vendor/plugins/rspec
  url = git://github.com/dchelimsky/rspec.git
[submodule "vendor/plugins/rspec-rails"]
  path = vendor/plugins/rspec-rails
  url = git://github.com/dchelimsky/rspec-rails.git
[submodule "vendor/plugins/will_paginate"]
  path = vendor/plugins/will_paginate
  url = git://github.com/mislav/will_paginate.git

If you have your dev version of one of these plugins, do not hesitate to change the address to point to your public repo.

Then you may want to install your preferred Typo plugins. The ones you have just forked on github.

git submodule add git://github.com/harryseldon/typo_related_posts.git vendor/plugins/typo_related_posts
git submodule add git://github.com/harryseldon/recentposts_sidebar.git vendor/plugins/recentposts_sidebar
git submodule add git://github.com/harryseldon/recent_comments_sidebar.git vendor/plugins/recent_comments_sidebar

and again

git submodule update --init

To use Typo in your dev environment, you finally need to configure your database. Use your usual settings and run the migrations. Typo will work like any other Rails app.

Like any other git repo, feel free to create as many branches as you like. For instance you can create a production branch:

git branch typo_production

You would typically set the environment to production in environment.rb.

Create your production repo
Assuming an ssh connection, you create the repo on your host in a ~/git/Typo directory.

git init

You add the address of this repo to your dev repo:

git remote add production_repo ssh://user@ssh.domain.com/home/user/www/git/typo/.git

Now you can push your code to production. Let us say you created a special production branch,

git push production_repo typo_production

This step could be done using Capistrano and pushing the development branch. Capistrano would be typically in charge of making the changes in environment.rb.

Commit changes
Assuming you made some changes in your dev repo. You commit them:

git commit -a -m "my changes"

Then you can push them to your public repo:

git push 

Accordingly with the previous NB, this is equivalent to:

git push origin master

Then from your github account, you can send a “pull request” to Typo maintainers if you would like to see your changes included in the official Typo code.

As far as the plugins are concerned, the process is similar. You cd to your plugin folder which is under a git version control and you can push, just like for the Typo repo.

Following this tutorial, you have installed a typical environment for a Rails application under git version control.

Feel free to leave comments about the git environment or the Typo installation.

Posted in | 8 comments | Tags , , , , | atom

Migrating to Typo 5.2 and to GIT

Posted by Harry Seldon on January 13, 2009

Typo, this blog engine, underwent a lot of great improvements these last months thanks to Frederic and Cyril (2 blogs in French). So it was time for me to upgrade this blog to the new version: Typo 5.2 Release Candidate named after Helmut Newton. The main improvements are:

  • A lot faster (you should notice it)
  • A new backend: more flexible, simpler, with a clearer dashboard summarizing the last comments, the last posts, the most popular posts
  • A new text editor that facilitates the use of markup languages (I am specially glad of that one as I had complained about the previous text editor)
  • New SEO functions: places to easily enter your meta information: keywords, webmaster tools api, google analytics key etc.
  • Use of Coderay for a better syntax highlighting for many programming languages
  • Easier search (previous one was sexy but surprising when you hit the enter key)

The main thing missing is a live preview but that might be for the next release !

During the migration (to the RC) I had a few small difficulties:

  • I did not find the sidebar settings: they moved to the themes menu and sidebar submenu .
  • The plugins recent comments and recent posts were not compatible with Typo 5.2. I had modified them. But actually they now are compatible as Fred added the backward compatibility.
  • If you use your own theme, you will need to update the index page. Indeed the call to ‘classic pagination’ must be replaced by a call to ‘will paginate’. Simply copy and paste from one of the example themes.

By the way, migrating to git, I was able to update these plugins accordingly with what I had said in this post: Typo plugins for “recent comments” and “related posts”. To get the modifications, right now, you need to use my forks on github:

I had started talking about setting up a development and production environment with git and Typo in this post. Because of this new version of Typo, I have finally had a very good reason to change the set up of this blog and to migrate to git. The migration to git will be the subject of the next post. Installing Typo from its git repository, I had the opportunity to use the git submodules. That is why in this post I will use the Typo blog engine to make a case study for the use of git with :

  • several repos for development, production and deployment
  • several repos for open source development
  • Use of submodules for plugin management and development

To be continued !

Posted in | no comments | Tags , , , , | atom

How to add social bookmarking features to your (Typo) blog

Posted by Harry Seldon on December 28, 2008

As you can see below I have added the social bookmarks buttons at the bottom of each article. The buttons are for the following sites.

The links will direct you to their widget page.

The code to add these buttons is:

<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script>
<a href="http://delicious.com/save" onclick="window.open('http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=550,height=550'); return false;">
<img src="http://static.delicious.com/img/delicious.small.gif" height="50" width="50" alt="Delicious" /></a>
<script type="text/javascript" src="http://www.reddit.com/button.js?t=3"></script>
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> 
<a href="http://technorati.com/faves?sub=addfavbtn&amp;add=http://harryseldon.thinkosphere.com">
  <img src="http://harryseldon.thinkosphere.com/files/technorati.jpeg" alt="Add to Technorati Favorites" height="50" width="50" /></a>
<a href="javascript:location.href='http://slashdot.org/slashdot-it.pl?op=basic&amp;url='+encodeURIComponent(location.href)">
  <img src="http://harryseldon.thinkosphere.com/files/slashdot.jpeg" alt="Slashdot" border="0" height="50" width="50"></a>

Notice that the one for technorati is special. I have not found exactly what I wanted. It favorites the blog itself not only the article. Therefore, this part of the code is not suitable for your blog ! You need to adapt it. For the other links they should work as such on your blog.

If your blog engine is Typo simply add the previous code to /themes/your_theme/views/articles/read.html.erb, typically after the line :

<%= render :partial => 'article', :object => @article %>

And you which social bookmarking websites do you use ?

Posted in | no comments | Tags , , , , , , , | atom

Use OFC in your model

Posted by Harry Seldon on December 19, 2008

I am only now upgrading my OFC plugin version in my Thinkosphere project. Last update was before all the refactoring made by dfl.
From this refactoring until now, you need to add the line ‘include OpenFlashChart’ in your model to properly use OFC. You do not need to do that in your controllers because OFC is already required for all controllers and views thanks to the following lines in init.rb:

require 'open_flash_chart'
ActionView::Base.send :include, OpenFlashChart::View
OpenFlashChart::Base.send :include, OpenFlashChart::View
ActionController::Base.send :include, OpenFlashChart::Controller
ActionController::Base.send :include, OpenFlashChart

So if you want to use OFC in your model (what you should want) simply add the following lines in init.rb:

ActiveRecord::Base.send :include, OpenFlashChart::View
ActiveRecord::Base.send :include, OpenFlashChart::Controller
ActiveRecord::Base.send :include, OpenFlashChart

Notice that this will work for your ActiveRecord model not the others.

Then why would you want to use OFC in your model ? Probably because you want to use a “fat model, skinny controller” policy. Doing so will allow you to easily reuse your code needed to prepare the graphs. If you have lots of graphs in your application that will be very efficient.

This code update is currently available on my github fork.
Update: It is now available on OFC home.

This makes me think that a small demonstration of use of OFC with models seems needed in the OFC test app. If someone feels like wanting to do it, do not hesitate ! I am specifically aiming at Anthony Navarre who left a nice code snippet as a comment on Charlie’s blog ;-)

Posted in | no comments | Tags , , , , | atom

News from Open Flash Chart

Posted by Harry Seldon on December 18, 2008

In November, Open Flash Chart was updated with some new features and bugfixes. OFC rails plugin was also updated thanks to Charlie, Zuk and Otavio. I have just updated the OFC test app. The list of changes brought by OFC new version is given at the end of this post.

Moreover, some new examples of OFC use are available around:

For reference, here is the list of changes of the latest OFC version:

Posted in | 1 comment | Tags , , , , | atom



Recent Comments

Recent Posts


actuators aircraft atc blog chaos chaos_theory charts control controllers controls crisis economy finance flight fractals git gnc gs guidance linux mandelbrot marketing navigation ns ofc on pilot rails ruby sas scs sensors statistics systems techcrunch thinkosphere tutorial typo ubuntu wifi