#! /usr/bin/env python

from __future__ import division
from pylab import *
import sys
import Numeric


#
#   plot_image.py
#
#   Step 1: make this file executable
#
#           chmod +x plot_image.py
#
#   Step 2: pipe data in python script
#
#           ./gen_data | ./plot_image -s nx ny -c nc -t 'image title'
#
#   with optional arguments
#          -s nx ,ny    image size [16x16]
#          -c nc        number of contour levels [none]
#          -t ' '       image title ['some like it hot']
#
#   additional:  -g  gray map  [jet map]
#                -h  hot map
#
#   ref: matplotlib web site
#                                             Michel Vallieres, 2007
#

                        # dummy function to initialize Z
def func3(x,y):
    return 0.005*x*y

                        # defaults
mycontours = 0
nx = 16
ny = 16
mytitle = 'Some like it hot'
mymap = cm.jet

                        # parse command line arguments
n = len( sys.argv )
i = 1
while i < n:
    if sys.argv[i].find("s") == 1:
        nx = int( sys.argv[i+1] )
        ny = int( sys.argv[i+2] )
        i = i + 2
    elif sys.argv[i].find("c") == 1:
        mycontours = int( sys.argv[i+1] )
        i = i + 1
    elif sys.argv[i].find("t") == 1:
        mytitle = sys.argv[i+1]
        i = i + 1
    elif sys.argv[i].find("g") == 1:
        mymap = cm.gray
    elif sys.argv[i].find("h") == 1:
        mymap = cm.hot
    else:
        print " Syntax:    script -s nx ny -c "
    i = i + 1

                       # identification
print "Plot_image"
print "Title:            ", mytitle
print "Image size:       ", nx, ny
print "# countour lines: ", mycontours


                       # set grid
x = range( nx )
y = range( ny )

X,Y = meshgrid( x, y )

Z = func3( X, Y )

                       # read in data
for j in y:
   for i in x:
      Z[j,i] = input()

                       # min & max
min_data = Z[0,0]
max_data = Z[0,0]
for i in x:
   for j in y:
      if Z[j,i] < min_data:
          min_data = Z[j,i]
      if Z[j,i] > max_data:
          max_data = Z[j,i]

print "Data range:       ", min_data, max_data


                       # colored image
im = imshow( Z, interpolation='bilinear', origin='lower',
            cmap=mymap, extent=(1,nx-1.0,1,ny-1.0) )

                       # contour lines
if mycontours > 0:
    dcont = ( max_data - min_data ) / ( mycontours - 1 )
    cset = contour( Z, arange(min_data,max_data,dcont),
               origin='lower',
               linewidths=2,
               extent=(0,nx-1,0,ny-1)
               )

    clabel( cset, inline=1, fmt='%1.1f', fontsize=10 )


                       # render picture
axis('off')

colorbar()
title( mytitle )
show()

