Showing posts with label Ruby programming. Show all posts
Showing posts with label Ruby programming. Show all posts

Tuesday, August 3, 2010

Image montage with Perl Ruby Python

On occasion, you might want to create a single image from a list of individual images. The easiest way of making such an image is with ImageMagick.

ImageMagick is a free, open source, image application. Information is available at:

http://www.imagemagick.org/Usage/

If you use Windows, a compiled binary download is available:

Perl, Python, and Ruby each have their own interfaces to ImageMagick.

Today's blog provides equivalent implementations of the ImageMagick montage feature, in three languages.

Perl:

#!/usr/bin/perl
use Image::Magick;
my $image = Image::Magick->new;
my $montage = Image::Magick->new;
my $status = $image -> Read("mach_cov.jpg",
"071.jpg", "072.jpg", "073.jpg", "075.jpg",
"076.jpg", "077.jpg", "079.jpg");
$image -> Scale('200x200');
print STDERR $status;
$montage = $image -> Montage(background => "Blue",
borderwidth => "5", geometry => '+5+5',
tile => "4x2");
$montage -> Write('jpg:orig.jpg');
system("imdisplay orig.jpg");
exit;

Python:

#!/usr/bin/python
import os
os.system("montage mach_cov.jpg \
071.jpg 072.jpg 073.jpg 075.jpg \
076.jpg 077.jpg 079.jpg \
-background #0000ff -geometry 200x200+5+5 \
-borderwidth 5 -tile 4x2 orig.gif")
os.system("imdisplay orig.gif");
exit

The "\" appearing at the end of lines is the DOS command-line continuation character.

Ruby:

#!/usr/local/bin/ruby
require 'RMagick'
include Magick
orig = Magick::ImageList.new(
"mach_cov.jpg", "071.jpg", "072.jpg",
"073.jpg", "075.jpg", "076.jpg",
"077.jpg", "079.jpg")
new_img = orig.montage() {
self.background_color='blue';
self.border_color='red';
self.tile='4x2'
self.geometry='200x200+5+15'
self.border_width=5}
new_img.write("orig.gif")
system("imdisplay orig.gif")
exit

The input images are the 8 book covers that appear on the right hand side of this blog. Obviously, you'll substitute any number of images from your own collection. You'll also need to provide a an appropriate tiling geometry for the number of images you use (I used 4x2, four across and 2 down) for this example.

The output looks like this:


Each of the scripts calls provides the list of images to be included in the output image, and provides the montage method with attributes for the image display (i.e., background collor, image sizes, image border, space between images, tiling geometry).

In the case of the Perl script, the external module Image::Magick is called (available from ActiveState). In the case of Ruby, the RMagick gem is used. Users of these languages should known how to acquire these modules.

In the case of Python, a system call is made to the installed ImageMagick application. I had a little problem getting the Python script to work because the system call to the "montage" executable apparently executed some other program of the same name. This problem was skirted when I simply visited the subdirectory that held the ImageMagick files, and copied the montage.exe file over to the same subdirectory that held my Python script. When the python script was interpreted, the system used the montage.exe file in the same subdirectory as the script.

The montage method is explained in detail on the following web page:

http://www.imagemagick.org/Usage/montage/

Many of the basic algorithms of Medical Informatics, with equivalent implementations in Perl, Python, and Ruby are provided in my book, Methods in Medical Informatics: Fundamentals of Healthcare Programming in Perl, Python, and Ruby, which will be published next month by CRC Press.

- © 2010 Jules J. Berman
tags:image files, perl programming, Python programming, Ruby programming
Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.

Friday, July 23, 2010

New book coming in September

If you've noticed a decline in my blogging of late, it's because I've been putting the finishing touches on my new book, Methods in Medical Informatics: Fundamentals of Healthcare Programming in Perl, Python, and Ruby, which will be published in September in the CRC Press series in Mathematical and Computational Biology.

This book is a departure from my earlier language-specific works. The new book stresses descriptions of medical informatics algorithms, all presented in the following format:

1) Each method has a background discussion, explaining how the method is used by healthcare professionals.

2) This is followed by a narrative description of each of the steps of the algorithm.

3) Equivalent implementations of the algorithm are provided in Perl, Python and Ruby. Scripts draw data from freely available datasets (OMIM, SEER, CDC, Census Bureau, MeSH, and PubMed, Taxonomy).

4) Then comes an analysis of the output of the algorithm.

At the end of every chapter, a list of exercises provides students with short projects, that they can develop in the language of their own choice.

There are about 70 algorithms or methods provided in the book, and with a few exceptions (some of the introductory-level methods), these algorithms have not appeared in any of my prior publications.

The unique offering of this book is that students can master the fundamental methods and algorithms of medical informatics, in their preferred programming language. Instructors can concentrate on teaching useful algorithms, without wasting class time on language-specific programming instruction.

The book is divided into four parts: Part I. Building blocks of medical informatics; Part II. Free, publicly available medical data resources; Part III. The common tasks of medical informatics, and Part IV. Medical Discovery.

The purpose of Part I, Building blocks of medical informatics, is to introduce the basic computational subroutines that will be used in more complex scripts later in the book. Everyone who reads the book is expected to have a basic understanding of either Perl, Python, or Ruby. Readers can skip over the parts written for the other languages. Over the years, students will find it valuable to re-read the text, this time paying attention to the languages they ignored in the first pass.

In Part II, Free, publicly available medical data resources, students are shown how to use the U.S. government biomedical datasets. The chapters in Part II explain the intended uses of these datasets, how the data sets are organized, and how students can retrieve and analyze the data.

Part III, The common tasks of medical informatics, covers some of the computational methods of biomedical informatics, including autocoding, data scrubbing, and data de-identification.

Part IV, Medical discovery, provides examples of the kinds of questions that biomedical scientists can ask and answer with public data and open source programming languages. Students will learn techniques for combining heterogeneous data sources, measuring and visualizing trends in complex data, and testing new hypotheses. The majority of research and development projects that use biomedical data can be developed using the methods described in Part IV.

This book is written specifically as a textbook for courses in medical informatics. Instructors should appreciate this book, because it frees them to teach medical informatics, without wasting time teaching basic programming skills. The included scripts are for the students, who need code samples, from a familiar language, that they can use throughout their careers. The instructors will teach the algorithms (not the language implementations). This strategy allows instructors to teach a big subject (computational medical informatics), in a small amount of time (one academic course).

The book is designed to eliminate the inequities that result when an instructor imposes his choice [of programming language] on all of his students. Students who are trained in an alternate language will resent taking a course in an unfamiliar language. These students will be at a disadvantage compared to other students who happen to be trained in the course-book language. When a professor selects a computer language, he's usually got to start the course with the basics of the selected language, and this instruction can takes weeks of time away from the subject of the course [in this case, medical informatics]. This is just lame.

Creative Writing courses do not waste time teaching people about pens and pencils. Informatics courses should not be waste time teaching programming skills. When a medical informatics instructor tells everyone in the class to use Python, it's equivalent to a writing instructor telling everyone in the class to use a Papermate pen. A good course in medical informatics should expect students to have programming skills, but should not be focused on any particular programming language. Instructors should focus on the tasks, issues, and questions that comprise the core activities of professionals in the field. By providing a discussion of the importance and utility of each algorithm and method, instructors can teach the fundamentals of medical informatics, without wasting time teaching programming.

All of the data used in this book are free and publicly available. Most of the data comes from U.S. government sources, providing hundreds of gigabytes of high quality, curated biomedical data to a global community of scientists, healthcare experts, clinicians, nurses, and students. Every student should become familiar with these data sources, and understand their medical value. This book provides instructions for downloading all of the data sources discussed.

One of the most surprising features of medical informatics is that scripts capable of parsing large data sets, very quickly, can be quite short. By focusing on methods, not full-scale applications, scripts are kept short, concise, and easy to learn. In many cases, the scripts that implement an algorithm are actually shorter than the step-by-step description that precedes the implementation. Students will find that most of their future data analysis efforts can be accomplished by modifying and combining the scripts provided with this book.

-© 2010 Jules J. Berman


Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.

Sunday, January 24, 2010

Grabbing, Testing Web Links

Once more, I'm interrupting a series of blogs on the topic of complexity to provide a pointer to a recently constructed web page showing how to grab web pages and test web links, using Perl, Python, or Ruby.

Perl, Python and Ruby have their own external modules for HTTP transactions. Each language's module has its own peculiar syntax. Still, the basic operation is the same: your script initiates an HTTP request for a web file at a specific network address (the URL, or Uniform Resource Locator). A response is received determining if the page is available (equivalent to testing a link). With a little effort, you can modify the provided scripts to collect and examine a large number of web pages. With a little more effort, you can write your own spider software that searches for web addresses, iteratively collecting information from links within web pages.

The article is at:

http://www.julesberman.info/factoids/url_get.htm


© 2010 Jules J. Berman

key words: html, http, hypertext transfer protocol, testing link, ruby programming, perl programming, python programming, bioinformatics, valid web page, web page is available, good http request, valid http request testing if web page exists, testing web links, jules berman Ph.D., M.D.
Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.

Tuesday, December 30, 2008

Why I write scripts in Perl, Ruby and Python

Readers of this blog know that I often include equivalent scripts in Perl, Ruby and Python, for the biomedical informatics projects that I post.

It must be tedious to encounter a blog that devotes long stretches of space to scripts written in three different languages. I can imagine the groans coming from non-programmers when they see a long post full of code, while all they're interested in is the biomedical problem described in the first paragraph of the post.

I have reasons for including these scripts:

1. I want to reach all of the people who are interested in the biomedical problems discussed in my posts. Most of these problems are solved with informatics techniques. The techniques often involve a little bit of programming knowledge. Most biomedical programming is done with Perl, Ruby or Python. These are free, open source and cross-platform languages with active user communities and with abundant instructional material on the internet. If I want to attract the maximum number of readers, I've got to include solutions in all three languages.

2. I want to show readers that powerful scripts, that solve important biomedical problems, can be written in a few lines of code, regardless of the language used. Perl, Ruby and Python can all be used to write equivalent programs. For length, clarity, and speed of execution, there really isn't much difference among the major scripting languages. Biomedical scripts tend to use a few favorite commands (open a file, parse the file line by line, extract something from the lines of the file, do some sort of transformation on the extracted data, write the results to another file). These commands can be learned in a few hours.

3. I want to emphasize in all of my blogs that the difficult part in any informatics project is developing your question (i.e., asking a smart, important, and solvable question), and understanding the substance and limitations of the available data sources. Writing scripts is the easiest and most enjoyable part of the exercise.

- © 2008 Jules J. Berman
Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.

Monday, December 29, 2008

Perl, Ruby and Python scripts for CDC public use mortality file parsing

I have been interested in knowing whether sickle cell incidence is decreasing in the U.S. population. Despite Pubmed and web searches, I have not been able to find a single data source on the subject. In a prior post, I referred to one of my Perl scripts that
parsed through CDC public use records (about 5 Gigabytes of raw data). The results seemed to suggest that the incidence of sickle cell anemia in the U.S. may be increasing.

For those interested, here are Perl, Ruby and Python versions of the script that parses through the CDC public use mortality files for the years 1996, 1999, 2002, and 2004, to produce the number of occurrences and the rates for sickle cell disease cases, from death certificate data, for those years.

Please refer to the prior post for discussion of the data.

Please refer to my document describing uses for the CDC public use mortality files for general instructions on acquiring and analyzing the de-identified U.S. death certificate data.

#!/usr/local/bin/perl
@filearray = qw(mort96us.dat mort99us.dat mort02us.dat mort04us.dat);
foreach $file (@filearray)
{
open (ICD, $file);
$line = " ";
$popcount = 0;
$counter = 0;
while ($line ne "")
{
$line = <ICD>;
$codesection = substr($line,448,140) if ($file eq $filearray[0]);
$codesection = substr($line,161,140) if ($file eq $filearray[1]);
$codesection = substr($line,162,140) if ($file eq $filearray[2]);
$codesection = substr($line,164,140) if ($file eq $filearray[3]);
$popcount++;
if ($codesection =~ /D57/i)
{
$counter++;
}
}
close ICD;
$rate = $counter / $popcount;
$rate = substr((100000 * $rate),0,5);
print "\n\nRecords listing sickle cell is $counter in $file file";
print "\nSickle cell rate per 100,000 records is $rate in $file file";
}
exit;

#!/usr/local/bin/ruby
filearray = Array.new
filearray = "mort96us.dat mort99us.dat mort02us.dat mort04us.dat".split
filearray.each do
|file|
text = File.open(file, "r")
counter = 0; popcount = 0;
text.each_line do
|line|
codesection = line[448,140] if (file == filearray.fetch(0))
codesection = line[161,140] if (file == filearray.fetch(1))
codesection = line[162,140] if (file == filearray.fetch(2))
codesection = line[164,140] if (file == filearray.fetch(3))
popcount = popcount +1
counter = (counter + 1) if (codesection =~ /D57/i)
end
text.close
rate = ((counter.to_f / popcount.to_f) * 100000).to_s[0,5]
puts "\nRecords listing sickle cell is #{counter} in #{file} file"
puts "Sickle cell rate per 100,000 records is #{rate} in #{file} file"
end
exit

#!/usr/local/bin/python
import re
sickle_match = re.compile('D57')
lst = ("mort96us.dat","mort99us.dat","mort02us.dat","mort04us.dat")
for file in lst:
intext = open(file, "r")
popcount = 0
counter = 0
codesection = ""
for line in intext:
if file == lst[0]:
codesection = line[448:588]
if file == lst[1]:
codesection = line[161:301]
if file == lst[2]:
codesection = line[162:302]
if file == lst[3]:
codesection = line[164:304]
popcount = popcount + 1
p = sickle_match.search(codesection)
if p:
counter = counter + 1
intext.close
rate = float(counter) / float(popcount) * 100000
rate = str(rate)
rate = rate[0:5]
print ('\n\nRecords listing sickle cell is ')
print (str(counter) + ' in ' + file + ' file')
print ('\nSickle cell rate per 100,000 records is ')
print(str(rate) + ' in ' + file + ' file')
exit

© 2008 Jules Berman

As with all of my scripts, lists, web sites, and blog entries, the following disclaimer applies. This material is provided by its creator, Jules J. Berman, "as is", without warranty of any kind, expressed or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the author or copyright holder be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the material or the use or other dealings.

In June, 2014, my book, entitled Rare Diseases and Orphan Drugs: Keys to Understanding and Treating the Common Diseases was published by Elsevier. The book builds the argument that our best chance of curing the common diseases will come from studying and curing the rare diseases.



I urge you to read more about my book. There's a generous preview of the book at the Google Books site. If you like the book, please request your librarian to purchase a copy of this book for your library or reading room.

tags: common disease, orphan disease, orphan drugs, rare disease, disease genetics, sickle cell anemia, genetic counseling, public health, centers for disease control and prevention, international classification of diseases, cause of death, causes of death, epidemiology, Perl programming, Ruby programming, Python programming

Wednesday, December 17, 2008

CDC Mortality Data: 8

This is the eighth in a series of posts on the CDC's (Centers for Disease Control and Prevention) public use mortality data sets. In a prior blog of this series, we discussed one of the earliest medical mashups, Dr. John Snow's map of cholera occurrences for the 1854 London epidemic..

Today, we'll show how we can use the CDC mortality data set to create a mashup, using short scripts written in Perl and Ruby. Readers of this blog who are specifically interested in the topic of Ruby-based mashups should also read Data Visualization with Ruby and RMagick - Where Are Those Bikes?, by LoGeek. LoGeek's elegant blog goes much further than mine to show how Ruby mashups can work with web service APIs.

Let's pretend that we know nothing about the geographic distribution of coccidioidomycosis (commonly misspelled coccidiomycosis). We can write a short Perl script that parses through every record in the CDC mortality file, pulling each death for which the diagnosis of coccidioidomycosis was recorded, and tallying the the deaths for the states in which the deceased death certificate was recorded. This will tell us something about the state-by-state distribution of coccidioidomycosis.

Here is a Perl script that produces a list of states and the tally of coccidioidomycosis cases, culled from the 1999 U.S. mortality file.

#/usr/local/bin/perl
open (STATE, "cdc_states.txt");
$line = " ";
while ($line ne "")
{
$line = <STATE>;
$line =~ /^[0-9]{2}/;
$state_code = $&;
$line =~ / +([A-Z]{2}) *$/;
$state_abb = $1;
$statehash{$state_code} = $state_abb;
}
close STATE;
open (ICD, "Mort99us.dat");
$line = " ";
while ($line ne "")
{
$line = <ICD>;
$state = 0;
$codesection = substr($line,161,140);
if ($codesection =~ /B38/)
{
$code = substr($line,20,2);
$state = $statehash{$code};
$state_tally{$state}++;
}
}
open (MAP, ">state_count.txt");
while ((my $key, my $value) = each(%state_tally))
{
print "$key $value\n";
print MAP "$key $value\n";
}
exit

The output of the Perl script looks like this:

AZ 62
CA 53
ID 2
IL 2
IN 1
KS 1
KY 1
MN 1
MO 1
MT 1
NC 2
NM 3
NV 3
NY 1
OH 1
OR 2
PA 1
TX 18
UT 2
WA 4
WI 2
WV 1

You'll notice that fewer than 50 states are included in the list. States that had no cases of coccidioidomycosis were not added to the list. We will see that this does not effect the mashup.

How did the Perl script compile the occurrences of coccidioidomycosis in from the CDC mortality files?

The CDC mortality files include the state of record for the death certificate in bytes 21 and 22 of the record. Each state is provided with a unique two digit code. The codes, and their corresponding state name, are provided in the CDC data dictionary for the mortality file. I simply prepared a text file, cdc_states.txt, that listed all the 2-digit codes and the corresponding state abbreviations, so the raw CDC data could be converted to universally recognizable abbreviations.

The script parses through each record, and pulls the 140-byte section of the record that contains the ICD disease codes corresponding to the conditions registered in the death certificate. In the ICD, coccidioidomycosis matches "B38". The Perl script finds all of the records that match "B38" and increases the appropriate state (from byte 21 and 22) tally by one. After the entire file is parsed, it prints out the list of states that have cases of coccidioidomycosis, along with their tallies.

Once that's done, we can mashup the disease data into a map of the United States. I found a public domain outline map of the U.S. on the National Oceanographic and Atmospheric Associationon web site. I "erased" the interior of the map, leaving a minimalist outline of the U.S. upon which to project the state-specific data. You can use any map, so long as you know the longitude and latitude boundaries.



A Ruby script inserts the state data onto the U.S. map.

#!/usr/local/bin/ruby -w
require 'RMagick'
north = 49.to_f #degrees latitude
south = 25.to_f #degrees latitude
west = 125.to_f #degrees longitude
east = 66.to_f #degrees longitude
#corresponds to the us continental extremities
text = File.open("c\:\\ftp\\loc_states.txt", "r")
lathash = Hash.new
lonhash = Hash.new
text.each do
|line|
line =~ /^([A-Z]{2})\,([0-9\.]+)\,\-?([\.0-9]+) *$/
state = $1
latitude = $2
longitude = $3
lathash[state] = latitude.to_f
lonhash[state] = longitude.to_f
end
text.close
text = File.open("c\:\\ftp\\state_count.txt", "r")
sizehash = Hash.new
text.each do
|line|
line =~ / /
state_abb = $`
state_value = $'
sizehash[state_abb] = state_value
end
text.close
imgl = Magick::ImageList.new("c\:\\ftp\\us\.gif")
width = imgl.columns
height = imgl.rows
gc = Magick::Draw.new
lathash.each do
|key,value|
state = key
latitude = value.to_f
longitude = lonhash[key].to_f
l_y = (((north - latitude) / (north - south)) * height).ceil
l_x = (((west - longitude) / (west - east)) * width).ceil
gc.fill_opacity(0)
gc.stroke('red').stroke_width(1)
circlesize = ((sizehash[state].to_f)*2).to_i
gc.circle(l_x, l_y, (l_x - circlesize), l_y)
gc.fill('black')
gc.stroke('transparent')
gc.text((l_x - 5), (l_y + 5), state)
gc.draw(imgl)
end
imgl.border!(1,1, 'lightcyan2')
imgl.write("circle.gif")
require 'tk'
root = TkRoot.new {title "view"}
TkButton.new(root) do
image TkPhotoImage.new{file "circle.gif"}
command {exit}
pack
end
Tk.mainloop
exit

Here is the result.



Each state has been "pasted" into the U.S. map. States with red circles contained cases of coccidioidomycosis recorded on death certificates; the diameter of circles is proportionate to the number of cases.

With a glance, we can see that coocidiomycosis occurs primarily in the Southwest U.S. In fact, coccidioidomycosis, variously known as valley fever, San Joaquin Valley fever, California valley fever, and desert fever, is a fungal disease caused by Coccidioides immitis. In the U.S. this disease is endemic to certain parts of the Southwest.

This post has gotten lengthy. In the next blog post of the CDC mortality series, I'll explain how the Ruby mashup script works.

© 2008 Jules Berman

As with all of my scripts, lists, web sites, and blog entries, the following disclaimer applies. This material is provided by its creator, Jules J. Berman, "as is", without warranty of any kind, expressed or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. in no event shall the author or copyright holder be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the material or the use or other dealings.


Image of C. immitis in sputum sample.

Some additional information on Coccidioidomycosis is available from my web site.

In June, 2014, my book, entitled Rare Diseases and Orphan Drugs: Keys to Understanding and Treating the Common Diseases was published by Elsevier. The book builds the argument that our best chance of curing the common diseases will come from studying and curing the rare diseases.



I urge you to read more about my book. There's a generous preview of the book at the Google Books site. If you like the book, please request your librarian to purchase a copy of this book for your library or reading room.

tags: epidemiology, neoplasms, Ruby programming, rare diseases, genetic diseases, orphan diseases, complex diseases, orphan drugs, cdc, death certificates, mortality data

Thursday, May 29, 2008

Biomedical Ruby Programming

If you're a regular reader of this blog, you've read some of my prior essays about the Ruby Programming Language. My book teaches Ruby, but its content is not exclusively focused on the Ruby Language (there are many excellent Ruby language books available to programmers). My book is mostly about the tasks that confront students and professionals in the biomedical fields... and how you can use Ruby to solve those tasks. So in the book chapters, I may spend more words describing the biomedical tasks (which can be hard to understand) and many fewer words on the Ruby scripts (which are usually quite short).

The basic theme in my books is that if all biomedical workers knew how to program, they would gain some independence (from application vendors), and become more creative.

Once you start using Ruby, you may find that you can integrate your knowledge of medicine and biology with your knowledge of programming, to solve a wide range of new and interesting problems.

I recommend either Perl, Python, or Ruby as excellent languages for anyone in the biomedical sciences. I wouldn't claim that these are the best languages for programmers, in general. But they are superb languages for individuals whose primary interest lies in biology or medicine and who use programming as a creative tool to discover and solve new questions in their fields. These languages are easy to learn, and each has an active community that contributes open source libraries and modules to the language.

- Jules J. Berman


Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.

Monday, April 14, 2008

Ruby script for building phylogenetic lineages from EBI's taxonomy.dat

Taxonomy.dat is a large, publicly available list of organisms. The file is available from the European Bioinformatics Institute (EBI). It contains over 400,000 species:

[A sample record in Taxonomy.dat]

[ID : 50]
[PARENT ID : 49]
[RANK: genus]
[GC ID : 11]
[SCIENTIFIC NAME : Chondromyces]
[SYNONYM : Polycephalum]
[SYNONYM : Myxobotrys]
[SYNONYM : Chondromyces Berkeley and Curtis 1874]
[SYNONYM : "Polycephalum" Kalchbrenner and Cooke 1880]
[SYNONYM : "Myxobotrys" Zukal 1896]
[MISSPELLING : Chrondromyces]

The taxonomy.dat file exceeds 100 megabytes in length.

The taxonomy.dat file is available for public download through anonymous ftp.

[ftp://ftp.ebi.ac.uk/pub/databases/taxonomy/]

Information about the taxonomy.dat file is found at:

[http://www.ebi.ac.uk/msd-srv/docs/dbdoc/ref_taxonomy.html]

Notice that the sample entry (above) provides an ID number for the entry organism, Chondromyces, and for it's parent class. Since every organism and class has a parent, you can write a script that reconstructs the full phylogenetic lineage for any entry in taxonomy.dat.

In this blog, I include a Ruby script that parses through taxonomy.dat, builds a hash of all the child-parent relationships, then re-parses the file, building the phylogenetic lineage of each organism using the child-parent hash that was built in the first pass.

This Ruby script is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.

A copy of the Ruby script is available at: http://www.julesberman.info/taxon.htm.

Lately, I've gotten into the habit of creating Perl and Python versions of my Ruby scripts, and these are also available at the web site. All three scripts operate at about the same speed. It takes under a minute to execute these scripts on a desktop computer running at 2.6 MHz with 512 MByte RAM. You may need this much RAM to provide memory for the hash (of child-parent relationships).

#!/usr/local/bin/ruby
intext = File.open("taxonomy.dat", "r")
outtext = File.open("taxo.txt", "w")
parenthash = Hash.new()
namehash = Hash.new()
intext.each_line("//") do
|line|
line =~ /\nID\s+\:\s*([0-9]+)\s*\n/
child_id = $1
line =~ /\nPARENT ID\s+\:\s*([0-9]+)\s*\n/
parent_id = $1
parenthash[child_id] = parent_id
line =~ /\nSCIENTIFIC NAME\s+\:\s*([^\n]+)\s*\n/
scientific_name = $1
namehash[child_id] = scientific_name
end
intext.close
intext = File.open("taxonomy.dat", "r")
intext.each_line("//") do
|line|
getline = line
getline.sub!(/\/\//,"")
outtext.puts(getline, "HIERARCHY")
line =~ /\nID\s+\:\s*([0-9]+)\s*\n/
id_name = $1
(1..30).each do
outtext.puts(namehash[id_name])
id_name = parenthash[id_name]
break if namehash[id_name].nil?
end
outtext.print("//")
end
exit

The script produces an output file, taxo.txt that exceeds 224 Megabytes in length. The output consists of the taxonomic entries from taxonomy.dat, along with the phylogentic lineage for each organism.

An sample ancestral lineage, for "banana" is:

ID : 89151
PARENT ID : 4640
RANK : species
GC ID : 1
MGC ID : 1
SCIENTIFIC NAME : Musa x paradisiaca
SYNONYM : Musa paradisiaca
SYNONYM : Musa sapientum
SYNONYM : Musa acuminata x Musa balbisiana
SYNONYM : Musa x paradisiaca L.
SYNONYM : Musa x sapientum L.
SYNONYM : Musa x sapientum
COMMON NAME : banana
INCLUDES : Musa sp. RN-2001
MISSPELLING : Musa lactan
HIERARCHY
Musa x paradisiaca
Musa
Musaceae
Zingiberales
commelinids
Liliopsida
Magnoliophyta
Spermatophyta
Euphyllophyta
Tracheophyta
Embryophyta
Streptophytina
Streptophyta
Viridiplantae
Eukaryota
cellular organisms

A web site that produces the phylogeny of any entered species (in taxonomy.dat) is available at: http://www.julesberman.info/post.htm

- Jules Berman
My book, Principles of Big Data: Preparing, Sharing, and Analyzing Complex Information was published in 2013 by Morgan Kaufmann.



I urge you to explore my book. Google books has prepared a generous preview of the book contents.

tags: big data, metadata, data preparation, data analytics, data repurposing, datamining, data mining, ruby programming language, python programming language, perl programming language, phylogeny, taxonomy, taxa, taxon, ancestral lineage, classification

Saturday, March 1, 2008

Ruby Programming for Medicine and Biology limited preview at Google Books

I just noticed that the Google Book site now features a
limited preview of my book,
Ruby Programming for Medicine and Biology.

If you're curious, the Google book site is nearly as good as skimming through a copy of the physical book.

- Jules Berman

key words: biomedical informatics, book review

Friday, February 22, 2008

Ruby, Perl, and Python medical autocoding

The other day, I created a very large web page that included 20,000 PubMed abstracts and the autocoded output for each.

The web page was apparently too large for some people to view, so I cut it down to show about 10,000 autocoded samples, along with the code for the autocoder in Ruby, Perl and Python. It is all available at:

http://www.julesberman.info/rubycode.htm


For anyone unfamiliar with medical autocoding, a medical autocoder is a software program capable of parsing large collections of medical records (e.g. radiology reports, surgical pathology reports, autopsy reports, admission notes, discharge notes, operating room notes, medical administrative emails, memoranda, manuscripts, etc.) and capturing the medical concepts contained in the text.

The term "autocoding" should be distinguished from "computer-assisted manual coding." Health care workers may use a software enhancement of their Hospital Information Systems to code a section of text as they enter reports into the computer system. Typically, candidate terms and term codes [from a medical nomenclature] are displayed on the same screen as the entered report. The person entering text is often given the option of editing the proffered codes. This process should not be confused with "autocoding" and is not equivalent to the fully automatic and large-scale coding required by biomedical informaticians.

Finding all the concepts in a corpus of text is a necessary and early step in all data mining efforts. The autocoded terms can be used individually as index terms for the document, on a record-by-record basis to produce a concept "signature" that is highly specific for each report, or collectively to relate the frequency of terms within records with the frequency of terms in the aggregate document.

The simple autocoder provided (in Perl, Python, and Ruby programming languages) is fast (about 100 kilobytes of text per second) and nearly perfect. You can check the output yourself for accuracy (in neoplasm terms extracted and coded). A minor modification of the scripts will accommodate any nomenclature for which terms are assigned concept-code numbers.

- Jules Berman

key words: medical software, nomenclature, medical datamining, perl programming, ruby programming, python programming, biomedical informatics, medical informatics, autcoding, autocoder, medical autocoding
Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.

Wednesday, February 13, 2008

Ruby, Perl and Python medical autocoders

In the past two days on this blog, I've provided very short, fast, and accurate medical autocoders in Ruby and Perl. I thought I might as well offer the equivalent Python script. The Python script runs about twice as fast as either the Ruby or the Perl script.

The Ruby, Perl and Python scripts and their equivalent output are provided at:

http://www.julesberman.info/coded.htm

They are distributed under a GNU license.

All three scripts use a public domain file of 20,000 PubMed Citations, available at:

http://www.julesberman.info/tumorabs.txt

They all use an external tumor nomenclature contained within the Neoplasm Classification and available as a gzipped XML file distributed under a GNU license at:

http://www.julesberman.info/neoclxml.gz

- Jules Berman
Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.

Sunday, February 10, 2008

Correction to Ruby Programming for Medicine and Biology

Sorting the lines in large files is a frequent task for informaticians (e.g., sorting the lines from a long list of terms, with a different term on each line of the file).

For very large files, the built-in sort function of programming languages just cannot do the job because the lines are put into an array (held in memory), and even computers with lots of memory tend to choke.

An easy short-cut involves only sorting the first few characters of each line (10 characters in the script provided below), instead of the entire line. In this way, the array of lines from the file can be shortened to ten characters per line, and this saves lots of memory.

I provided a short Ruby script (bigsort.pl) in my book, Ruby Programming for Medicine and Biology. The bigsort.pl script on page 150 of Ruby Programming for Medicine and Biology, has a few quirks. First, it assumes that the text file (to be sorted) is a DOS-style file with a two character (carriage-return,line-feed) linebreak. Also, it assumes that every line (in the file to be sorted) contains alphanumeric text.

Provided here is a minor modification to the bigsort.pl Ruby script. It should work for any type of text file and does not require text to appear on each line of the file that is being sorted. As with all my posted scripts, the method is provided by its creator, Jules J. Berman, "as is", without warranty of any kind, expressed or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. in no event shall the author or copyright holder be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.

Thanks goes to Dr. Tim Rand, who spotted the error and sent me his own version of a fix on February 6, 2008.

#!/usr/local/bin/ruby
text = File.open("terms.txt", "r")
out = File.open("terms.put", "w")
linearray = Array.new
begin_position = 0
text.each_line do
|line|
old_position = begin_position
begin_position = text.pos
line = line.chomp! + " " #pad ten spaces
linearray << line.slice(0..9) + old_position.to_s
end
linearray.sort!
linearray.each do
|value|
seekplace = value.slice(10..20).to_i
text.seek(seekplace, IO::SEEK_SET)
out.puts(text.readline)
end
exit

-Jules Berman
Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.

Tuesday, November 6, 2007

Ruby climbs up a notch on TIOBE index

On my September 14 blog, I wrote that Ruby had risen to a rank of 10 on the TIOBE index of programming languages.

On the November, 2007 TIOBE index, Ruby climbed another notch to number 9.

According to their web site, the TIOBE index ratings "are based on the world-wide availability of skilled engineers, courses and third party vendors."

This rating system seems to overlook one of the strongest features of Ruby: its appeal to non-programmers. Ruby is a language that unskilled engineers can use productively. One of the themes of my Specified Life blog site is that biomedical research requires a little bit of programming (usually less than a dozen lines of Ruby code) to perform common computational tasks related to data organization, data sharing and data analysis. Ruby empowers non-programmers (people who do not identify themselves as programmers) to perform the common computational tasks in their fields.

Still, it is re-assuring to know that Ruby is moving up as a language used by professional programmers.

- Jules Berman


Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.


Wednesday, October 24, 2007

Merging and splitting pdf images while preserving image annotations

A nice feature of pdf files is the ability to merge files or even parts of files. In the past week, we have discussed the free command-line utility, pdftk. The pdftk utility manages pdf files and is available at:

http://www.accesspdf.com/pdftk

The pdftk utility permits you to easily merge collections of pdf files. If you have converted your images to pdf files (something easily done with Ruby and discussed in several recent blog posts), you can make a large pdf file with each page of the file corresponding to a different image. If you are a pathologist who wants to send a set of images for consultation to another pathologist, you can combine all of the pertinent images into a single pdf file and send it to a colleague.

The message stressed in almost every entry of this Specified Life blog is that data has no value unless it is fully described. Furthermore, the description of the data must be bound to the data object. There are lots of ways of achieving this goal. In the case of pdf images, descriptive data can be added to the image header or descriptive data can be added to the image as an attachment file.

What happens to the attachment files for pdf images when you combine images into a merged document? Do you lose your attachments?

No. The descriptive attachments are preserved and can be reclaimed from the merged file. There are actually several different ways of reclaiming attached files from a merged pdf document. In this blog, we'll describe just one method, using pdftk.

First, we'll prepare two pdf image files for which textual attachments have been added (technique discussed in a prior blog). We'll put these into the c:\pdftk subdirectory, where we keep our pdftk exe files.

10/23/2007 08:00 PM 30,101 out_att.pdf
10/24/2007 07:07 AM 125,845 submu_at.pdf

We'll combine all of our pdf image files in the subdirectory using pdftk's cat command.

C:\pdftk>pdftk *.pdf cat output combined.pdf

This produces a multipage file, combined.pdf, with each image occupying a page of the file.

Next, we'll split the file, combined.pdf into pages, with each page representing a new pdf file containing a single image (using pdftk's burst command).

C:\pdftk>pdftk combined.pdf burst

Now, when we look at all of the .pdf files in our subdirectory, we see the two files that we started with (out_att.pdf and submu_at.pdf) plus the file that merges the two image files, combined.pdf, plus the two files that represent the split pieces of the file combined.pdf, produced by the burst command (pg_0001.pdf and pg_0002.pdf).


C:\pdftk>dir *.pdf
Volume in drive C has no label.
Volume Serial Number is 504C-8FB6

Directory of C:\pdftk

10/24/2007 07:09 AM 155,685 combined.pdf
10/23/2007 08:00 PM 30,101 out_att.pdf
10/24/2007 07:11 AM 30,251 pg_0001.pdf
10/24/2007 07:11 AM 125,990 pg_0002.pdf
10/24/2007 07:07 AM 125,845 submu_at.pdf
5 File(s) 467,872 bytes
0 Dir(s) 30,727,413,760 bytes free


Can we reclaim the attachments for these pdf figures? Yes.

We can retrieve the attachment file by using pdftk's unpack_files command on any of the burst files.

Here, we extract the attachment to pg_0002.pdf

C:\pdftk>pdftk pg_0002.pdf unpack_files output

The new files produced by unpacking the attachment is submu_at.txt, the textual attachement originally added to the file submu_at.pdf.


C:\pdftk>dir *.txt
Volume in drive C has no label.
Volume Serial Number is 504C-8FB6

Directory of C:\pdftk
10/24/2007 07:18 AM 190 SUBMU_AT.TXT


We can read the contents of submu_at.txt with the DOS type command.


C:\pdftk>type submu_at.txt
This is the descriptive text that I have attached
to an image of submucosa from Gray's Anatomy, and
copied from the Wikipedia Commons at:
http://en.wikipedia.org/wiki/Image:Gray1033.png


This seems like a lot of work, and it is. Now that we know the individual steps for creating pdf image attachment files, merging pdf images, reclaiming the attachments, and displaying the image and its description, we can write scripts (in Perl, Python, or Ruby) that automate all of these steps (by making system calls to pdftk) and that scale up to more ambitious efforts.

Jules J. Berman

My book, Principles of Big Data: Preparing, Sharing, and Analyzing Complex Information was published last year by Morgan Kaufmann.



There are three crucial topics related to data preparation that are omitted from virtually every other Big Data book: identifiers, immutability, and introspection.

I urge you to read more about my book. Google books has prepared a generous preview of the book contents. If you like the book, please request your librarian to purchase a copy of this book for your library or reading room.

tags: big data, metadata, data preparation, data analytics, data repurposing, datamining, data mining

Monday, October 22, 2007

Adding and extracting comments to a Tiff image, with Ruby

This blog is part of a series describing methods to annotate images. The purposes of image annotation is to convey important (and often necessary) textual information inside the header of your image.

The basic utilities for image display/manipulation in Ruby are posted.

For this blog, we will use the .tif version of a public domain image of submucosa selected from Gray's Anatomy and downloaded from the Wikipedia Commons.



The Ruby script tifadd.rb adds a simple comment, "Hello world" to the
tif file submu_bw.tif.


#!/usr/local/bin/ruby
require 'RMagick'
include Magick
tissue = ImageList.new("submu_bw.tif")
tissue.cur_image[:Comment] = "Hello world"
tissue_copy = ImageList.new
tissue_copy = tissue.cur_image.copy
tissue_copy.write("submu_2.tif")
exit


The Ruby script is invoked from the command line.


c:\>ruby tifadd.rb


That's all there is to it. The comment can be extracted from the new .tif file, submu_2.tif, with the Ruby script tifout.rb.


#!/usr/local/bin/ruby
require 'RMagick'
include Magick
tissue = ImageList.new("submu_2.tif")
print tissue.properties['Comment']
exit


Here is the output.


c:\ftp>ruby tifout.rb
Hello world


It's very simple, but this technique allows you to start annotating your .tif files with text.

- Jules Berman


Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.


Sunday, October 21, 2007

Annotating a PDF image

I have been writing a series of posts on image annotation. Basically, images should convey textual information that describes the image and that describes the image file (the title of the image, who made the image, who can use the image file, etc.).

Prior posts explained how to do this with jpg and png images. If you transfrom a png image into a jpg image, text in the comment block in the png image header is preserved in the comment block of the jpg image header. However, if you transform a png image into a pdf image, the comment block is lost.

In this post, I'll show how to fetch the textual descriptors from a pdf file, and how to add your own textual descriptors to the pdf file. The methodology is fully described in Sid Steward's excellent book, "PDF Hacks: 100 industrial-strength tips & Tools."

First, just about any image in any popular format, can be converted into a PDF document. Here's a Ruby script that takes the png image, neo1.png, and converts it to the pdf file, out.pdf. More information about Ruby and RMagick are available.


#!/usr/local/bin/ruby
require 'RMagick'
include Magick
walnut = ImageList.new("neo1.png")
walnut_copy = ImageList.new
walnut_copy = walnut.cur_image.copy
walnut_copy.write("out.pdf")
exit


Now, if you want to see the text header in the pdf file, get pdftk (free).

http://www.accesspdf.com/pdftk/

If you have Windows, you can download the binary exe. For example:

pdftk-1.12.exe.zip (1,470,142 bytes)

Unzip the file and put the output into c:\pdftk

It will look something like:


C:\pdftk>dir
..
11/08/2004 03:11 PM 39,049 pdftk.1.html
11/08/2004 03:11 PM 17,878 pdftk.1.txt
11/08/2004 03:34 PM 1,489,920 pdftk.exe


Put your pdf image file in the c:\pdftk directory

Create an output file, outd.txt from your out.pdf image, with the following command line:


C:\pdftk>pdftk out.pdf dump_data output outd.txt

Then look at the outd.txt file:

C:\pdftk>type outd.txt
InfoKey: Title
InfoValue: out.pdf
InfoKey: Producer
InfoValue: ImageMagick 6.2.9 08/11/06 Q8
http://www.imagemagick.org
InfoKey: ModDate
InfoValue: D:20071021080307
InfoKey: CreationDate
InfoValue: D:20071021080307
NumberOfPages: 1


Every pdf file has important textual descriptors, including the Creation date.

Now, let's go into a text editor and add values to the outd.txt file. We add four lines (bottom) that describe the copyright and the usage for the image.


InfoKey: Title
InfoValue: out.pdf
InfoKey: Producer
InfoValue: ImageMagick 6.2.9 08/11/06 Q8
http://www.imagemagick.org
InfoKey: ModDate
InfoValue: D:20071021080307
InfoKey: CreationDate
InfoValue: D:20071021080307
InfoKey: Copyright
InfoValue: Copyright (C) 2007 Jules J. Berman
InfoKey: Usage
InfoValue: GNU Free Documentation License
NumberOfPages: 1


Now, let's upload this revised descriptor file into the pdf image.


C:\pdftk>pdftk out.pdf update_info outd.txt output outd.pdf


We now have a new pdf file, outd.pdf, with the revised descriptor list included in the pdf file header. Let's check. Write a dump_data command line to extract the text descriptors of the outd.pdf file.


C:\pdftk>pdftk outd.pdf dump_data output outd2.txt


Then print out the outd2.txt file containing the text descriptors for outd.pdf


C:\pdftk>type outd2.txt
InfoKey: Title
InfoValue: out.pdf
InfoKey: Producer
InfoValue: ImageMagick 6.2.9 08/11/06 Q8
http://www.imagemagick.org
InfoKey: Copyright
InfoValue: Copyright (C) 2007 Jules J. Berman
InfoKey: ModDate
InfoValue: D:20071021080307
InfoKey: Usage
InfoValue: GNU Free Documentation License
InfoKey: CreationDate
InfoValue: D:20071021080307
NumberOfPages: 1


Notice that the InfoKey/InfoValue pairs are rearranged, but the information that we added (copyright statement and usage statement) are included.

So, how do you preserve header information when you transform a png or a jpg file to a pdf file? I'm sure you can figure this out for yourself, but just for completeness sake, I hope to write some future blogs that provide techniques and examples.

- Jules Berman


Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.


Saturday, October 20, 2007

More Ruby image header and image format tricks

This blog is just an elaboration on an earlier blog. Again, it uses RMagick and ImageMagick. Details for using these within Ruby have been posted.

Here's a script, pdfadd.rb, that takes a png image file and creates a jpg image file with a text comment.



#!/usr/local/bin/ruby
require 'RMagick'
include Magick
walnut = ImageList.new("neo1.png")
walnut.cur_image[:Comment] =
" Developmental Lineage
Classification
of Neoplasms
Copyright (C) 2007
by Jules J. Berman
and distributed under
the GNU Free
Documentation License"
walnut_copy = ImageList.new
walnut_copy = walnut.cur_image.copy
walnut_copy.write("out.jpg")
exit



Once the comment has been put into the jpg file, we can extract it with another Ruby script, pdf2.rb.



#!/usr/local/bin/ruby
require 'RMagick'
include Magick
walnut = ImageList.new("out.jpg")
print walnut.properties['Comment']
exit



The output looks like this:



c:\ftp>ruby pdf2.rb
Developmental Lineage
Classification
of Neoplasms
Copyright (C) 2007
by Jules J. Berman
and distributed under
the GNU Free
Documentation License



We can also directly transform one image type into another. Here, we will transform a png image into a pdf image.



#!/usr/local/bin/ruby
require 'RMagick'
include Magick
walnut = ImageList.new("neo1.png")
walnut_copy = ImageList.new
walnut_copy = walnut.cur_image.copy
walnut_copy.write("out.pdf")
exit



As a caveat, when you transform an image between different formats, your comment text may be lost if the receiving format doesn't recognize the attribute object. So you can transfer Comment text from png to jpg, but you can't directly transfer the comment over to pdf.

- Jules Berman
Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.

Tuesday, October 9, 2007

Ruby scripts from Ruby Programming for Medicine and Biology

For those interested, here is a list of Ruby scripts that are included and described in Ruby programming for Medicine and Biology, my book that was published last month (September, 2007).

SCRIPTS IN RUBY PROGRAMMING FOR BIOLOGY AND MEDICINE

1.3.1. Getinput.rb retrieves a line of keyboarded text.

1.4.1. Grow.rb simulates six generations of bacterial growth.

1.4.3. Grow2.rb uses explicit Ruby objects and statements.

1.5.1. Lowclass.rb provides syntax for user-created classes.

1.5.3. Noclass.rb requires an external Person class definition.

1.5.4. Person_class_file.rb, a class library for script no_class.rb.

2.7.1. Combo.rb parses an array into all possible ordered subarrays.

2.8.1. Hash.rb creates and displays key/value pairs for a Hash instance object.

2.8.4. Neohash.rb creates three hash instances for the Neoplasm Classification.

2.10.1. Glob.rb demonstrated the Dir class glob method.

2.10.3. Dirlist.rb lists the files in the current directory.

2.12.1. Time.rb measures the length of time for any process.

3.4.2. Mod1.rb defines and includes a simple module.

3.4.3. Mod2.rb calls a module with the scope operator.

3.4.4. Mod3.rb embeds a module within a class.

6.2.1. Readsome.rb reads the first 20 lines of the MRCONSO file.

6.3.2. Zipf.rb prints the number of occurrences of words in a string.

6.3.4. Zipf2.rb creates a Zipf distribution of the words in OMIM.

6.4.1. Snom_get.rb extracts SNOMED-CT terms from UMLS.

6.5.1. Disease.rb collects SNOMED-CT diseases from UMLS.

6.6.1. Neosdbm.rb creates three persistent database objects.

6.7.1. Sdbmget.rb retrieves data from persistent object.

7.3.1. Sentence.rb, a simple sentence parser.

7.6.1. Search.rb searches through any file for lines matching a Regex expression.

7.7.1. Pubemail.rb extracts e-mail addresses from a PubMed search.

8.3.1. Base64.rb encodes strings in Base64 notation.

8.4.1. Dircopy.rb copies files from one directory to another.

8.5.1. Dcm2jpg.rb converts a DICOM file into a jpeg file.

8.5.3. Dcmsplit.rb converts a DICOM file into a jpeg and a text file.

8.6.1. Jpeg_add.rb inserts textual information into a jpeg image.

9.2.1. Concord.rb creates a concordance.

9.3.1. Indexer.rb creates an index.

10.2.1. Haystack.rb performs a binary search on a file.

10.3.2. Tinysort.rb sorts the lines of a file.

10.3.4. Bigsort.rb sorts large files quickly.

10.4.1. Anatomy.rb extracts SQL data from the Functional Model of Anatomy.

10.5.2. Alldata.rb sums the census districts to yield the total U.S. population.

11.2.1. Scrubit.rb scrubs and deidentifies any input line.

12.2.2. Autocode.rb provides nomenclature terms and codes for an input sentence.

12.3.1. Fastcode.rb improves performance compared with aucode.rb.

12.4.3. Icd.rb collects ICD10AM codes from the UMLS Metathesaurus.

12.5.1. Seer.rb determines the occurrences in the U.S. of tumor types found in the SEER public-use data files.

13.5.1. Fibo.rb computes the first twenty elements of the Fibonacci series.

13.6.1. Mean.rb computes the mean from an array of numbers.

13.7.1. Std_dev.rb computes the standard deviation for an array of numbers.

13.8.1. Randtest.rb simulates 600,000 casts of the die.

13.10.1. Error.rb uses resampling to simulate runs of errors.

14.6.2. Thresh.rb divides a text file into two threshold files.

14.6.5. Threshrv.rb computes original file from two threshold files.

15.2.2. Neopull.rb searches a server file for a web client query.

15.3.1. Neosafe.rb improves the security of neopull.rb.

17.3.1. Biohack.rb, converts a gene sequence into a protein sequence.

18.14.2. Rdf3.rb extracts triples from an RDF document.

18.19.2. Jpg2b64 inserts a Base64 jpeg image into an RDF file.

19.2.2. Ancestor.rb determines the ancestor lineage for organisms.

19.2.4. Class_lineage.rb determines ancestral lineage.

19.3.1. Neoself.rb provides tag hierarchy for XML file.

20.5.1. Conflict.rb overrides a class assignment.

-Jules Berman tags: bioinformatics, biomedical informatics, medical informatics, Ruby, ruby language, Ruby programming, scripts

Science is not a collection of facts. Science is what facts teach us; what we can learn about our universe, and ourselves, by deductive thinking. From observations of the night sky, made without the aid of telescopes, we can deduce that the universe is expanding, that the universe is not infinitely old, and why black holes exist. Without resorting to experimentation or mathematical analysis, we can deduce that gravity is a curvature in space-time, that the particles that compose light have no mass, that there is a theoretical limit to the number of different elements in the universe, and that the earth is billions of years old. Likewise, simple observations on animals tell us much about the migration of continents, the evolutionary relationships among classes of animals, why the nuclei of cells contain our genetic material, why certain animals are long-lived, why the gestation period of humans is 9 months, and why some diseases are rare and other diseases are common. In “Armchair Science”, the reader is confronted with 129 scientific mysteries, in cosmology, particle physics, chemistry, biology, and medicine. Beginning with simple observations, step-by-step analyses guide the reader toward solutions that are sometimes startling, and always entertaining. “Armchair Science” is written for general readers who are curious about science, and who want to sharpen their deductive skills.


Friday, September 14, 2007

Ruby moves up on TIOBE Programming Index

Yesterday marked the publication date for my new book, Ruby Programming for Medicine and Biology!




As a reality check, I checked Ruby's ranking on the TIOBE Programming Language Index for September 2007.

Ruby is now ranked 10th (up from rank 13 last year at this time).

Perl is now ranked 6th (same rank as this time last year).

Python is now ranked 8th (down from rank 7 this time last year).

Remarkably, Lua, a programming language that I had never heard of, is ranked 18th (up from rank 50 this time last year!!!).

More on Lua on my next blog.

- Jules