SimFrost (#117)

On Mar 12, 2007, at 12:04 PM, Robert D. wrote:

Talking about netpbm, I used it from Linux and I had no problem to
create an mpeg from 705 frames (512x512) only that err… it is about
50 times too big.

30MB
No way to post this to the list, I continue to try making it smaller -
this is my first attempt of video compression.

Would you be interested in it for the site maybe, and if so what size
is acceptable?

I’m going to pass just because I already have one movie up there and
I’m sure that’s doing enough damage to my alloted bandwidth already. :wink:

James Edward G. II

Here’s my SimFrost solution. It was done by Saturday night, but I so
wanted to get images working.
Thanks James Edward G. II for the PPM solution

Hey James, I tried out your solution in the Linux partition on the same
machine, and it renders correctly with Kview. Something must be wonky
with
my windows ImageMagick install…

Sorry for the noise ppl, but this was kinda bugging me…
On the color issues of the ppm, windows was sneaking a CR at the *
P680 25 255

Must be because “\n” in windows is 0d0a instead of just 0a

On 3/13/07, Albert Ng [email protected] wrote:

Sorry for the noise ppl, but this was kinda bugging me…
On the color issues of the ppm, windows was sneaking a CR at the *
P680 25 255

P6 is the raw format I use the text format P3, that should avoid your
problems.
Robert

Must be because “\n” in windows is 0d0a instead of just 0a

On Mar 13, 2007, at 12:46 PM, Albert Ng wrote:

Sorry for the noise ppl, but this was kinda bugging me…
On the color issues of the ppm, windows was sneaking a CR at the *
P680 25 255

As an interesting aside, Graphic Converter reports the image as
broken. Did I mention that I love that program? :wink:

James Edward G. II

On 12 Mrz., 07:22, Ruben M. [email protected] wrote:

Woah, this quiz was very entertaining. I enjoyed a lot doing it, and
still enjoy watching it every time :smiley:

As the console version wouldn’t let me be happy, I tried to do it using
OpenGL. I got it at the end, although it’s pretty slow (runs at decent
speed for size of <200*200, obviously the greater values the slowest),
but I’m happy with it for being my first try using GL.

Nice that someone did it with OpenGL.
I just installed ruby-opengl to try your solution.
But gem always want to make me cry.

Now require ‘opengl’ is no longer an option
it must be
require ‘rubygems’
gem ‘ruby-opengl’
Thanks for that Mr. Gem.

I am on Ubuntu, but i remember having similar probs on Windows, maybe
the exact opposite :\

For now I wrote my own opengl.rb and put it in my loadpath.
Maybe someone needs it too :>

—>8—
require ‘rubygems’
gem ‘ruby-opengl’

require ‘glut’
require ‘gl’

%w(glut gl).each do |modul|

eval <<-CODE
#{modul.upcase} = #{modul.capitalize}
module #{modul.capitalize}
def self.method_missing sym, *args
send((“#{modul.downcase}” + sym.to_s).to_sym, *args)
end
def self.const_missing sym
const_set(sym, const_get(“#{modul.upcase}_” + sym.to_s))
end
end
CODE

end

On Mar 13, 3:04 pm, “rretzbach” [email protected] wrote:

Nice that someone did it with OpenGL.
the exact opposite :\

  end
end

CODE

end

=)
Actually, I did it Windows, since I was working on it when I read the
quiz. However, on my Ubuntu, Mr. Gems wouldn’t actually let me work
(that fed by the fact I did a mess on my dependences, and hadn’t
cleaned it up D: )

I’ll try it, thanks :smiley:

:slight_smile:
As promised, I tuned up my code for OpenGL, and runs it faster, allowing
bigger boards.

Here’s the code:

http://pastie.caboo.se/46744

And… playing a little more with OpenGL, I managed to do a 3D
simulation. The bad thing is that I’m a completely newb into it, so it
doesn’t look like expected, mainly because I’m having troubles with the
viewport, shadows, angles, lighting and all that. This quiz is a good
excuse for me to learn :smiley:

I’ll throw also the code I experimented with, if someone’d like to check
it and play with it, it’s basically the same code expanded to a 3D
array. Of course, it would be nicer if someone experienced with GL could
make it look better :smiley:

http://pastie.caboo.se/46751

I’ll show a couple of images resulting from it.

http://img98.imageshack.us/img98/4487/simfrost3d3cv6.gif
http://img368.imageshack.us/img368/1899/simfrost3d4lg2.gif

Rubén

(P.S. Sorry for the double posting)

Hi Jupp

settings = get_settings
cols = settings[“cols”],
rows = settings[“rows”],
prob = settings[“prob”]

this isn’t realy what you wanted, right?

cheers

Simon

Hi!

  • Ruby Q., 09.03.2007 13:58:

The goal is to create a simulation of frost.

My aim was not to solve the task in a very object-oriened way or to
have a shiny output. My major objectives were

  • Writing a Ruby program that can easily be ported to C, porting it
    and then compare the performance. It turned out that the C
    implementation is faster by a factor of about 100.

  • Finding a simple way of animating the produced data without
    having to implement a GUI.

For the implementation see source below, let’s turn to animation:

I use numbered PGM files as output format. For tick 0 (initial state
tick_00000.pgm is written, for tick 1 tick_00001.pgm and so forth.
For large simulations - I ran a C 1280x1024 C simulation with 25%
vapor that took about 7 minutes (with the bottleneck being the
Journaling File System) that took 3472 ticks meaning 3473 output
frames - it can be a good idea not to display all of the frames but
only every 10th or so. This goal can easily achieved by not looking
at all frames but only at those matching “tick_0.pgm". For every
20th one could use "tick_
[02468]*.pgm” and so on.

One way of animating the output is using “convert” to create an
animated gif in the following manner:

convert -delay 0 -loop 0 tick_*.pgm simfrost.gif

Beware that this can require quite a lot of RAM!

A less demanding way of animtin the output is using an appropriate
display program. Personally I perfer qiv. To use this program to
animate the output all one has to do is issue

qiv -s -d 0 tick_*pgm

Where ‘-s’ orders qiv to display the images as a slideshow and ‘-d’
provides a delay in seconds between the individual images, for I was
using the program for 1280x1024 images I set this delay to 0.

qiv is available at http://www.klografx.net/qiv/

The second major advantage of using PGM or PBM or PGM besides the
simplicity of output is that they can be converted to virtually any
other graphics format because they are the generic formats used by
the netpbm tools, see http://netpbm.sourceforge.net/

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Follows Ruby implementation
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#!/usr/bin/ruby -w

#####################################################################

Ruby Q. 117, SimFrost

The simulation uses an array of integers.

It seems to make sense to use

0 to represent vacuum

1 to represent vapor

2 to represent ice

Note that your terminal emulation should support ANSI escape

sequences

#####################################################################

#####################################################################

Integer#even - see if Integer is even

#####################################################################

class Integer
def even?
self/2*2 == self
end
end

#####################################################################

cls - clear screen

#####################################################################

def cls
print “\e[2J”
end

#####################################################################

home - move cursor to home position

#####################################################################

def home
print “\e[1;1H”
end

#####################################################################

Get even positive number

#####################################################################

def get_even_positive(desc)
n = 0
until n > 0 && n.even?
print "Please enter #{desc} (must be even and positive): "
n = gets.to_i
end
return n
end

#####################################################################

Read probability

Input is probability in percent, return value is probability

#####################################################################

def get_probability(desc)
p = -1.0
while p < 0.0 or p > 100.0
print "Please enter probability for #{desc} (in %, float): "
p = gets.to_f
end
return p / 100.0
end

#####################################################################

Read settings

#####################################################################

def get_settings
okay = “no”
while okay != “yes”
cls
cols = get_even_positive(“number of columns”)
rows = get_even_positive(“number of rows”)
prob = get_probability(“vapor”)
puts <<-EOF
You want:
\t#{cols}\tcolums
\t#{rows}\trows
\t#{prob*100.0}\tas the initial probabilty for vapor in percent
IS THAT CORRECT? If so please answer with: yes
EOF
okay = gets.chomp
puts “Please re-enter data.” unless okay == “yes”
end
return { “cols” => cols, “rows” => rows, “prob” => prob }
end

#####################################################################

generate initial state for simulation

#####################################################################

def initial_state(cols, rows, prob)
a =
Array.new(rows) do |row|
Array.new(cols) do |elem|
rand < prob ? 1 : 0
end
end
a[rows/2][cols/2] = 2
return a
end

#####################################################################

output current simulation state

#####################################################################

def output_state(state, tick)
home
puts “Simulation tick #{tick}”
filename = “tick_#{‘%05d’ % tick}.pgm”
File.open(filename, ‘w’) do |file|
file.puts <<-EOF
P2

#{filename}

#{state.first.length} #{state.length}
2
EOF
state.each do |row|
row.each do |elem|
file.puts elem.to_s
end
end
end
end

#####################################################################

see if state is frozen out (i.e. no more vapor is present)

#####################################################################

class Array
def frozen_out?
not self.flatten.member?(1)
end
end

#####################################################################

the simulation itself

#####################################################################

settings = get_settings
cols = settings[“cols”],
rows = settings[“rows”],
prob = settings[“prob”]
state = initial_state(cols, rows, prob)
tick = 0
cls
while true
output_state(state, tick)
break if state.frozen_out?
tick += 1
offset = (tick + 1) % 2
i = offset
while i < rows
i1 = (i + 1) % rows
j = offset
while j < cols
j1 = (j + 1) % cols
if [ state[i][j],
state[i][j1],
state[i1][j],
state[i1][j1] ].member?(2)
state[i][j] = 2 if state[i][j] == 1
state[i][j1] = 2 if state[i][j1] == 1
state[i1][j] = 2 if state[i1][j] == 1
state[i1][j1] = 2 if state[i1][j1] == 1
else
if rand < 0.5
state[i][j], state[i][j1], state[i1][j], state[i1][j1] =
state[i][j1], state[i1][j1], state[i][j], state[i1][j]
else
state[i][j], state[i][j1], state[i1][j], state[i1][j1] =
state[i1][j], state[i][j], state[i1][j1], state[i][j1]
end
end
j += 2
end
i += 2
end
end

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Follows C implementation
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void cls(void)
{
printf(“\033[2J”);
}

void home(void)
{
printf(“\033[1;1H”);
}

int get_even_positive(char* desc)
{
int n = 0;
char s[21];
while( n <= 0 || n/2*2 != n)
{
printf(“Please enter %s (must be even and positive): “, desc);
scanf(”%20s”, s);
n = atoi(s);
}
return n;
}

double get_probability(char* desc)
{
double p = -1.0;
char s[21];
while (p < 0.0 || p > 100.0)
{
printf(“Please enter probability for %s (in percent, float): “,
desc);
scanf(”%20s”, s);
p = atof(s);
}
return p / 100.0;
}

int **initialize_state(int cols, int rows, double prob)
{
int i;
int j;
int **a;

a = (int **) calloc(rows, sizeof(int *));
for (i = 0; i < rows; i++)
{
a[i] = (int *) calloc(cols, sizeof(int));
}
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
a[i][j] = (rand() < RAND_MAX * prob) ? 1 : 0;
}
}
a[rows/2][cols/2] = 2;
return a;
}

void display_state(int **state, int tick, int cols, int rows)
{
int i;
int j;
char filename[15];
FILE *file;

home();
printf(“Simulation tick %d\n”, tick);
sprintf(filename, “tick_%05d.pgm”, tick);
file = fopen(filename, “w”);
fprintf(file, “P2\n”);
fprintf(file, “# %s\n”, filename);
fprintf(file, “%d %d\n”, cols, rows);
fprintf(file, “2/n”);
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
putc(“012”[state[i][j]], file);
putc(‘\n’, file);
}
}
fclose(file);
}

int frozen_out(int **state, int cols, int rows)
{
int i;
int j;

for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
if (state[i][j] == 1)
{
return 0;
}
}
}
return 1;
}

int main(void)
{
int okay = 0;
int tick = 0;
int offset;
int cols;
int rows;
int i, i1;
int j, j1;
int h00, h01, h10, h11;
double prob;
char s[21];
int **state;

while (!okay)
{
cls();
cols = get_even_positive(“number of columns”);
rows = get_even_positive(“number of rows”);
prob = get_probability(“vapor”);
printf(“You want:\n”);
printf(“\t%d\tcolums\n”, cols);
printf(“\t%d\trows\n”, rows);
printf(“\t%f\tas the initial probabilty for vapor in percent\n”,
prob * 100.0);
printf(“IS THAT CORRECT? If so please answer with: yes\n”);
scanf(“%20s”, s);
okay = !strcmp(s, “yes”);
if (!okay)
{
puts(“Please re-enter data.”);
}
}
state = initialize_state(cols, rows, prob);
cls();
while(1)
{
display_state(state, tick, cols, rows);
if (frozen_out(state, cols, rows))
{
return 0;
}
offset = (tick++ + 1) % 2;
for (i = offset; i < rows; i += 2)
{
i1 = (i + 1) % rows;
for (j = offset; j < cols; j += 2)
{
j1 = (j + 1) % cols;
if (state[i][j] == 2 ||
state[i][j1] == 2 ||
state[i1][j] == 2 ||
state[i1][j1] == 2)
{
if (state[i][j] == 1) state[i][j] = 2;
if (state[i][j1] == 1) state[i][j1] = 2;
if (state[i1][j] == 1) state[i1][j] = 2;
if (state[i1][j1] == 1) state[i1][j1] = 2;
}
else
{
h00 = state[i][j];
h01 = state[i][j1];
h10 = state[i1][j];
h11 = state[i1][j1];
if (rand() < RAND_MAX/2)
{
state[i][j] = h01;
state[i][j1] = h11;
state[i1][j] = h00;
state[i1][j1] = h10;
}
else
{
state[i][j] = h10;
state[i][j1] = h00;
state[i1][j] = h11;
state[i1][j1] = h01;
}
}
}
}
}
return 0;
}
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

Even if you’ve never seen C before you ought to be able to understand
the C implementation by comparing it to the Ruby one.

Josef ‘Jupp’ Schugt

Hi again Jupp,

i don’t want to start a flamewar here, trust me.
I admit that C is faster than ruby in all situations
that might matter (except developing speed).

Nevertheless some comments to your code:

def output_state(state, tick)

this is where half the time is spend - at least on my system

state.each do |row|
  row.each do |elem|
    file.puts elem.to_s
  end
end

replacing this with

 file.puts(
   state.map do |row|
     row.join("\n")
   end.join("\n")
 )

dramatically cuts down the time spend in IO.
A simple

file.puts state

does not. Which might give a hint on why this is so slow,
puts is recursively called for every element in the array
while join is only called once for each row.

end
end

You create large new arrays here every tick.
To be fair replace it with

def frozen_out?
not any? {|row| row.member?(1)}
end

cls
j1 = (j + 1) % cols
if [ state[i][j],
state[i][j1],
state[i1][j],
state[i1][j1] ].member?(2)

this creates new arrays in the innermost loop…
better do a simple

     if (state[i][j]   == 2 ||
         state[i][j1]  == 2 ||
         state[i1][j]  == 2 ||
         state[i1][j1] == 2)

if you care for speed (you do that in C)

      state[i1][j], state[i][j],  state[i1][j1], state[i][j1]
    end
  end

parallel assignments do create arrays also.
do the same as in C:

   else
       h00 = state[i][j];
       h01 = state[i][j1];
       h10 = state[i1][j];
       h11 = state[i1][j1];
       if (rand < 0.5)
         state[i][j]   = h01;
         state[i][j1]  = h11;
         state[i1][j]  = h00;
         state[i1][j1] = h10;
       else
         state[i][j]   = h10;
         state[i][j1]  = h00;
         state[i1][j]  = h11;
         state[i1][j1] = h01;
       end
   end
  j += 2
end
i += 2

end
end

[…]

Well that’s it. At least my ruby version doubled its speed.
(but i only tested for small simulations, would you run these
modifications to see the difference on your system with your
data?)

Josef ‘Jupp’ Schugt

cheers

Simon

  • Simon Kröger, 15.03.2007 22:45:

settings = get_settings
cols = settings[“cols”],
rows = settings[“rows”],
prob = settings[“prob”]

this isn’t realy what you wanted, right?

Well, I wanted no lines longer than 69 chars :slight_smile:
looked different before…

Josef ‘Jupp’ Schugt

On Mar 12, 2007, at 11:41 AM, Albert Ng wrote:

Did some testing, and came out with this…
BLUE = [ 0, 255, 0].pack(“C*”)
GREEN = [ 255, 0, 0].pack(“C*”)
RED = [ 0, 0, 255].pack(“C*”)

is it just in my PC?

Weird, I can’t think how that is possible…

James Edward G. II

Did some testing, and came out with this…
BLUE = [ 0, 255, 0].pack(“C*”)
GREEN = [ 255, 0, 0].pack(“C*”)
RED = [ 0, 0, 255].pack(“C*”)

is it just in my PC?

On 3/12/07, Albert Ng [email protected] wrote:

I’ll try it out on the Linux side as soon as this 500x500 sim’s done :slight_smile:
My 512x512 sim took 2 hours :frowning: but the ppm files will stay for
eternity so runtime was about 0 ;).

I’ll try it out on the Linux side as soon as this 500x500 sim’s done :slight_smile:
By the way, this quiz is addictive!

On Mar 12, 2007, at 11:47 AM, Albert Ng wrote:

seems like the mailing list doesn’t like ppm attachments, ate my last
message…

The list has a size limit. Try zipping the file.

Previous message said:

Hey, James, I ran your solution in my PC (running win2k), and the
ppm came
out red instead of blue…

Weird. I don’t have any good guesses on that one… :frowning:

James Edward G. II

seems like the mailing list doesn’t like ppm attachments, ate my last
message…
Previous message said:

Hey, James, I ran your solution in my PC (running win2k), and the ppm
came
out red instead of blue…

Given a square SimFrost, what’s the average vapor% so that the number of
steps ~= size of side?
Gah!, got to go to school, or else it’d eat up the remainder of the
afternoon.