Friday, March 14, 2014

A new Forth interpreter written in C


/
/*
File      forth-and-c.c
Author    Ernesto P. Adorio
          ernesto.adorio@gmail.com
Desc
This simple forth interpreter reads from the command line based on the following
prescription.

loop:
  read
  eval
  print

This version uses double floating point numbers for ease in applications.
Version   0.0.1 march 12, 2014
Compile   gcc -std=gnu99 forth-and-c.c  
*/

#include 
#include 
#include 
#include 



/* Constants */
char* ByeMessage = "Thanks for trying out forth-and-c.\n";
char* WelcomeMessage="Welcome to Forth-and-C Version 0.0.1, March 12, 2014.\n";
    
/* Global interpreter variables. */



#define BUFFMAXLEN 1024 
#define EOI '\0'
 char BUFF[BUFFMAXLEN];
 char * tokenstart, *tokenend = BUFF;
 
 #define MAXSTACKDEPTH 10
 union {
   double f;
   long int i;
 }OPSTACK[MAXSTACKDEPTH];
 int opindex = -1;


char PROMPT[32]= ">> ";

/* token system */
double fnum;  /* number read */
enum tokentype  { FPLUS, FMINUS, FDIV, FMUL, DOT,   BYE,  EMIT,   CR, EOL, FNUM, UNDEFINED};
char* symbols[] ={  "+",  "-",    "/",  "*",  ".",  "bye","emit", "cr" };
int NSYMBOLS=8;

char* errmssgs[] = {"NOERROR", "OVERFLOW", "UNDERFLOW"};
enum errorcodes {NOERROR, OVERFLOW, UNDERFLOW};
int error = NOERROR;


int lex(void)
{  
   /* process token pointed to by token start */
   if (*tokenstart==EOI) {
     return EOL;
   }
   for (int i = 0; i < NSYMBOLS; i++){
      if (strcmp(tokenstart, symbols[i]) == 0){
         return i;
      }   
   }
   
   /* Pure Forth assumes a number only after trying other token types */
   fnum = strtod(tokenstart,NULL);
   return FNUM;
   
   /* Error at this stage! */
   return UNDEFINED;
}p
  
  
int parse(void)
/* Parsing system, splits input line into tokens */
{
   tokenstart = tokenend;
   /* Find location of next space character. */ 
   while (! isspace(*tokenend) &&  *tokenend !=EOI)tokenend++;
   if (*tokenend != EOI){
      *tokenend++='\0';
      return 1;
   } else {
     /* reset tokenend */
     return EOL;
   } 
}


int execute(int toktype)
{
  switch(toktype) {
    case FNUM:if (opindex < MAXSTACKDEPTH) {
                 OPSTACK[++opindex].f = fnum;
              } 
       break;
    case DOT: if (opindex >= 0){
                 printf("%f ", OPSTACK[opindex--].f);
       } else {
  error= UNDERFLOW;
       }; 
       break;
    case FPLUS:  
              OPSTACK[--opindex].f += OPSTACK[opindex + 1].f;
              break;
    case FMINUS:
              OPSTACK[--opindex].f -= OPSTACK[opindex + 1].f;
              break;
    case FMUL:
              OPSTACK[--opindex].f *= OPSTACK[opindex + 1].f;
              break;
    case FDIV:
              OPSTACK[--opindex].f /= OPSTACK[opindex + 1].f;                    
              break;
    case EMIT:putchar( (int) (OPSTACK[opindex--].f));
       break;
    case CR:  /* carriage return */
              putchar(10); putchar(13);
              break;
    default:  break;                  
  };    
};


int main()
{
   int ntokens = 0;
   /* print welcome.*/
   printf("%s", WelcomeMessage);
   
   while (1) {
      /* read input */
      printf("%s", PROMPT);
      fgets(BUFF, BUFFMAXLEN, stdin);
      
      /*reset tokenizer */
      tokenend=BUFF;              
      while (parse()!= EOL) {
 ntokens ++;
 int tokentype = lex();
 // printf("%d: %s %d\n",ntokens, tokenstart, tokentype);
 execute(tokentype);
 
 if (tokentype == BYE) {
   printf("%s", ByeMessage);
  
   return (0);
 }  
 if (error) {
   printf("%s", errmssgs[error]);
   switch(error){
     case UNDERFLOW:opindex= -1; break ;
     case OVERFLOW: opindex= MAXSTACKDEPTH - 1; break;
     default: break;
   }  
   error = 0;
 }
      }
   }
}


We have decided to rewrite our Forth interpreter written in C. Default data type are double floating point numbers and this allows you to use it for processing simple arithmetic problems.

Compile the above using the command line invocation

gcc -std=gnu99 forth-and-c.c
Then run the program by typing ./a.out Type the expression 4 3 * 1 - . You should get the answer 11.


Tuesday, August 20, 2013

Extracting and displaying the Astronomy Photo of the Day in a server.


I am having problems presenting this article. Please be patient.

The most astounding photos in astronomy are posted daily in the NASA site
http://apod.nasa.gov The url of the photo
however do not have the same value everyday, say "apod.jpg", instead the
filename is like "http://apod.nasa.gov/apod/image/1308/sunvenusuv3_dove_960.jpg".
This filename is embedded in the redirected url
"http://apod.nasa.gov/apod/astropix.html".


The image filename is enclosed in an IMG tag.Our hope is that all other html
containing the image file has similar html template.
So we read in this file, extract the filename and build up the image url.
We then use the Linux utility wget to download the image file, then move it
to a fixed destination in our server with a fixed filename apod.jpg.
This way we only "disturb" the NASA site once each day instead of linking
each time a browser visits our weather page which hosts the image.

This is our first version. Python has changed much with new recommended
libraries and we will update the following code to make it more readable and
"Pythonic". We are open to experiment with the regular expression library,
and use the Requests module.


#!/usr/bin/env python

import urllib
import os

 
src = "http://apod.nasa.gov/apod/astropix.html"
strstart="<img SRC=\""
l = len(strstart)

contents = urllib.urlopen(src).read()
startpos = contents.find(strstart)
print "parsing and determining graphics file name"
if startpos:
   endpos = startpos + contents[startpos:].find(".jpg\"")+len(".jpg\"")
   imgurl = "http://apod.nasa.gov/apod/"+contents[startpos+l:endpos-1]
   

   print "copying to destination directory"
   os.system("sudo wget -ct 0 %s" % imgurl)  
   srcfile   = imgurl[imgurl.rfind("/")+1:]

   destfile = "/var/www/xxxxx/xxxx/xxx/apod.jpg"

   #print "storing image file to apod.jpg"
   os.system("sudo cp  %s %s" % (srcfile, destfile))
To see how it works out, please click on our weather http://adorio-research.org/wordpress/?page_id=5833 page.

Wednesday, November 14, 2012

Programming in R, computing determinant of matrix.


Assume that the matrix is square with number of rows greater than or equal to 2.
The determinant of the 2 by 2 matrix


$
A = \begin{array}{ll}
a_{11} & a_{12}\\
a_{21} & a_{22} \\
\end{array}
$

is given by A[1,1]* A[2,2] - A[2,1] * A[1,2]. To be continued.....

$\sum_{\forall j} A[1,j] * (-1) ^ {j+1} *det(A[-1,-j]$

where A[-1, -j] denotes the submatrix obtained by deleting the first row and the jth column! R has a clever method of denoting the row or column to be deleted.


here is a simple recursive implementation with debugging statements. We ask the reader to remove them and simplify the code.

"""
# file    mydet.R
# author  your name here!


mydet <- function (A) {
    rows <-nrow(A)
    print (c("rows=", rows))
    if (rows != ncol(A)) {
       print("A is not a square matrix!!!")
    }
    if (rows == 2) {
       result <- (A[1,1] * A[2,2] - A[2,1] * A[1,2])
       print (c("result=", result))
       return(result)
    }

    # expand by first row.
    tot = 0.0
    sign = 1
    for (j in seq(1, rows)){
       tot  = tot + sign * A[1,j] * mydet(A[-1,-j])
       sign = -sign
    }
    return(tot)
}


Sunday, September 23, 2012

Friday, August 24, 2012

Finding all locations of substring in a string.


There are a lot of methods for fining all locations of a substring substr in a string s, and if we ever find ourselves teaching again Python, I would first emphasize the simplest algorithm to do so.

We repeatedly use the basic string object find function. If s is a string and substr is a string pattern (no wild cards!) then s.find(substr) will -1 if substr is not found in s, otherwise it will return the starting index of substr in s.

Here is our function for findind all occurence of substr in a string:


"""
def findall(s, substr):
   """
   Find all locations of substr in s.
   """
   out = []
   oldpos = 0
   n = len(substr)
   while (1):
     pos = s[oldpos:].find(substr)
     if pos >=0:
        out.append(oldpos + pos)
        oldpos += (pos+n+1) #remove +n if you want to find occurences starting within substr also!
     else:
        break
   return out
 

if __name__ == "__main__":
   s   = 'the quick brown fox jumps over the lazy dog near the bank of the river.'
   sub = 'the'
   x=  findall(s, sub)
   print x
   for v in x:
      print s[v:v+len(sub)]

The string find function can actually perform a search using a sprcified starting and ending indices. Thus s[oldpos:].find(substr) may be rewritten as s.find(substr, oldpos). We ask the reader to experiment by modifying the above code.

Help on built-in function find:

find(...)
    S.find(sub [,start [,end]]) -> int
    
    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.


Other methods may be searched in Google. Here are some links to get you started in learning alternative and complicated approaches:

Saturday, July 7, 2012

Two giants of computing who died in the same month!



This image from a facebook posting emphasized the importance of both Steve Jobs and Dennis Ritchie.




Wednesday, February 1, 2012

Python, finding nearest matching color name for RGB values




There are 147 standard color names for use in HTML. here is a simple Python code to find the nearest matching color name given input R,G, B values (from 0-255). The minimization criterion is the sum of absolute vaues of the differences from the color r, g, b values of the colornames.


"""
File    colornames.py
Author  Ernesto P. Adorio, Ph.D
Version 0.0.1 February 1, 2012
"""


# Src: http://www.w3schools.com/html/html_colornames.asp
lines = """AliceBlue  #F0F8FF   Shades Mix
AntiqueWhite  #FAEBD7   Shades Mix
Aqua  #00FFFF   Shades Mix
Aquamarine  #7FFFD4   Shades Mix
Azure  #F0FFFF   Shades Mix
Beige  #F5F5DC   Shades Mix
Bisque  #FFE4C4   Shades Mix
Black  #000000   Shades Mix
BlanchedAlmond  #FFEBCD   Shades Mix
Blue  #0000FF   Shades Mix
BlueViolet  #8A2BE2   Shades Mix
Brown  #A52A2A   Shades Mix
BurlyWood  #DEB887   Shades Mix
CadetBlue  #5F9EA0   Shades Mix
Chartreuse  #7FFF00   Shades Mix
Chocolate  #D2691E   Shades Mix
Coral  #FF7F50   Shades Mix
CornflowerBlue  #6495ED   Shades Mix
Cornsilk  #FFF8DC   Shades Mix
Crimson  #DC143C   Shades Mix
Cyan  #00FFFF   Shades Mix
DarkBlue  #00008B   Shades Mix
DarkCyan  #008B8B   Shades Mix
DarkGoldenRod  #B8860B   Shades Mix
DarkGray  #A9A9A9   Shades Mix
DarkGrey  #A9A9A9   Shades Mix
DarkGreen  #006400   Shades Mix
DarkKhaki  #BDB76B   Shades Mix
DarkMagenta  #8B008B   Shades Mix
DarkOliveGreen  #556B2F   Shades Mix
Darkorange  #FF8C00   Shades Mix
DarkOrchid  #9932CC   Shades Mix
DarkRed  #8B0000   Shades Mix
DarkSalmon  #E9967A   Shades Mix
DarkSeaGreen  #8FBC8F   Shades Mix
DarkSlateBlue  #483D8B   Shades Mix
DarkSlateGray  #2F4F4F   Shades Mix
DarkSlateGrey  #2F4F4F   Shades Mix
DarkTurquoise  #00CED1   Shades Mix
DarkViolet  #9400D3   Shades Mix
DeepPink  #FF1493   Shades Mix
DeepSkyBlue  #00BFFF   Shades Mix
DimGray  #696969   Shades Mix
DimGrey  #696969   Shades Mix
DodgerBlue  #1E90FF   Shades Mix
FireBrick  #B22222   Shades Mix
FloralWhite  #FFFAF0   Shades Mix
ForestGreen  #228B22   Shades Mix
Fuchsia  #FF00FF   Shades Mix
Gainsboro  #DCDCDC   Shades Mix
GhostWhite  #F8F8FF   Shades Mix
Gold  #FFD700   Shades Mix
GoldenRod  #DAA520   Shades Mix
Gray  #808080   Shades Mix
Grey  #808080   Shades Mix
Green  #008000   Shades Mix
GreenYellow  #ADFF2F   Shades Mix
HoneyDew  #F0FFF0   Shades Mix
HotPink  #FF69B4   Shades Mix
IndianRed   #CD5C5C   Shades Mix
Indigo   #4B0082   Shades Mix
Ivory  #FFFFF0   Shades Mix
Khaki  #F0E68C   Shades Mix
Lavender  #E6E6FA   Shades Mix
LavenderBlush  #FFF0F5   Shades Mix
LawnGreen  #7CFC00   Shades Mix
LemonChiffon  #FFFACD   Shades Mix
LightBlue  #ADD8E6   Shades Mix
LightCoral  #F08080   Shades Mix
LightCyan  #E0FFFF   Shades Mix
LightGoldenRodYellow  #FAFAD2   Shades Mix
LightGray  #D3D3D3   Shades Mix
LightGrey  #D3D3D3   Shades Mix
LightGreen  #90EE90   Shades Mix
LightPink  #FFB6C1   Shades Mix
LightSalmon  #FFA07A   Shades Mix
LightSeaGreen  #20B2AA   Shades Mix
LightSkyBlue  #87CEFA   Shades Mix
LightSlateGray  #778899   Shades Mix
LightSlateGrey  #778899   Shades Mix
LightSteelBlue  #B0C4DE   Shades Mix
LightYellow  #FFFFE0   Shades Mix
Lime  #00FF00   Shades Mix
LimeGreen  #32CD32   Shades Mix
Linen  #FAF0E6   Shades Mix
Magenta  #FF00FF   Shades Mix
Maroon  #800000   Shades Mix
MediumAquaMarine  #66CDAA   Shades Mix
MediumBlue  #0000CD   Shades Mix
MediumOrchid  #BA55D3   Shades Mix
MediumPurple  #9370D8   Shades Mix
MediumSeaGreen  #3CB371   Shades Mix
MediumSlateBlue  #7B68EE   Shades Mix
MediumSpringGreen  #00FA9A   Shades Mix
MediumTurquoise  #48D1CC   Shades Mix
MediumVioletRed  #C71585   Shades Mix
MidnightBlue  #191970   Shades Mix
MintCream  #F5FFFA   Shades Mix
MistyRose  #FFE4E1   Shades Mix
Moccasin  #FFE4B5   Shades Mix
NavajoWhite  #FFDEAD   Shades Mix
Navy  #000080   Shades Mix
OldLace  #FDF5E6   Shades Mix
Olive  #808000   Shades Mix
OliveDrab  #6B8E23   Shades Mix
Orange  #FFA500   Shades Mix
OrangeRed  #FF4500   Shades Mix
Orchid  #DA70D6   Shades Mix
PaleGoldenRod  #EEE8AA   Shades Mix
PaleGreen  #98FB98   Shades Mix
PaleTurquoise  #AFEEEE   Shades Mix
PaleVioletRed  #D87093   Shades Mix
PapayaWhip  #FFEFD5   Shades Mix
PeachPuff  #FFDAB9   Shades Mix
Peru  #CD853F   Shades Mix
Pink  #FFC0CB   Shades Mix
Plum  #DDA0DD   Shades Mix
PowderBlue  #B0E0E6   Shades Mix
Purple  #800080   Shades Mix
Red  #FF0000   Shades Mix
RosyBrown  #BC8F8F   Shades Mix
RoyalBlue  #4169E1   Shades Mix
SaddleBrown  #8B4513   Shades Mix
Salmon  #FA8072   Shades Mix
SandyBrown  #F4A460   Shades Mix
SeaGreen  #2E8B57   Shades Mix
SeaShell  #FFF5EE   Shades Mix
Sienna  #A0522D   Shades Mix
Silver  #C0C0C0   Shades Mix
SkyBlue  #87CEEB   Shades Mix
SlateBlue  #6A5ACD   Shades Mix
SlateGray  #708090   Shades Mix
SlateGrey  #708090   Shades Mix
Snow  #FFFAFA   Shades Mix
SpringGreen  #00FF7F   Shades Mix
SteelBlue  #4682B4   Shades Mix
Tan  #D2B48C   Shades Mix
Teal  #008080   Shades Mix
Thistle  #D8BFD8   Shades Mix
Tomato  #FF6347   Shades Mix
Turquoise  #40E0D0   Shades Mix
Violet  #EE82EE   Shades Mix
Wheat  #F5DEB3   Shades Mix
White  #FFFFFF   Shades Mix
WhiteSmoke  #F5F5F5   Shades Mix
Yellow  #FFFF00   Shades Mix
YellowGreen  #9ACD32"""

def rgbfromstr(s):
    # s starts with a #.
    r, g, b = int(s[1:3],16), int(s[3:5], 16),int(s[5:7], 16)
    return r, g, b

def findnearestcolorname(R,G, B, colorD):
    mindiff = None

    for d in colorD:
       r, g, b = rgbfromstr(colorD[d])
       diff = abs(R -r)*256 + abs(G-g)* 256 + abs(B- b)* 256 
       if mindiff is None or diff < mindiff:
          mindiff = diff
          mincolorname = d
    return mincolorname
 

if __name__ == "__main__":
  D={}
  for line in lines.split("\n"):
    tokens = line.split()
    if len(tokens) > 1:
        D[tokens[0]]= tokens[1]
     
  R, G, B = 0, 127, 127
  colorname = findnearestcolorname(0, 127, 127, D)
  print hex(R), hex(G), hex(B)
  print colorname, D[colorname]
 

When the above program runs, it outputs


$ python colornames.py
0x0 0x7f 0x7f
Teal #008080



Questions.

1. Modify the minimizaiton criterion to use least sum of squares of the differences.

2. Provide error checking for input R, G, B values to be within the interval [0, 255].

3. Procide different ways to specify the input RGB values, aside from the (R, G, B) values as done in the program above.