Skip to content

Avalanche Beacon Rescue Simulator

Avalanche Beacon Rescue Simulator

Avalanche Beacon Rescue Simulator

The avalanche beacon (typically known as ARVA in Europe: Appareil de Recherche de Victimes d´Avalanches) is an electronic device used to locate/be quickly located when trapped under a snow avalanche.

Back in 2004 I presented an avalanche beacon rescue simulator as my Masther Thesis. The main goal was to try to better understand current rescue techniques, and to determine the influence of the beacons of several victims emitting all at once.

Here is the main research (in Spanish) and the source code of the simulator (in Matlab).

  1. Simulador de Rescates en Avalanchas con ARVA. Document presented as Master Thesis containing information on avalanche beacons, magnetic field, rescue techniques, analysis and development of the simulator, algorithm descriptions and user manual. Licensing information.
  2. Simulator source code (in Matlab). Licensing information.

This is not my current research topic but feel free to contact me if you have any questions.

Tagged

Simulador de Rescates en Avalanchas con ARVA

Avalanche Beacon Rescue Simulator

Avalanche Beacon Rescue Simulator

El ARVA (Appareil de Recherche de Victimes d´Avalanches) es un dispositivo electrónico que sirve para localizar/ser localizado rápidamente en una avalancha de nieve cuando realizamos actividades invernales con un grupo.

En 2004 realicé como proyecto fin de carrera un simulador de rescates en avalanchas con ARVA, dentro de la titulación de ingeniería informática en la Universidad de Zaragoza y con el Grupo de Tecno-Espeleología (ahora Grupo de Tecnologías en Entornos Hostiles). Con él se pretendía entender mejor las dos técnicas de rescate (en cruz o siguiendo las líneas de flujo) y cómo influía la presencia de más de una víctima en el ARVA del rescatador. Es un trabajo que supuso una buena investigación en tema de ARVAs y técnicas de rescate y que también ha servido para impartir formación sobre ARVAs en la sección de esquí de montaña el Club Alpino Universitario de Zaragoza.

El tema todavía sigue vigente y, aunque algo desfasado con la proliferación de los ARVAs digitales actuales, hay mucho trabajo interesante y reutilizable, así que aquí lo dejo para disfrute de todos. Texto y código están registrados públicamente en Safe Creative y protegidos bajo una licencia (más detalles en cada documento). Esto significa que, tanto el texto como el código, puedes descargarlos y distribuirlos, siempre que se cite al autor original (o sea, yo) y que sea sin ánimo alguno de lucro. Incluso puedes realizar obras derivadas (mejorarlo, reutilizar partes, etc…), siempre que se cumpla lo anterior y que se distribuya bajo una licencia exactamente igual.

  1. Simulador de Rescates en Avalanchas con ARVA. Documento íntegro depositado como proyecto fin de carrera. Contiene información sobre ARVAs, campo magnético, técnicas de rescate, análisis y desarrollo del prototipo de simulador, explicación de los algoritmos principales y manual de instalación y usuario. Registro y licencia.
  2. Código fuente del simulador (en Matlab). Registro y licencia.

Hace años que abandoné este tema de investigación, pero no dudes en contactar conmigo si tienes alguna pregunta. En el peor de los casos siempre podré ponerte en contacto con alguien que te podrá ayudar.

Tagged

Working with Files: When Size Does Matter

Donald Knuth said that premature optimization is the root of all evil. And I cannot but completely agree. Abstracting to a higher level is always better for both the code writer and especially the code reader and maintainer. It also makes you focus on the problem you are solving. Optimization can be done later, if needed.

Take a look at this simple example. Imagine you have the following text file containing a set of lines:


Hi!
How are you doing?
Fine, thanks
And you?
Good
Let's execute the code
Good idea

And now you need to build an n-gram file for each n-gram size. That is, you want a 1-grams.txt file containing all lines with 1 word, 2-grams.txt with lines with 2 words, and so on.

Here is an example of how 2-grams.txt should be:


Fine, thanks
And you?
Good idea

A Shell script and some command line utilities seem great for this kind of jobs. A possible, compact solution could be the following, where you pass the original file as the first argument:


#!/bin/sh
while read line
do
  nlen=`echo "$line" | wc -w`
  echo "$line" >> `echo $nlen | tr -d ''`-grams.txt
done < $1

You can later on use uniq or sort if you want to filter out duplicate n-grams or order the files, but the previous code solves the main problem of generating the n-gram files.

This solution, as elegant and compact as it is, however, stops being practical when the input text file is of certain size. Try with a 10MB or a 100MB text file and see what happens. How long do you think it will take? 1 second? 1 minute? 10 minutes? 1 hour? Computers are fast. Really. Just try and see how long it takes.

Are you satisfied with the performance?

The following is another equivalent solution, written in python. However, in this case the generated files won’t contain any duplicate n-gram and n-grams will appear in order.


#!/usr/bin/env python
import sys

ngrams = {}

for line in open(sys.argv[1]):
  try:
    nlen = len(line.split())
    ngrams[nlen].add(line)
  except KeyError:
    ngrams[nlen] = set()
    ngrams[nlen].add(line)

for n in ngrams:
  file = open(str(n) + '-grams.txt', "w")
  file.writelines(sorted(ngrams[n]))
  file.close()

Are you now satisfied?

If you don’t wanna test both solutions (although you should) I’ll just tell you: the first one takes hours, even for moderate file sizes (100 MB). The second one takes a few seconds. Can you explain why?

When you are working with files, be very careful about performance. If you’re not happy with it, just stop and think what’s going on beyond the stage: how often are files opened, closed or written? Although elegant and abstract solutions are excellent for understanding the problem we want to tackle and they might work for small input sizes, there might be a spot where that implementation is simply useless in practical terms.

A small change in how you tackle the problem can turn your solution from really bad to excellent in terms of performance.

Tagged , , , , ,

Descargar SNOMED CT del Ministerio de Sanidad

España es miembro del IHTSDO y por tanto, tenemos a nuestra disposición la terminología médica SNOMED CT. Para ello, el Ministerio de Sanidad habilitó un área de recursos semánticos en su web.

En la página se describen los pasos necesarios para descargarlo: es necesario disponer de un certificado digital de la FNMT. El mismo que podemos utilizar para identificarnos ante las administraciones de manera electrónica. En este caso, sin embargo, se utiliza no sólo para identificarse sino para firmar electrónicamente la solicitud.

Quien tenga algo de experiencia en temas de firma digital sabe que, debido a la variedad de navegadores, versiones y formas de gestionar la firma digital, la programación del Javascript para realizar la firma digital no es nada sencilla.

¿El resultado? Es muy probable que si intentas descargarte SNOMED CT de la página del Ministerio, no te funcione.

Estos son los resultados que obtuvimos nosotros en diciembre de 2009 con diferentes navegadores, independientemente del sistema operativo utilizado:

- Firefox: “Error durante la validacion de la firma. – SIA Error. Código=038, detalles=Firma incorrecta o sin firmante para verificar, mensage=null”

Google Chrome: “Cannot call method ‘signText’ of undefined.”

- Internet Explorer: “No se ha podido instalar el componente de firma digital. Compruebe que tiene permisos de administrador de la máquina y si el problema persiste, consulte con su Administrador.”

Puestos en contacto con el Ministerio no pudieron solucionarnos el problema, achacándolo a algún error por nuestra parte en la instalación o gestión del certificado. Sin embargo, estábamos prácticamente seguros, al haber utilizado certificados digitales anteriormente, de que los problemas residían en la parte que gestiona la firma digital.

Y, efectivamente, así fue. Descargamos una versión antigua de Firefox (Firefox 2), instalamos el certificado digital en ella y procedimos a realizar la solicitud. Et voilá, la solicitud se firmó digitalmente y obtuvimos SNOMED CT. Por tanto, parece que el Javascript es muy dependiente del navegador y está pendiente de actualizar para que funcione con las versiones actuales. Quizá en estos momentos ya lo ha sido, lo desconozco.

Este post viene a cuento porque ayer, en un curso donde se encontraban reunidos los mayores expertos en SNOMED CT de nuestro país, y hablando sobre este tema, ni una sola persona había logrado descargarse SNOMED CT desde la página del Ministerio. Las únicas personas que disponían de SNOMED  lo habían obtenido mediante una suscripción propia al IHTSDO anterior a la entrada de España en este organismo.

Por tanto, mientras no se haya solucionado el problema, es necesario utilizar la versión 2 de Firefox e instalar en ella el certificado digital de la FNMT para descargar SNOMED CT.

Tagged ,

Dealing with the bib2html WordPress plugin

What about sharing your publications in an elegant way by using only a bibtex file as source? Check mine or Javier Campos‘ to see what I mean. You just need to use WordPress and the bib2html plugin. It’s pretty simple, but there are a few caveats.

First, install the bib2html plugin from WordPress using the standard procedure, directly from WordPress. Activate it. Now you just need to enter a special bibtex tag in any page or post and provide a bibtex source (local or remote).

Here is the source of my publications page (remove the asterisk in [*bibtex, just added to prevent that bib2html processed it) :

Conference Papers

[*bibtex file=http://svn.plopez.info/website/publications/pablo.bib allow=inproceedings]

Journal Articles

[*bibtex file=http://svn.plopez.info/website/publications/pablo.bib allow=article]

Others

[*bibtex file=http://svn.plopez.info/website/publications/pablo.bib deny=article,inproceedings]

The process is pretty simple, however there are two main problems with bib2html.

  1. The plugin is not working after installation: If, after installation, nothing seems to work and you receive a bunch of warnings of this kind: "Warning: fopen(..../wp-content/plugins/bib2html/data/yourbib.bib.cached.bib) failed to open stream... on line 184", then probably the data directory is missing. If so, create it (via SSH or however).
  2. The publications page does not change after  the bibtex file is updated (e.g. when adding a new publication): This plugin uses caching: I haven't researched how it works (it might reflect your changes after a given time), but if you want to see changes immediately just delete the cache file at .../wp-content/plugins/bib2html/data/yourbib.bib.cached.bib)  and refresh the page.
Tagged , , ,

Practicing Ruby with Google Code Jam

Google Code Jam is here again!

A great opportunity to practice with the excellent exercises provided. I just took exercise A from the Qualification Round 2009.

If you have a quick look at it… aren’t they asking for pattern matching? Aren’t you seeing regular expressions there? I did, they were just using “( )” instead of “[ ]“. So… why re-implement an algorithm that is already available and efficiently programmed at almost every standard library? Translate into a legal regular expression and let the library work for you.

Here is a possible solution to the problem. It lets you play again with lots of Ruby stuff and passes Google’s tests. Great for learning the language!


f = File.open(ARGV[0])

l, d, n = f.gets.split

alien_words = Array.new

for alien_word in 1..d.to_i
  alien_words.push f.gets.chomp
end

for j in 1..n.to_i
  pattern = f.gets.chomp
  pattern = pattern.gsub("(","[")
  pattern = pattern.gsub(")","]")

  test_case = Regexp.new pattern

  matches = 0
  alien_words.each do |word|
    unless(result = word.match(test_case)).nil?
      matches = matches + 1
    end
  end

  puts "Case ##{j}: #{matches}"

end

Input Files: Example in the exercise, Small file, Large file

Output Files (generated by the program above): Example in the exercise, Small file, Large file

Tagged , ,

Rakefile to download “El Quijote” audiobook

In the previous post I presented a Ruby script to download and rename “El Quijote” audiobook from a site which was far from user friendly (remember there were 126 badly named, badly ID3-tagged MP3 files to download).

There was still something not solved by the script: the ID3 tags of the MP3 files. id3lib, a library to read and write ID3 tags, comes to the rescue. We can use it from Ruby thanks to the id3lib-ruby RubyGem. Note that id3lib-ruby requires id3lib installed on your system. If you are using a Macintosh with Snow Leopard, MacPorts and RubyGems, follow these instructions to install id3lib and id3lib-ruby:


sudo port install id3lib
sudo env ARCHFLAGS="-arch x86_64" gem install id3lib-ruby -- --with-opt-dir=/opt/local

Instead of modifying the small script of the previous post to add the ID3 tag fixing code, I decided to create a Rakefile (mainly a Makefile in Ruby) and use Rake. It’s nice as a learning example because each task recreates a different step: downloading the files, renaming the files and fixing the ID3 tags. You can use each of these tasks individually (e.g. rake rename) or, by default, perform them sequentially, following the logical dependencies.

Notice again that the idea here is to play with a variety of Ruby code (code blocks, regular expressions, files, call to command-line utilities…) and Rake tasks, not to be particularly efficient or smart. I hope you have fun and learn as much as I did with this example.

To run this Rakefile you will need wget, ruby, rubygems, id3lib, and id3lib-ruby. As usual, the following code is generated live from the latest version of the Rakefile available at my repository:


require 'rake'
require 'id3lib'

TOTAL_PARTS = "2"
CHAPTERS_IN_PART1 = "52"
CHAPTERS_IN_PART2 = "74"

def fix_tag(filename, part, total_parts, chapter, total_chapters_in_part)
  puts "Fixing ID3 tag of #{filename}..."
  tag = ID3Lib::Tag.new(filename)
  tag.strip!
  tag.title = "Parte #{part} - Capitulo #{chapter}"
  tag.album = "Don Quijote de la Mancha"
  tag.artist = "Miguel de Cervantes"
  tag.disc = "#{part}/#{total_parts}"
  tag.track = "#{chapter}/#{total_chapters_in_part}"
  tag.update!
end

desc "Download all files"
task :download do
  ("01"..CHAPTERS_IN_PART1).each do |chapter|
    `wget http://www.aularagon.org/files/espa/elquijote/p1/Parte%201%20Cap%C3%ADtulo-#{chapter}.mp3`
  end
  ("01"..CHAPTERS_IN_PART2).each do |chapter|
    `wget http://www.aularagon.org/files/espa/elquijote/p2/Parte%202%20Cap%C3%ADtulo-#{chapter}.mp3`
  end
end

desc "Rename files to remove accents and whitespaces"
task :rename do
  Dir.foreach(".") do |f|
    unless (m = f.match(/Parte\s(.*)\sCap.+tulo-(.*)\.mp3/)).nil?
      File.rename(f.to_s, "P" + m[1] + "-Capitulo-" + m[2] + ".mp3")
      puts "#{f.to_s}: Removed accents and whitespaces from filename"
    end
  end
end

desc "Fix ID3 tags"
task :fixid3  do
  ("01"..CHAPTERS_IN_PART1).each do |chapter|
    fix_tag("P1-Capitulo-#{chapter}.mp3", "1", TOTAL_PARTS, chapter, CHAPTERS_IN_PART1)
  end
  ("01"..CHAPTERS_IN_PART2).each do |chapter|
    fix_tag("P2-Capitulo-#{chapter}.mp3", "2", TOTAL_PARTS, chapter, CHAPTERS_IN_PART2)
  end
  puts "DONE!"
end

desc "Default: Download, rename and fix ID3 tags"
task :all => [:download, :rename, :fixid3]

task :default => [:all]
Tagged , , , ,

Setting up an Alcatel X060 / X060s 3G USB modem on a 64-bit Windows 7

Someone I know bought a brand new PC with a 64-bit Windows 7. Unfortunately, plugging in the Alcatel X060s USB modem didn’t work.

After unsuccessfully trying a lot of drivers from the Internet, here is the only one providing a patch that works: Alcatel X060 Driver for Windows 7 (32 & 64 bits).

Update(April 14th, 2010): A reader warned me that the previous link seems to have been removed (thanks!).

Here is the new one (note, however, that this might not be the exact version I tested): Alcatel X060 Driver for Windows 7 (32 & 64 bits).

Tagged ,

Setting up Trac on Dreamhost

Warning: This worked for me on Trac 0.11.1 hosted at Dreamhost as of March 2010 but I take no responsibilities. Use this information at your own risk.

Trac is a very popular open source system to manage software development projects, but it can also be very useful for other management tasks. Installing Trac on Dreamhost is very, very easy, thanks to the available one-click install feature. However, a fresh installation of Trac is useless because, to begin with, you can’t log in to administer Trac. You need to browse the Internet for a while to figure out how to overcome this and other small inconveniences. While not very difficult, it can be time consuming and you might forget how you did it the previous time, as it happened to me.

Appart from that, you might be initially stuck at how to configure directories for different projects and their corresponding subversion repositories. There are lots of possibilities to set up all this stuff and mine might not be the best approach, but it has worked pretty well for me.

Here is what I did, just in case it comes in handy to you:



Directories, Trac and Subversion



1 – Set up a new subdomain for all your Trac projects, for example myprojects.yourdomain.info, using Dreamhost’s control panel.



2 – Create a new subversion repository that matches your project name (for example newproject) at myprojects.yourdomain.info/svn/newproject using Dreamhost’s control panel.

As a general rule, don’t create subversion repositories inside Trac projects or directories containing another application. Use a new directory or a new subdomain for all your subversion repositories. For example, don’t install your subversion repository at myprojects.yourdomain.info/newproject/svn if you plan to install Trac at myprojects.yourdomain.info/newproject. Everything seems to work until you try to commit a change.



3 – Install Trac on myprojects.yourdomain.info/newproject using the one-click advanced install from the control panel and link it to the subversion repository created in the previous step: myprojects.yourdomain.info/svn/newproject.

Trac is now installed, but you can’t log in. You need to authenticate. The easiest way is via HTTP basic authentication, which is not recommended. HTTP digest authentication is preferred (step 4).



Trac Authentication and WebAdmin



4 – Connect to your Dreamhost account using SSH and use htdigest to create a file for digest authentication, for example at /home/youraccount/trac.htpasswd:

htdigest -c trac.htpasswd whatever yournewuser

The actual name of the realm (“whatever”, in this case) is not important but it’s mandatory, as it will be used in the next step to check credentials.



5 – Add the following to myprojects.yourdomain.info/newproject/.htaccess:

AuthType Digest
AuthName "whatever"
AuthUserFile /home/youraccount/trac.htpasswd
Require valid-user

Note that realm (“whatever”, including quotes) must match what you provided to htdigest in the previous step.

Refresh your browser and check that your Trac site asks you for a username and password. You are now logged in Trac using HTTP digest authentication.

You’ll probably want to use WebAdmin to manage Trac, so proceed to step 6.



6 – Still connected via SSH? From your Dreamhost acount use trac-admin to add permissions (and check them afterwards) to yournewuser:

trac-admin /home/youraccount/myprojects.yourdomain.info/newproject

Welcome to trac-admin 0.11.1
Interactive Trac administration console.
Copyright (c) 2003-2008 Edgewall Software

Type: '?' or 'help' for help on commands.

Trac [/home/youraccount/myprojects.yourdomain.info/newproject]> permission add yournewuser TRAC_ADMIN
Trac [/home/youraccount/myprojects.yourdomain.info/newproject]> permission list yournewuser

Refresh your browser. Now a new tab called “Admin” should appear next to the Wiki, Timeline… Search tabs on the top right corner of the page.

You’re done!

Thanks to all people that have shared their previous experience installing Trac on Dreamhost. I found this post by Arash Keshmirian particularly useful.

Tagged , ,

Ruby script to download “El Quijote” audiobook

Don Quixote (Don Quijote), probably the most famous Spanish text of all times, is available for free as an audiobook (in Spanish), thanks to a cultural project from the Government of Aragón (Spain). Unfortunately, someone decided that the best distribution method was to provide the users with 126 links (one MP3 file for each chapter). Wow!

Some time ago I tried to learn some Ruby, so I wrote a small script to download the files using wget (a popular command-line download manager). My solution was not very smart, as probably wget or other tools such as curl on their own were more than enough to handle the downloads using ranges or something, but my objective was to practice with Ruby.

After downloading the files, my MP3 player didn’t like the accents and whitespaces in the file names, so I wrote another small script to rename them to something more reasonable using regular expressions.

I mixed both scripts into one (quijote.rb script). Please note that the only goal of this implementation is to practice with different aspects of Ruby (you could more easily use wget {1..n} ranges, for example). You obviously need Ruby and wget to run it:


#Download all files from website
("01".."52").each {|i| `wget http://www.aularagon.org/files/espa/elquijote/p1/Parte%201%20Cap%C3%ADtulo-#{i}.mp3`}
("01".."74").each {|i| `wget http://www.aularagon.org/files/espa/elquijote/p2/Parte%202%20Cap%C3%ADtulo-#{i}.mp3`}

#Rename files to remove accents and whitespaces
Dir.foreach(".") do |f|
  unless (m = f.match(/Parte\s(.*)\sCap.+tulo-(.*)\.mp3/)).nil?
    File.rename(f.to_s, "P" + m[1] + "-Capitulo-" + m[2] + ".mp3")
  end
end

However, notice that there’s still another stupid problem with the files once you’ve downloaded them. If you check the ID3 tags, you’ll find that the track name and album have been swapped! All chapters (tracks) are named “Don Quijote de la Mancha”, each belonging to a different Album (the chapter number)!

Track name: Don Quijote de la Mancha
Album: Cap‚tulo 01

This avoids song managers and MP3 players to catalog the files correctly, so I still need to complete the script to fix the ID3 tags of the files. Please be patient, it’s coming… (UPDATE: You can find it here).

Note: Some time after writing the script I discovered this post. In the comments there are some alternatives to download the files. Mainly, using cURL or the wonderful DownThemAll! Firefox extension.

Tagged , ,