##----------------------------------------------------------------------------
## Name:     RotaryBldgResonance.py
##             
## Purpose:  Compute resonant coupling of the lab at specific drive frequencies
##           
##                 
##           Depends on Python SciPy and NumPy
##             
## Author:       J Park
##
## Created:      5/3/08
##
## Modified:     
##----------------------------------------------------------------------------

import sys, getopt, time, glob

Version = sys.argv[0]+" : "+str( time.asctime( ( time.gmtime(time.time()) ) ) )
DEBUG = False

try:
    from numpy import *  # www.numpy.org numpy.scipy.org
except ImportError: 
    print "Failed to import numpy."
    
try:
    import pylab as mp  # matplotlib.sourceforge.net
except ImportError: 
    print "Failed to import pylab."
    
# Global variables
# Default Parameters
f_x = 9.4  # Hz
f_y = 18.7 # Hz
f1  = 2
f2  = 30
df  = 0.5

PlotAll       = False        # -p
WriteOutput   = False        # -o

##----------------------------------------------------------------------------
## Main module
def main():

    print Version
    
    ParseCmdLine()

    f = arange( f1,f2,df )
    wx = (f/f_x - f_x/f)
    ax = 1/sqrt( pow(wx , 2) )
    wy = (f/f_y - f_y/f)
    ay = 1/sqrt( pow(wy , 2) )

    if DEBUG:
        print ax
        print ay

    r1 = 1./sqrt( pow(12/f_x - f_x/12, 2) )
    r2 = 1./sqrt( pow(12/f_y - f_y/12, 2) )
    r3 = 1./sqrt( pow(16/f_x - f_x/16, 2) )
    r4 = 1./sqrt( pow(16/f_y - f_y/16, 2) )

    print 'f=12Hz,fx=9.4Hz:',r1,'f=12Hz,fy=18.7Hz:',r2
    print 'f=16Hz,fx=9.4Hz:',r3,'f=16Hz,fy=18.7Hz:',r4

    # Setup Plots
    # ----------------------------------------------------------------------
    #mp.figure(1)
    mp.subplot(2,1,1)
    mp.title ( "" )
    mp.ylabel( "" )
    mp.xlabel( "Frequency (Hz)" )
    #legendFont = FontProperties(size='small')
    mp.plot( f, ax )
    mp.subplot(2,1,2)
    mp.plot( f, ay )

    #mp.legend( loc='lower left', prop=legendFont )

    # Show the Plot
    # ----------------------------------------------------------------------
    mp.show()

    print "Normal Exit"
## Main module
##----------------------------------------------------------------------------

    
##----------------------------------------------------------------------------
def usage():
    print "Usage: ", sys.argv[0]
    print "\t -h (help)"
    print "\t -d (debug)"
    print "\t -p (PlotAll)"
    print "\t -o writeOutput"

##----------------------------------------------------------------------------
def ParseCmdLine():
    ##
    global PlotAll
    global WriteOutput
    global DEBUG

    try:
	## Parse the command line arguments in sys.argv via getopt()
	opts, args = getopt.getopt(sys.argv[1:], "hdpo")

    except getopt.GetoptError, error:
	print "ParseCmdLine(): GetoptError: ",error
	return

    if len(opts) == 0:
        usage()
        return

    argCount = 0
    for optElement in opts:
        argCount = argCount + 1
        if optElement[0] == "-h":
            usage()
            sys.exit(1)
        if optElement[0] == "-d":
            DEBUG = True
        if DEBUG:
            print "opts element %d:" % (argCount), optElement
        if optElement[0] == "-o":
            WriteOutput = True
        if optElement[0] == "-p":
            PlotAll = True

    if DEBUG:
        print "-p", PlotAll
        print "-o", WriteOutput

    return

##----------------------------------------------------------------------------
def OpenFile(file, mode):
    try:
        # open() will raise an IOError exception if it fails
        print "Opening file:", file
        fd = open(file,mode)

    except IOError, error:
        print "OpenFile(): I/O error:", error
        sys.exit("OpenFile()")

    except OSError, error:
        print "OpenFile(): OS error:", error
        sys.exit("OpenFile()")
        
    except:
        print "OpenFile(): Unexpected error:", sys.exc_info()[0]
        raise
        sys.exit("OpenFile()")

    else: # executed after the try if no exceptions
        return fd
    
##----------------------------------------------------------------------------
## Provide for cmd line invocation
if __name__ == "__main__":
    main()