el arte evanescente de la programacin cientfica

Download El arte evanescente de la programacin cientfica

If you can't read please download the document

Upload: jj-merelo

Post on 11-Mar-2016

218 views

Category:

Documents


2 download

DESCRIPTION

Consejos para mejorar tu tiempo-para-publicar

TRANSCRIPT

El arte evanescente de la programacin cientfica,
por Dr. Juan Julin Merelo Guervs.
De la universidad de Granada en el viejo continente de Europa

Thanks for being here. But what I wonder is, why are you here? In a tutorial about programming evolutionary algorithms? Because...

Somos malos

Muy malos

Yo, el peor

Esta charla es sobre ser un poco mejor

En programacin cientfica, nada menos

Wonderful drawing from http://www.flickr.com/photos/keeki/4264005006/in/photostream/

Y sobre el zen

Picture from http://www.flickr.com/photos/imsbildarkiv/4962991603/in/photostream/Zen means totality, and this tutorial is not just about how to write programs, but about the whole process from idea to publishing a paper in a high-impact index journal (and everything in between).So we'll make in the shape of 28 mantras that should be followed when programming evolutionary algorithms (and probably all metaheuristics)Why 28? It's more than 10, less than one hundred. And I couldn't come up with any round number of mantras. So let it be 28. Or 29. Maybe I though about a few more after I wrote this.

Y sobre escribir trabajos publicables a travs de programacin cientfica eficiente y mantenible.

Picture By MarionVosshttp://www.flickr.com/photos/ooocha/2869488840/in/photostream/

1.
Prepara tu entorno

Forge picture from http://www.flickr.com/photos/jamesclay/1396990924/in/photostream/ Todo el mundo tiene un entorno de trabajo con el que se siente cmodo: todas sus herramientas, desde el editor hasta el lenguaje de programacin que usa para procesar la salida o hacer las grficas. Importante que el entorno sea fcil de preparar y portable, que no necesite media hora para echar a andar (adis, Windows) o medio milln de pesetas (adis, software privativo)

Las herramientas del negocio

Usa sistemas operativos de verdad.

Editores de programador: kate, emacs, geany (tu editor favorito aqu) + Debugger (gdb, language-specific debugger)Crea macros, colores segn la sintaxis y comprobacin de la misma, debugging en lnea.

IDE: Eclipse, NetBeansCurva de aprendizaje inclinada, dirigidos a Java, y demasiado pesados en consumo de recursosEn muchos casos acaba mereciendo la pena

You need real operating systems to speed up the gathering of tools to start. It needs to be free and gratis, so that you can have all the libraries you need, and designed for programming, not for desktop and office environment.Programmer's editors speed up coding, allowing you to check the structure of a program at first glance. Every one has his favorite program, but you need to settle for one, since you'll be much more productive with it. Emacs or vi are probably a good choice, since you can live in them and with them.NetBeans and Eclipse are free, and popular, and good, but it's overkill if you want to do small programs and scripts (which is all you need sometimes) Plus you can't do LaTex from them.There are other IDEs for particular languages, worth checking out, but agains a minimalistic environment

2.
Libera tu cdigo y datos

Picturehttp://www.flickr.com/photos/goldenberg/22276200/in/photostream/Now it's more important than ever to open source because research topics are more and more narrower and the code is the law (maybe the law of Physics)

Pero, to...

Libera primero, programa despusEl cdigo cientfico debe nacer libre

La ciencia debe ser reproducible.

Ms fcil para otros partir de tu trabajo Se incrementa HLlegas al cielo de los cientficos.

Manifiesta suposiciones escondidas.

Si no compartes, es que te da igual.

It's the second, because the best moment to make an open source release is now, before writing the first line of code. Hay pocas razones para liberar el cdigo fuente cientfico, pero aqu hay unas cuantas (y su contraargumento)http://osl.ugr.es/2010/09/30/excusas-frecuentemente-puestas-para-no-liberar-software-y-su-contraargumento-correspondiente/

3.
Minimiza errores a travs de programacin
dirigida por pruebas

http://www.flickr.com/photos/wohinauswandern/4146824312/in/photostream/Once you want to program, you want to think about the tests first. Always test before commiting.

Tests antes del cdigo

Qu quieres que haga tu cdigo?Mutar una cadena de bits, por ejemplo.

Escribe el testEl resultado es diferente del original?Por supuesto!Lo seguir siendo si cambias una dependencia? O la representacin?

Cambia todos los bits en la misma proporcin?

Sigue la tasa de mutacin (ms o menos)?

Deja el original tranquilo?

Those are just a few examples. You might think of different tests at different levels for all parts of an evolutionary algorithm.

Una entornos de prueba

Las pruebas unitarias se hacen para pillar errores en los tomos ms pequeos de un programaInterfaz, clase, funcin, decisin.

Todos los lenguajes tienen su entornoPHPUnit, jUnit, xUnit, DejaGNU...

Escribe tests para que fallen, no para que vayan bien.

http://www.flickr.com/photos/paulwatson/43393028/in/photostream/

En principio, DejaGNU sirve para cualquier programa que se pueda ejecutar desde lnea de rdenes http://en.wikipedia.org/wiki/DejaGnu Yo, la verdad, no lo he usado. Perl tiene una cantidad de clases muy extensiva para probar todo tipo de cosas, desde pginas web hasta expresiones regulares.

4.
Controla la fuente de tu poder

http://www.flickr.com/photos/anotherpioneer/5252749975/

Los sistemas de control de fuentes te salvan el culo

Los sistemas de control de cdigo permiten...Checkpoints

Interaccin estigmrgica

Responsabilidad invidual sobre cambios en el cdigo.

Ramas

Sistemas distribuidos de moda: git, mercurial, bazaar

Centralizados, demods: subversion, cvs.

Copia de seguridad instantnea!

Recordaremos esto cuando hablemos de las copias de seguridad, pero el efecto colateral, que es no perder el trabajo, al final es lo que te salva el culo.

Cdigo completo

Bjate el cdigo/actualzalo

Haz cambios

Haz commit (y push si hay repositorio central)

Cdigo completo

Bjate el cdigo/actualzalo

Haz cambios

Prueba tu cdigo

Haz commit (y push si hay repositorio central)

5.
S agnstico para el lenguaje

http://www.flickr.com/photos/youngrobv/2497132840/That means that you shouldn't believe that a single language is the revealed Truth to which all others should kneel, and that outside that language lies hell and eternal condemnation.

El lenguaje le da forma al pensamiento

No te creas todo lo que dicen:Los lenguajes compilados son ms rpidos... pues no

No existe el almuerzo gratis.

Evita programar en C en cualquier lenguaje que uses

Consider DSL: Damn Small Languages/Domain specific Languages

Python, Perl, Lua, Ruby, Javascript, Clojure... los lenguajes interpretados son ms rpidos.

Old saying goes Fortran programmers are so good they can write fortran programs in any language. Fortran is out of fashion, but people now write C programs in any language (even in C). Speed will depend on many factors, and every language is geared for particular features.De hecho, Python se usa mucho en programacin cientfica. Aqu tienes 10 razones http://www.stat.washington.edu/~hoytak/blog/whypython.html

El culmen del agnosticismo

Evolving Regular Expressions for GeneChip Probe Performance Prediction

http://www.springerlink.com/content/j3x8r108x757876w/

Las expresiones regulares estn codificadas en AWK:Although this may seem complex, gawk (Unix free interpreted pattern scanning and processing language) can handle populations of a million individuals.

Aho, Weinberger, Kernighan, AWK is a data-driven language included in all Unices. Extremely mature, extremely fast, extremely unknown... and also the best tool for this paper.

Velocidad de programacin
>
velocidad del programa

6

Foto: http://www.flickr.com/photos/gnackgnackgnack/3297936548/in/photostream/Programming speed is more important than program speed. It does not make sense to spend days programming something to be able to run it in 2 minutes instead of 6. Or even 10.

Cientficos, no ingenieros de software

Nuestros plazos son para trabajos, no para publicaciones de productos.

Lo que se debe optimizar es la velocidad de publicacin.

Cuanto tiempo pasas escribiendo el programa/ejecutndolo/escribiendo el trabajo?

Los lenguajes interpretados molanY minimizan el tiempo-hasta-publicacin.

Perl ms rpido que Java?

Algorithm::Evolutionary, a flexible Perl module for evolutionary computationhttp://www.springerlink.com/content/8h025g83j0q68270/ Clase por clase, Perl ms compacto que JavaMenos cdigo que escribir.

Dentro del cdigo evolutivo puro, Algorithm::Evolutionary ms rpido que ECJ

In fact, test by Kernighan and Pike over Markov chains, back in 99, proved the same. Things have evolved, but in both languages. Scripting languages like Perl (or Python, or Ruby) require less effort to write even complex applications. De hecho, Java se puede mejorar mucho usando una serie de optimizaciones de la mquina virtual. Pero tambin Perl. En una carrera, no hay ganadores claros salvo el que sabe sacarle el mximo partido al lenguaje.

10.
Convirtete en un adepto del lenguaje elegido

http://www.flickr.com/photos/inoxkrow/1041584485/in/photostream/It could contradict with your agnosticism, but let's say you should be pragmatic, like Japanese, and believe in three or four languages, and be agnostic on which one using at a particular time.

Si a sus aos no se ha acostumbrado...

Tu primer lenguaje es una marca de fuego.

Pero no hay dos lenguajes iguales.

Todos los lenguajes incluyen soluciones muy eficientes paraExpresiones regulares

Proceso simblico

Grficos

pero no todo a la vez

Equilibrio entre eficiencia y conocimiento.

There is a balance between efficiency in programming and efficiency when doing a task. There's a power law: you can be best at one, maybe 3 languages, but at least know the potentialities of several others. Or at least know enough to tell a graduate student where she should look.

11

No supongas: mide

Foto de http://www.flickr.com/photos/marcelgermain/2071204651/in/photostream/

Las prestaciones importan

Medida bsica: tiempo de CPU medido por time

jmerelo@penny:~/proyectos/CPAN/Algorithm-Evolutionary/benchmarks$ time perl onemax.pl0; time: 0.0032741; time: 0.005438[...]498; time: 1.006539499; time: 1.00884500; time: 1.010817

real0m1.349suser0m1.140ssys0m0.050s

Don't ask me how you can do that in Windows, I told you already you should use a real operating system for development.

Ms profundo: profilers

A profiler, which is available for every computer language but we show here for Perl, allows to know how much time is spent in every function, and then in every line of every function. That allows identification of bottlenecks, and surgically directed optimization.

El tamao importa

Parameters of an evolutionary algorithm really matter, and the two main ones are chromosome and population size. This is, BTW, one of the first purely evolutionary-algorithmic stuff I introduce here. It can vary in complex ways, and differently depending on implementation, computer languaje, and lots of other factors. In this case what is being measured is the running time of three different implementations.Details in http://www.springerlink.com/content/a618063033u34177/You probably know this already. But it's good to remember it from time to time.And happens all the time. Algorithms, at all levels, are rarely linear. Implementations, too.

Siempre hay un mejor algoritmo/
estructura de datos

12

How can you optimize? By looking for a better algorithm, like the cat is doing.Picture from http://www.flickr.com/photos/broterham/13140244/in/photostream/

Las diferencias son grandes

Los algoritmos de clasificacin son un ejemploY realmente los necesitas?

Usa caches para acelerar la evaluacinCambia CPU por memoria (o viceversa)

Miles de formas de calcular algoCmo calculas el nmero de unos?$fitness_of{$chromosome} = ($copy_of =~ tr/1/0/);

Los algoritmos interaccionan con las estructuras de datos

Instead of sorting, some algorithms just need the max or two max. You have to look for the best implementation in your programming language of choice.

A choide of data structure forces using lenguage function and algorithms, which might be slow or the other way round. For instance, if you use a string instead of a bitvector you will be forced to use string operations a language might not be prepared for.

13

Aprende los trucos del negocio

Image from http://www.flickr.com/photos/adactio/502362353/in/photostream/

Estamos en dos negocios

El del algoritmo en el que estemos trabajando.T y tu algoritmo, uno soloNo funciona, pero por una razn diferente por la que crees que no funciona

El de los lenguajes de programacin Qu funcin est mejor implementada?

Hay otra biblioteca ms para clasificar?

Dnde deberas ir si hay un problema?

Incluso un tercer negocio: el de la programacin en s.

Caso de estudio: ordenacin

La ordenacin se usa de forma rutinaria en los algoritmos evolutivos, por ejemplo.Pero tambin en muchos otros.

Ordenacin ms rpida (en Perl): http://raleigh.pm.org/sorting.htmlOrdenar implica comparar.

Orcish Manoeuver, Schwartzian transform

Sort::Key, la ms rpida http://search.cpan.org/dist/Sort-Key/

Realmente, de veras, tienes que ordenar? En algunos casos basta con extraer los n mejores o peores.

Facilita el procesamiento de la salida

14

Imagen de http://www.flickr.com/photos/lwr/3462352862/in/photostream/

Evita ahogarte en datos

Cada experimento produce megas de datosTiempos, vectores, matrices, matrices asociativas...

Difciles de entender despus de cierto tiempo.

Usa lenguajes de serializacin para almacenar los datos.YAML: Yet another markup language

JSON: Javascript Object Notation

XML: eXtensible Markup languajge

el que ms rabia te d.

Remember that Excel sheets are not the best way for doing this. The languages above are much better at serializing any kind of data. For the same reason, CSV is no good either.

Un ejemplo: MasterMind

Entropy-Driven Evolutionary Approaches to the Mastermind ProblemCarlos Cotta et al., http://www.springerlink.com/content/d8414476w2044g2m/La salida est en YAML

IncluyeParmetros del experimento

Datos por ejecucin y por generacin.

Tiempo de ejecucin y poblacin final.

Libre!

Cuando todo falla

visualiza

15

De hecho, tambin lo aconseja en The practice of programming: hacer tests estadsticos simples.It's an example of evoluitonary algorithm for MasterMind. It does not work very well: too many copies of a single one in the population.Having a YAML log allowed easy off-linen visualization of the evolution of the population.

16 a 25

Saca copias de tus datos

Image from http://www.flickr.com/photos/dacran/2369215001/in/photostream/'nuff said!

Mejor a salvo que sin publicar

Usa un ordenador viejo para copias de seguridad.

En algunos caso, crea entornos virtuales para reproducir el entorno de un trabajoSeguro que gcc 3.2.3 funciona en Ubuntu 12.10?

Usa rsync, bacula o simplemente cp

No se trata de si tu disco duro va a fallar, se trata de cuando.

La nube est bien, pero las copias mejor.

26

Mantn tus cosas juntas

Picture from RealBlades http://www.flickr.com/photos/xtl/3007809619/

Dnde dej las llaves?

Trabajo: programa + datos + grficos + registros de experimentos + texto + revisiones + informes revisores + presentaciones.

Los experimentos deben ser reejecutados, los grficos retrazados, trabajos reescritos.

Usa registros para saber qu parametros produjeron qu datos que produjeron qu grficosMejor si no tienes que hacerlo.

Ponlo todo en el mismo rbol de directorios

Y cuanto se tardMejor si no tienes que hacerlo: todo su entorno de trabajo produce esto automticamente, uniendo todos los elementos necesarios para producir un paper.

Considera programacin literaria

Literate programming consiste en crear en un solo documento la descripcin de un trabajo y el programa que lo lleva a cabo.

Algunos programas permiten escribir en LaTeX e insertar cdigo del paquete estadstico R.

Consultar disponibilidad para tu plataforma favorita.

En todo caso, no es la forma ms popular del mundo de escribir trabajos.

Sal y huele el aire

27

Picture by Fernando Rodrguez, http://www.flickr.com/photos/frodrig/5317382828/

Lo nuevo siempre es mejor

Los paradigmas de programacin cambian a diarioNoSQL, cloud computing, internet de las cosas, Google Prediction API, map/reduce, GPGPU, lenguajes funcionales.

Mantn un equilibrio entre seguir las modas y encontrar formas ms eficientes de hacer la programacin de tu trabajoY cuando digo hacer quiero decir publicar.

Cuida tu cdigo

28

Picture by 1967geezerhttp://www.flickr.com/photos/chrisguise/5607158342/in/photostream/

Un momento de gozo, una vida de tristeza

Ejecuta tests peridicamente, o cuando haya un cambio de las dependencias o SO.Se puede automatizar.

Mantn una hoja de ruta de versiones.Recuerda, es software libre

Consigue que la comunidad eche una manoTu investigacin es para todo el mundo.

Publica, no perezcas!

Picture by doviende from http://www.flickr.com/photos/doviende/77324602/

(No se hizo dao a ningn gato preparando esta presentacin)

http://geneura.wordpress.com

http://twitter.com/geneura

http://facebook.com/jjmerelo

O camello!O becario!

/