June 2009
Click on the thumbnails below to go to albums of the family in Wareham.
![]() |
| The barn |
![]() |
| June2009 |
![]() |
| corfe |
![]() |
| WeymouthMarch |
| From WeymouthMarch |
How Lyx works with sweave
Below is an animated Gif that should show the way R code can be embedded in a Lyx document and compiled to form the document on reshaping data mentioned in a previous post. Click on the image to run the animation. Click here to see the final document reshapingdata

The Lyx document can be downloaded here. Change the extension from .doc to lyx.
reshapingdata-copylyx
Reshaping data in R
The text below lacks graphics and tables, However just click on the blue first paragraph to download it all as a PDF .
Duncan Golicher
Students should be taught to collect and hold data in a standardized “long” form in which there is only one variable for each form of measurement from the start. This resolves most problems and saves hours of tutors time. However even of they do, they still need help in reshaping this data to their own needs. This is especially true if they use SPSS. Data reformatting in SPSS is very complex and confusing and SPSS does not have powerful generic routines for handling very complex operations.
There are many tricks for handling data in R using tapply, lapply, stack, aggregate, by and a range of other functions. However R now has an efficient and powerful syntax for data handling provided by Hadley Wickham’s elegant reshape package. I have only just discovered reshape and I am very impressed. Reshaping operations were always far easier in R than in a spreadsheet, but that wasn’t to say that they were ever that easy. With reshape they are a lot simpler. I now think I can safely trust my students who use R to be able to handle most of the cases they come accross with a little thought and guidance. As an example here is some data extracted from tables of goals scored in the 2006 -2007 and 2007-2008 football season.
http://www.soccerstats.com/adv_scoring_times.asp?league=england
The number of goals scored by each team are identified by the fifteen minute period of the match (0-15 = m15, 15-30 =m30 etc) and the year when the season started. This is not raw data. That would consist of the exact times the goals are scored identified by team. The data tables available on the web site are in a wide format. There was an issue caused by the fact the original tables hold for and against goals together. This had to be resolved using strsplit. However this is a different matter that I don’t go into here. The reshaped data looks like this. Note how xtable can provide nicely formatted tables for reports.
Visualizing data in long format using R
If data is in this standard “long format” everything is just so easy. For example after loading lattice a box plot is produced simply by using the standard model formula.
Or the boxplots can be placed the other way around.
The plotmeans function in gplots is very useful for plotting confidence intervals. Notice this is not Hadley Wickham’s ggplot package, it is Greg Warnes gplots. This has a very convenient function for plotting confidence intervals for means, one of the more difficult common operations in R for students to achieve.
Modelling data in long format
It is particularly nice to have data in long format because the way we visualize the data using formulae corresponds directly to a simple linear model for the data
There is clearly one significant main effect. This is the time in the match. Neither season nor interaction is significant.
The effects package can be used to form a very quick graphical picture of the model that is also an effective alternative to using plotmeans.
Notice that the main message is that more goals are scored before half time and at the end of the match. Some of this may be attributable to a few minutes injury time being added on, but there is a upward trend anyway in both halves.
Reshaping data
The standard “long” format unifies data analysis and visualization in R. Unfortunately we do often need to switch between this convenient long format and wider formats for presentation of data as tables and some forms of analysis.
How does Hadley Wickham’s package reshape help us to do this?
Full technical details of the package are available here
http://www.jstatsoft.org/v21/i12/paper
To kick start the process of using reshape I will provide practical examples as templates, although to understand its full power I recommend the original formal documentation.
The logic of the package is first to “melt” the data into a form that is consistent for any type of data. This is similar to the long form of the data except that one column is used to store the name of the variable and one for the value. You thus always have a number of columns that correspond to the identifying (grouping) variables + 2.
To melt the data you need to specify which are the variables used for identifying cases and which are the measurements. These can be specified as the names of the columns or their numbers. It is often quicker to use numbers.
As Hadley notes, getting data into this form is not always easy. However any properly designed “long” data set will melt like butter. Wide data sets are sometimes more challenging. Once you have the data in this standard “molten” form Hadley Wickham’s formula based approach takes over and is used to reshape it to almost any form you could want. There is something quite magical about seeing data turn itself into exactly what you need with just two lines of code, especially if you have had sufficient previous experience with Excel to understand just how time consuming it can be without reshape to help. Even with tapply, by and aggregate in R things can often be tricky. Under Windows data can be moved from and to Excel through the clipboard, so an R window can easily do the work that pivot tables previously managed in a less elegant way.
The logic of reshape is rather challenging at first. There is no free lunch. It does take a little bit of getting used to, but once mastered it is just so powerful that you will never look back. Not only can you turn long tables into wide tables, but you can easily apply aggregations using the same logic. The trick is that the variables you want as the column names are placed in the second part of a formula. Understanding this and the how to use two special variables “.” and “…” is the key to using reshape. The “…’’syntax means “all the variables” and “.” means none. This if all the variables are used to form column names a “wide” format results. Look at the example on the next pages.
Moving to a wide format
Reshape the whole table to a wide format using all the variables. Time will form the columns holding the measurements (number of goals). Notice the way … is being used in the formula.
Aggregating
Sum the goals for each team over the two seasons with Time as column header. In this case note that some teams only played in the premier league for one season. Reshape can quite easily produce a simple count for this by further aggregation and this can be used to subset the data.
Including margins
Margins can also be calculated using reshape. This is a nice feature in some cases when you need to display the data. A bad part of student’s use of Excel is their frequent inclusion of marginal totals within the columns in which the data is held. This breaks a fundamental rule. Everything in a column of data should be the product of the same measurement protocol. However marginal totals are often useful when the data is presented in a final form. This is the right time to calculate them and it is easy with reshape.
Moving from wide to long format
This is one of the most complex operations to get right using the traditional stack. There is often a need for renaming column headings. However it works fine with reshape.
A simple summary of forest inventory data using reshape
A common task is calculating summed basal areas and counts of individuals from forest inventory data. First lets make up a very short simulated data set with just four species in ten plots. The procedure for reshaping data on 400 species in 10,000 plots is exactly the same and takes no more time, although the resulting table would make a very long appendix! Notice that the species names are first kept as a separate table then merged to form the data. It is very important always to do this to avoid mistakes. I often seen students typing species names multiple times, which is clearly a recipe for disaster.
Counts of individuals are simple as the function “length” counts the number of observations in each cell. Notice that you must not include margins=T if you are going to work with the data as a matrix for multivariate analysis as this produces the row and column totals.
More interestingly we can apply a function that calculates and sums basal areas directly to the melted data in the same way.
Testing for normality 2
As a follow up to the previous post on testing for normality I have put together my take on the solutions to the issues as a set of guidelines available here.
This document clearly needs revision and expansion but I hope it may be useful
Naturalización como ciudadano Mexicano
El viernes por fin pasé mi examen de naturalización como ciudadano Mexicano. Estoy muy orgulloso del logro. He querido tomar la nacionalidad del país desde 2005 cuando apliqué. Desde entonces, la Secretaria de Relaciones Exteriores ha perdido mi expendiente en multiples ocasiones y todavía estoy esperando la carta que formalice mi estatus.
Por favor ¡vota! No te cuesta mas de un segundo.
Otro detalle sorprendente fueron las 101 preguntas que tenía que memorizar para asegurar éxito en el examen. La guia de estudio cambió desde que estaba invitado a tomar el examen, asi que tuve que hacerlo dos veces. La segunda guia fue bastante menos lógica que la primera.
Aqui esta la guia de estudio guia_estudio
El procedimiento es muy arbitrario. El candidato para naturalización recibe cinco preguntas aleatorias de esta lista esoterica. Se permite equivocarse en una. Las preguntas obviamente tienen poca relevancia como forma de evaluar la integración del candidato en la sociedad Mexicana. Hay algunas ambiguas y mal redactadas. Por ejemplo “Que era la cuenca larga”. Supongo que queria decir cuenta.
Si tienes otras sugerencias dejalos como comentarios abajo.
Aqui hay algunos ejemplos mas
Kolmogorov-Smirnov tests of normality
Click here for an explanation of the animation below
Today I had an interesting exchange regarding tests of normality when teaching introductory statistics.
I have a dilemma. The point is that I do not place a great deal of stress on tests of normality when I teach Master’s students, although I mention that they are often used. However in introductory statistics texts tests of normality are given a lot more attention, presumably in order to ensure that students are aware that normality is an important assumption for many statistical procedures. I’m all in favour of testing assumptions. But do students really know what assumptions they are testing?
I have to teach introductory statistics without confusing students or sending mixed messages. It is therefore quite a delicate matter that needs clarity.
In fact none of these statements are accurate (and its Smirnoff you are thinking of!). My own preference is to try teach students to understand why any underlying population or sampling frame might not be normal.They should also intuitively understand how the procedure used for sampling from the population may influence the properties of the sample drawn from the populations.
These properties are then treated as expected before beginning any field work. All data transformation or use of non-parametric tests are pre-planned as part of the formal protocol designed for data collection and analysis.
I really do not like any post-hoc alterations to a planned work scheme after the data are collected. At best they waste time, at worst they lead students to think that the data themselves are somehow “invalid” and thus unpublishable.
I therefore quite strongly dislike including post hoc tests of normality within the work flow of the analysis as a knee jerk procedure with a yes/no answer. This certainly does not suggest that I tell students to assume that all the preplanned analyses are necessarily valid, nor to accept that inference on the mean can be conducted without checking assumptions.
The alternative to automated tests of normality is to make sure that students always visualise the distribution of their data fully in order to understand why any assumption of normality may be wrong. I also try to encourage students understand how and why data transformations might work. Again this is usually most helpful before data is collected, but it is also a way to deal with major surprises.
Here again is the link to the pdf document I wrote that suggests a possible answer to the poll.
Click on the link above as it is easier to include PDFs in wordpress this way.
An here is a quick test of any interpretation of the results of a KS test of normality.
Just to summarise the well known reason to avoid testing for normality. If you draw a very large sample from a slightly non-normal population the test tends to provide low p-values. You should presumably reject the null hypothesis that the data could have come from a normal population and according to a strict interpretation you then can’t use your planned analysis as it would be “invalid!
However if you draw small samples from very non normal populations (as shown in the pdf) you will not reject the null hypothesis as often, even though the methodology will provide misleading inference.ksdemo3
Draft beginners R course
As a follow up to today’s post on Lyx I have produced two presentations for a beginners course using Lyx/Beamer/Sweave.
I developed a very simple working protocol for making Beamer presentations with sweave. Once everything is set up it is simple and productive. I use the standard beamer commands for any slide without R code. I don’t ever try to mix beamer features and R code on the same slide.
Here are two introductory presentations using this approach.
And the draft document (with gaps)
The source is in the zip file below (remove the .doc and replace with.zip)
Lyx and Sweave: Worth climbing the learning curve?
One of the interesting elements of using Linux is the demystification of many *nix concepts that you might have come into contact previously in a lateral manner. One of these is Latex. Any R user in Windows quickly becomes aware that Latex exists. However Latex is fundamentally a *nix thing. It has even been claimed by Windows users that Latex is a legacy typesetting paradigm!
There are certainly some issues with the complexity of Latex. However there is no denying that Latex documents look impressively formal. Personally I think it is worth the effort to look seriously at latex, even if you are a complete newcomer to Linux.
I was curious about Latex. However I readily admit that I really couldn’t be bothered to learn latex as such. Life is far too short. Fortunately I found Lyx. Lyx is Latex for the lazy. No need to learn all the details, it is advertised as a WYSWYM latex typesetting program (What you see is what you mean).
So how do you use Lyx? The first important tip is to make sure that you install ABSOLUTELY, BUT ABSOLUTELY, EVERYTHING remotely relevant to TEX and Latex before starting anything with Lyx. Fonts, languages, the lot. This avoids later frustrations with missing sty files etc. I can’t remember offhand all the packages I needed, but do go to Synaptics and look for texlive-full plus anything else remotely related with either tex or latex. This will mean quite a long initial download but you certainly won’t regret it. Without all the Tex/Latex stuff installed the Lyx experience can be frustrating. You are likely to get at least a few annoying and incomprehensible error messages when compiling documents. This could give you the feeling that the whole system is more trouble than it is worth. You will add about 500 MB to your install in total, but that shouldn’t be a problem.
The next step before using Lyx seriously for work is to analyse your own ability with Word or Open Office. The idea of using Lyx is to save time in the long run. Experienced Office users can probably replicate everything Lyx or Latex can do. However many of us do have problems writing long documents such as theses or technical reports in Office suites. It becomes very difficult to maintain a consistent style. I now find Lyx easier to use than any office program for long document. The logic of using Lyx is to improve productivity, not make simple tasks much more difficult. Define what was most difficult for you to use in an Office suite and find a consistent way to achieve it in Lyx. My main problems were with positioning figures on the page and producing correctly structured tables of content. Both are very easy in Lyx once you have found out how, but there is an initial learning curve.
Then follow the examples in the Lyx documentation and allow some time for experimentation.
Sweave in Lyx
Most R users will be very interested in the use of Sweave with Lyx. This has been made possible by the work of Gregor Gojanc. I have only recently realised just how cool this can be. Once all the Latex extras are installed in Ubuntu following the instructions in “INSTALL” here worked well.
http://cran.r-project.org/contrib/extra/lyx/
A faster way of getting to this point would be to download the file below which contains my .lyx directory hidden as a zip file with fake doc extension. Replace the whole of the .lyx directory you have in your home directory by mine. Remember to use control H to see hidden files. You might want to back up your original directory first, but the replacement shouldn’t cause any issues.
Then do tools/reconfigure in Lyx and you should be able to use Sweave. My directory also has a layout incorporated for making beamer files that I got from here.
http://ggorjan.blogspot.com/2008/09/using-beamer-with-lyx-sweave.html
Here is an example
The source in Lyx that made this is available here (again take of the doc extension and change it to .lyx), You’ll need beamer-latex installed to compile it and you will have to provide your own logo picture.
And here is an early draft of a course for beginners to R that I am writing in Lyx/Sweave. If the documents compile then you have everything installed correctly.
Again there is a bit a sharp curve up to get Lyx and Sweave working. You will need to read the sweave manual first (A Google for Sweave will provide other material)
It is admitedly hard to get Sweave/beamer working as this is still quite an experimental concept. I found that not all the beamer features work, but you can still get some nice looking slides. The easiest way to use beamer for the time being is to adapt my template by cutting and pasting the box of “ERT” for every new slide, changing the R code within them to what you need. Some styles such as Title and Author stop the document compiling, so don’t change the title page much. Remember to put your own logo in the graphic. The huge payoff in terms of time saved producing slides is made by \begin{frame}[shrink,containsverbatim]. The shrink option automatically adjusts R output to the page. Great as long as you don’t print a huge object. Also notice the use of xtable and <<results=tex>> in code chunks to produce formatted tables.
Inserting a histogram into a normal Lyx/Sweave document like the R course is very simple. In an ERT box you just need to write.
<<fig=T>>=
hist(x)
@
The great thing about this way of working is you know all the R code you are showing actually runs, as they document won’t compile if you’ve made a typo or syntax error.
I will be mentioning Lyx with bibtex in a later post as this is another potentially major productivity booster that may need some help to use at the start.
A presentation for the first class on the introductory R course I am writing is now available here
Accidente en el cruce del pequeño sol
(El siguiente episodio esta disponible aqui http://duncanjg.wordpress.com/2008/09/27/accidente-2-el-valor-de-la-verdad-en-chiapas/)
Hoy nuestra famila sufrió un evento muy estresante. Adriana esta involucrada en un accidente de tránsito en el cruce del Pequeño Sol.
Afortunadamente el choque por si fue relativamente leve. Ni Adriana ni Mickey estaban lesionados. Hasta el daño al coche no fue tan severo. Pero desgraciadamente la forma en la cual el policía de tránsito y el representante del agencia de seguros manejaron el asunto ha dejado mucho daño psicológico.
Adriana estaba parada en el crucero esperando que una camioneta diera vuelta en frente de ella a la izquierda. El conductor de la camioneta dio señales con sus faros para dar prioridad a Adriana de dar vuelta a su propia izquierda. Adriana no estaba convencida y no se movió. El conductor dio el señal una segunda vez. Entonces ella empezaba a cruzar. En este momento un taxi atrás de la camioneta se desesperó y aceleró a toda velocidad rebasando ilegalmente por el lado derecho de la camioneta. El taxi (con matrícula 31-68- BHC y calcomanía del alien) embistió el auto de Adriana. Había múltiples testigos del accidente. Todos conicidieron exactamente con la versión mostrada en la animación en esta página. No había duda sobre lo que pasó y tampoco había ninguna otra explicación viable al accidente. Desafortunadamente el conductor de la camioneta se fue, evidentemente no quería involucrarse. Estamos buscandolo para ayudar en aclarar los acontecimientos a los autoridades. El oficial de transito niega aceptar la existencia del tercer vehiculo dado de que no estaba presente cuando el llego.
El taxista claramente había actuado en una forma muy imprudente y peligrosa, dejando que su impaciencia dominaba todo sentido común. Adriana no podía ver el taxi por el tamaño de la camioneta. Además ella estaba señalando que daba vuelta a la izquierda. El taxista ni la vió.
Al principio el evento parecía un poco triste y frustrante pero fácil de resolver. El coche estaba asegurado y además Adriana no tenía la culpa. Sin embargo se complicó mucho al llegar el policía de tránsito, el agente de seguros y un montón de compañeros del taxista. Mientras Adriana todavía estaba en estado de shock ellos hablaron entre sí. Dijeron que Adriana había causado un accidente por “impedir el tránsito libre”. Al final no daban otra alternativa a Adriana mas que firmar un papel en el cual ella se responsabilizaba del evento y en el cual ella solo estipuló: -acepto la “parte de responsabilidad” que me corresponde.
El último daño a nuestra tranquilidad pasó a las cinco de la tarde. Ya Adriana estaba tan estresada que no podía enfrentar la situción mas. Yo fui a una reuníon en la delegación de tránsito con el represesntante de seguros Tepayac, un tal señor Homero Trujillo.
Explique mi inquietud sobre la forma que mi esposa había sentido forzada de aceptar responsiblidad por un accidente que ella no causó, en contra del interés de su propia compañía de seguros de evitar pagos innecesarios. El me explicó claramente que no había alternativa aparte de pasar dos meses sin coche esperando un dictámen legal del Ministerio Público, el cual seguramente ibamos a perder por el poder político del dueño del taxi como líder del cooparativo.
Lo curioso es que a pesar de la rabia que sentia acepté los argumentos por pragmatismo. Dije al Sr. Trujillo que firmaré culaquier papel para que no se alarga el asunto. Necesitamos el coche. Al entrar en un proceso legal se puede retener en el corralon durante varios meses. Pero el Sr. Trujillo claramente ya tenía otra agenda distinta. Salió a llamar por celular al dueño del taxi. Cuando llegaron los taxistas ya no estaban dispuestos de hacer nungún trato. El señor Trujillo dijo que nosotros no debemos preocuparnos sobre el costo del proceso legal largo que se estaba empezando, la compañía Tepeyac pagará todos los gastos asociado con los procedimientos legales. Pero no tendríamos el coche durante meses y tendríamos que pasar varios dias de cada semana esperando turno en el ministerio.
Si yo fuera accionista en la compañía Tepeyac estaría cuestionando mucho esta forma de operación. Una compañía de seguros tiene la obligación de no aceptar un pago innecesario. El taxista no estaba asegurado, asi que para nosotros sería mas difícil recuparar el daño al coche si estabamos esperando el pago por parte del dueño del taxi. Pero estariamos dispuesto de aceptar este riesgo si la taxista nos da la razón. El causo el accidente, no fue Adriana. La retención del coche en el corralón (500 pesos por día) nos cuesta mucho mas en tiempo perdido y obviamante mucho mas a la misma compañía de seguros. ¿Cuales intereses realmente representa Sr Trujillo?¿Los avogados, la compania Tepayac, o otros?
Graficos malos en ecologia
Acabo de ver una pagina interesante del departamento de Estadistica de Vanderbilt University. Aparentemente el departamento tiene la politica de prohibir el uso de untipo de grafico que sigue siendo injustamente popular en Ecologia, los “dynamite plots”. Una vez un arbitro me regaño por haber usado un grafico de barras de este tipo. Tenia mucha razón. Son malos.
Entonces, llevo varios años diciendo a los estudiantes que odio estos graficos. Normalmente un boxplot o dotplot es mejor. Al mismo tiempo llevo años escuchando la respuesta por parte de otros tutores de que boxplots son “meramente descriptivos”. Hay que publicar graficos de barras con “intervalos de confianza”, aun cuando los intervalos de confianza son engañosos y mal fundamentado porque los arbitros prefieran este tipo de grafico.
Yo por mi parte simplemente quiero ver los datos, no los supuestos.
Good Statistical Practice
General
- See our checklist
Graphics
At a department meeting on 18Oct06, statisticians in the department voted in favor of the following policy:
- In a small dataset (e.g., < 15 observations per category) it is mandatory to show the raw data in a graphic in a publication, and this cannot be done with dynamite plots (bar charts with error bars). Example
The vote was 22 in favor, 3 against. All 3 against would be in favor if “mandatory” were replaced with “usually”. Therefore the following is department policy:
- Dynamite plots often hide important information. This is particularly true of small or skewed data sets. Researchers are highly discouraged from using them, and department members have the option to decline participation in papers in which the lead author requires the use of these plots.
Simplest possible clean PostGIS install in Ubuntu Heron
Many of the pages of instructions for installing PostGIS in Ubuntu make the process seem quite complicated. Some are quite out of date.
While it is probably necessary to know a bit about the process of importing functions and languages and creating templates it is no longer necessary to get a basic PostGIS data base up and running.
If these instructions are followed carefully with Ubuntu Heron, at the time of writing, you will get PostGIS running with QGIS in a few minutes.
First place the following in your sources list either using synaptics or pasting the line at the bottom of /etc/apt/sources.list (sudo gedit /etc/apt/sources.list)
deb http://ppa.launchpad.net/qgis/ubuntu hardy main
Then
sudo apt-get update
sudo apt-get install qgis
sudo apt-get install postgresql-8.3
sudo apt-get install postgis
sudo apt-get install postgresql-8.3-postgis
sudo apt-get install pgadmin3
One small step that is necessary is to change the user password for postgres within the database as for some reason after installing PostGIS it is no longer the default value “postgres” (Although the linux password for postgres is) . You can do this with psql. Care needed here. This has to be done correctly. The following line gets you into psql.
sudo -u postgres psql -d template1
Type this (being very careful with quotation marks and the semicolon).
alter user postgres with password ‘postgres’;
If successul you get a message saying ALTER ROLE (If there is any problem here then retype the single quotation marks to make sure they are simple. WordPress keeps changing them for some reason if they are not in an HTML box).
Then exit psql with \q or control d
Now create a database
sudo -u postgres createdb gisdb
Download a small test database with the countries of the word from this site with wget. Again the file is disguised as a word doc in order to go into the wordpress site.
wget http://duncanjg.files.wordpress.com/2008/09/paises.doc
Restore this database.
sudo -u postgres psql gisdb<paises.doc
Now run qgis and connect to your new PostGIS data base.
You can then experiment importing shapefiles into the database using the graphical plugin “SPIT” and looking at the structure of the database using pgadmin.
The trial database with a single countries of the world table can also be downloaded without wget by clicking here.
Categoria “Ecosur” en este Weblog
No fue mi intención usar este sitio para hacer comentarios asociado con Ecosur, donde trabajo. Estos comunicaciónes deben estar limitado a miembros de la propia institución.
Empecé el weblog en febrero con el proposito de tener un sitio donde puede compartir pensamientos sueltos, ideas, opiniónes y incluso experiencias de la familia con otros conocidos sin tener que copiar emails a todos. WordPress te da la opción de abrir el sitio al publico, y dado de que no hay nada en el que me causa verguenza, asi lo hice. Actualmente el weblog recibe alrededor de 100 visitas por dia de desconocidos, muchos buscando información tecnico de R y PostGIS.
Esperaba que ya por estas fechas Ecosur ofreceriá un espacio propio a cada investigador, no solamente para textos y fotos, pero tambien para datos y videos. Se requiere alrededor de 10 GB por investigador, configurado con Apache, PHP, MySQL (lo tipico) ofreciendo hosting para Drupal, Joomla, phpesp (para encuestas .. no debo tener que usar SurveyMonkey) etc. ¿Se puede tener? Claro que si. O se usa un servidor propia bien conectado al Internet o se contrat el servicio externo. No tiene que ser muy caro. El costo en el mercado sería alrededor de $5 US por mes por investigador. Pero no se ha percibido la necesidad.
Asi que sigo usando el servidor de WordPress porque es gratis y sencillo. Pero no he firmado nungún acuerdo con Ecosur sobre su uso. Este no es realmente correcto, y estoy muy conciente del hecho. Estoy dispuesto de borrar toda las paginas que he puesto en la categoria Ecosur si recibo una comunicación al respeto.
Texto de un email escrito al departamento de informatica 5 de noviembre 2007
El mensaje abajo fue escrito el 5 de noviembre 2007. Hace casi un año. Me gustaría tener la posibildad de compartir algunos de las comunicaciones previas y la contestación por parte de Informatica, pero hay que respetar el hecho de que las comunicaciones son confidenciales. No veo problema en publicar mis propias palabras.
En este epoca estaba tratando de clasificar imagenes en mi oficina y no podia mover la información. Tenia dinero para comprar mas anchura de banda para el proyecto. Pero me negaron permiso de contratarlo. La consecuencia fue el entorpecimiento del proyecto.
No fue mi intención de publicar este detalle nunca. Pero lo que me estimuló a actuar publicamente es que finalmente vinieron a mi oficina hace dos semanas para instalar Infinitum. Ya habia cerrado el proyecto y habia devuelto el dinero para telecomunicacions a Conservation International sin gastarlo. Aparentemente nunca existia una regla prohibiendo un contrato. Ademas, como evidenciado en la encuesta, estudiantes con laptos lleno de programas piratas y virus sigue contaminando la red institucional.
Estimada Ceci,
Por este medio reitero con urgencia, y con un sensación de creciente desesperación, la petición de información escrita sobre las razones del rechazo de mi petición de solucionar los problemas de conectividad en el edificio E con el uso de recursos externos contratando un servicio de internet independiente a la red institucional.
De nuevo repito que he pedido ya en mas de cuatro ocasiones la explicación para el rechazo de este petición basado en las normas institucionales o en los detalles de los contratos firmados entre Ecosur y la compania privada que proporciona el servicio de telecomunicaciónes. No he recibido este información por escrito. Información escrita es imprescindible para permitir un análisis detallada y debidamente documentado, lo cual me comprometo a hacer al recibir la información para cerrar estos comunicaciones infructíferos.
La razón de insistir otra vez es sencilla. La falta de conectividad esta afectando tan negativamente mis capacidades de realizar los labores cotidianos desde la oficina que estoy seriamente considerando la opción de trabajar siempre desde la casa. Este dia de asueto sentí que he logrado aumentar mi productividad por un factor de cinco, resolviendo asuntos pendientes rápidamente desde mi casa donde cuento con muy buen servicio de internet comercial. La diferencia era asombrosa.
También insisto que ustedes analizan mi sugerencia complementario de prohibir la entrada de cualquier laptop, equipo externo o PC que recibe USBs en la red institucional.
Al caso de estar en desacuerdo, creo que merezco un escrito formal estipulando las razones de rechazar esta ultima sugerencia. A mi juicio es sumamente necesario evitar que haya equipos de computo que entran en la red institucional (no en el internet, lo cual es otra cosa) que cuentan con derechos de administrador independientes. La razón es la seguridad. He registrado dos casos recientes de virus destructivo. Aunque estos solamente afectan equipos corriendo Windows, me preocupan el efecto que pueden tener en los equipos de mis compañeros. Muchos todavía corren Windows XP, lo cual es menos seguro que Vista (claro, ya no voy a mencionar mi alternativa preferida en el campo de sistemas operativas)
Entonces insisto en la prohibición absoluta que laptops de estudiantes forman parte de la red institucional. Al mismo tiempo lo considero absolutamente necesario que se permite que equipos de estudiantes y visitantes a la institución navegan el internet libremente bajo su propio riesgo con equipos propios físicamente dentro la institución usando una conexión que no forma parte de la red institucional, como he sugerido antes.
He consultado con varios amigos profesionales en informática en el Reino Unido. El consensos de todos es resumido en dos palabras sencillos en ingles. Son espantosos. Me impactaron. Me han dicho que estamos permitiendo el “enemy within”.
Los amigos Británicos opinan que actualmente estamos “patas arriba”. Me gustaría recibir la opinión de Abraham Mena sobre este comentario. Respeto mucho su conocimiento detallada y técnicamente fundamentado en asuntos de seguridad.
Explico los consejos brevemente. El consenso que he recibido es que nunca será factible bloquear los que tienen IPS ya adentro de la red, hay que bloquear los que están afuera, y por supuesto tratar las maquinas de estudiantes como los visitantes cualquiera, suponiendo que la mayoría son muy irresponsables y portadores de virus etc etc etc. Asi que deben entrar por el portal común, lo cual se puede controlar. Al mismo tiempo hay que respetar el hecho que los estudiantes dependen el los recursos académicos proporcionado por el internet para hacer su trabajo y darles acceso libre al internet. El hecho que ellos llegan ya todos con sus propios equipos ahorra mucho dinero al institución. Hay que respetar esta inversión y incluso estimularlo mas.
Lo claro es que es mucho mas fácil bloquear la entrada de sus IPs desde afuera donde forman parte del internet libre que tratar de bloquear todo el trafico que sale y entra. Así se puede administrar el Firewall o el servidor proxy con mucha calma y sin problemas mayores. Incluso puedes ser mucho mas estricto con los equipos ya adentro evitando el jaqueo de recursos con privilegios determinado por IP como los de la biblioteca.
Claro, hay que comprar un poco mas anchura de banda para asegurar los tomas de internet para todos, pero este es muy barato en el mercado libre (800 pesos por mes por ~2MB .. ¿o es que nosotros en Ecosur no podemos conseguir este precio por reglas de Telmex?).
El arreglo inverso es siempre incomodo, conflictivo, impopular, innecesario y no sostenible en una institución académica. Hay demasiado excepciones a cualquier regla que tratas de implementar.
Reitero. El único cambio necesario es lo que surgiere. Da a los estudiantes (y en el proceso porque no nos incluimos nosotros en el edificio E) una, o mas, tomas de internet inalambricos separados de la red institucional, como si fueron en un cybercafe. Al mismo tiempo regulariza muy bien y mucho mas estrictamente el uso de los recursos institucionales quitando todos los programas piratas etc etc etc y evitando la instalación de software no autorizado por completo.
¿Es una idea tan loca y poca convencional? Entonces por que es considerado tan obvio y de tanto sentido común por todos los que he consultado al respeto. Adémas, si TelMex no nos ofrece precios mas caros que los usuarios domésticos no representa un costó adicional. Al revés, nos ahorra un chorro.
Saludos,
Duncan
Rationality and fisheries
Politics can only fly in the face of rational scientific evaluation for so long. I have followed the debate on North Sea fisheries since my undergraduate times in Edinburgh. There was some optimism that progress would be rapid at the end of the nineties. However the narrowness of the political agenda seems to have prevented any common sense from being exercised and a policy review in 2002 was not comprehensive.
Biologists and fishery scientists cannot be expected to take into account all the social implications when advising governments. At the same time, short sighted policies aimed at placating a local electorate over a short political horizon are no way to ensure sustainability.
Previous policies have led to large amounts of scarce edible fish of reproductive age being dumped back into the sea dead, against all logic. Yet the basic premise of EU policy, that fish stocks have to be regulated at a transnational level, have always been sound. This is quite paradoxical.
So I was encouraged to read of what seems, on the face of it, to real be signs of a serious movement towards a fisheries policy based on science and common sense. What took so long?
http://news.bbc.co.uk/2/hi/europe/7621618.stm
The relevance of fisheries for a forest ecologist is that both have a tendency to suffer from the tragedy of the commons. I found this follow up on the BBC regarding individual transferable quotas extremely interesting
Resultados de la encuesta 2
A las 18:00 de la tarde el día 17 de septiembre ya habia recibido 112 respuestas a la encuesta. Cerre la encuesta un par de horas mas tarde (20.00) para evitar mas distracciones del trabajo. Hay un pdf con los resultados disponible aqui.
Debajo trato de mostrar rápidamente una parte critica de los resultados divididos por Unidad y categoría. Una gran parte (71) de San Cristóbal. Siempre es un reto presentar datos categóricos en una forma entendible para una audencia general, sin distorciones. Gráficos de pastel son las peores figuras inventadas, pero por alguna razón son muy populares. Gráficos de mosaico son mucho mejores, pero son relativamente poco usados asi que hay que explicar sus caracteristicas.
Un gráfico de mosaico es una forma de visualizar una tabla de contingencia. No son complicados. Piensa en el problema de la encuesta de Ecosur. Hay cinco unidades. Varían mucho en tamaño. Una muestra como esta encuesta refleja la población subyacente. Entonces no todas las Unidades deben pesar igual. En la última parte de la encuesta los participantes estaban invitados a expresar su opinión en una escala de 1-4. Hay una diferencia grande entre una calificación de 2 (por debajo de la mitad) y un 3 (por encima de la mitad). Al mismo tiempo la decisión es subjetiva y debe respetar el hecho de que se puede escoger entre cuatro categorias ordenales. No hay un valor absoluto, asi que tomar un promedio no tiene sentido.
Un gráfico de mosaico respeta el peso de cada parte de una muestra, dividiendolo en una forma proporcional a su tamaño. Asi que la figura abajo muestra la proporción de satisfacción (arriba desatisfecha, abajo satisfecha) con la conectividad del Internet en cada Unidad. La anchura de la barra es la proporción en cada Unidad. La altura es la proporción en cada categoría (1-4).

Gráfico de mosaico mostrando el grado de satisfacción con la conectividad del Internet en las cuatro Unidades. Rojo obscuro =mala,rojo=regular,verde=aceptable,verde obscuro=bien
Muestra un detalle interesante. El problema de conectividad al Internet, algo que que ha evitado múltiples labores productivas de investigación en la Unidad San Cristobal durante el último año, no es tan evidente en la unidad de Tapachula, pero al mismo tiempo afecta una gran proporción de la muestra entera dado el peso de SCLC.
En contraste la buena opinión sobre la biblioteca es compartida entre Unidades, aunque con muestras de problemas en San Cristóbal. En este caso, como me han comunicado muchas personas hoy, las bases de datos de la biblioteca si se ven muy bien, pero puede tardan horas en bajar los documentos de texto completos de los servidores externos que tienen los textos en la unidad de SCLC. Las frustraciones asociadas con la pésima conectividad en este Unidad ha afectado injustamente la imágen del SIBE en San Cristóbal. La conectividad a servidores externos es reponsibilidad de informatica, no SIBE.
Esta problema ha sido aparente por mucho tiempo, pero sigue sin solución definativa. (Ver este mensaje madado en noviembre del año pasado http://duncanjg.wordpress.com/2008/09/19/conectividad-en-scl/)
Los gráficos de 16 análisis de este tipo estan disponibles abajo en un solo archivo ligero de PDF. Es interesnate verlo.
Haz clic aqui para bajar los rplots en PDF condicionado por unidad y categoria.
No tengo ni el tiempo ni las ganas de analizar cada uno de estos gráficos uno por uno. Además hay otros análisis posibles si bajas los datos en R (ver abajo). Este Weblog recibe comentarios al fondo. Los datos crudos y el código R para hacer los gráficos mosaicos estan disponibles abajo (pegalo en tu consola de R y tendrás el PDF en tu directorio de trabajo y los datos cargados en un data frame llamado d en R)
library(vcd)
load(url("http://duncanjg.files.wordpress.com/2008/09/encuesta.doc"))
pdf(width=12,height=6)
for (i in 24:32){
mosaicplot(table(d$X.Categoria,as.factor(d[,i])),
col=c("darkred","red","green","darkgreen"),main=names(d)[i])}
#dev.off()
#png(file="Unidad%00d.png",w=1200,h=600)
for (i in 24:32){
mosaicplot(table(d$Unidad,as.factor(d[,i])),
col=c("darkred","red","green","darkgreen"),main=names(d)[i])}
dev.off()
Geotagging example 2
As a quick proof of the Geotagging concept (explained in Spanish here) for use in vegetation research I spent quite literally no more than fifteen minutes of my time producing a KMZ file with images of the vegetation in the field next to my house, this afternoon. This was in response to a message from a colleague who was concerned that the technique could be overly time consuming. In fact it is much more likely to be time saving.
If I had laid down standard sized quadrats and used higher resolution settings on the camera I imagine that it would be quite possible to produce standardised cover estimates for most of the species in the quadrats after the event (perhaps a a job for the long winter evenings if the work were done in the UK) , although admittedly some of the smaller cryptic species could be missed.
The spatial error was no more than 3m in my case. The spatial relationship between the “quadrats” is also correct. There is a limit to the zoom on the photos when they are looked at within Google Earth itself. However a high resolution image could always be zoomed into using other software. The nice feature of using GPicSync is that the geographical information is permanently written into the file header for posterity. When spatial visuliazation techniques become more sophisticated they will be able to use this information. However if it is not placed within the photo at the time it is taken it could be lost.
To look at my example download the file below and rename it to somethig with an *.kmz extension. For example quadratsexample.kmz. Then open it in Google Earth (downloaded from http://earth.google.com/download-earth.html)
My own geopositioning was achieved using an ultra cheap NMEA gps attached to the laptop I call tiny (for characteristics see http://duncanjg.wordpress.com/2008/09/10/ssh-dont-tell-anyone-its-so-easy/). The setup under Linux that I explained previously works very well with tiny and is very convenient to use once it has been configured.
As I understand it Windows users can get a version of gpsbabel with a graphical user interface that can be used with a Garmin GPS from here
http://www.gpsbabel.org/download.html
And they can download GpicSync from here.
http://code.google.com/p/gpicsync/
I did get a missing dll message when I tried it on my version of Windows XP. I solved it by following instructions here
http://code.google.com/p/gpicsync/wiki/TroubleShooting
But I do confess that I still haven’t gone through the whole process using Windows and Garmin. It should be extremely simple. All that is involved is
- Check that the camera time is set exactly.
- Check that the GPS is receiving enough satellites when in the field.
- Record waypoints or save a tracklog at the time when the photographs are taken.
- Download the recorded waypoints or tracklog to the computer in gpx format using gpsbabel.
- Import the photos to the computer.
- Run GPicSync to add the coordinates into the photo headers and build the kml file based on correlations between the gps coordinate time stamps and those recorded for the photos by the camera.


















































