LehreWiki

   1 #!/usr/bin/env python 
   2 #               use "env" command to make sure you use the right python interpreter
   3 # -*- coding: utf-8 -*-
   4 #               allows usage of non-ASCII characters in scripts
   5 
   6 
   7 # Add general information below
   8 
   9 '''
  10 FILENAME:
  11     ncreader.py
  12 
  13 DESCRIPTION:
  14     Introduction to various python objects
  15     Python Seminar 13.09.2012
  16 
  17 Sample ncfile "../Nio/sresa1b_ncar_ccsm3_0_run1_200001.nc
  18 
  19 '''
  20 
  21 # for python objects naming conventions and style see PEP8:
  22 #  http://www.python.org/dev/peps/pep-0008/
  23 
  24 # If you use this file as a importable module for other programs than
  25 # the information below is useful to describe 
  26 __author__ = "A. U. Thor"
  27 __version__ = "0.0"
  28 __date__ = "0000/00/00"
  29 
  30 
  31 import sys
  32 import os
  33 from optparse import OptionParser
  34 import Nio
  35 import numpy as np
  36 import matplotlib.pyplot as plt
  37 import pdb
  38 import cPickle as cP
  39 
  40 
  41 
  42 # below is a simple class that provides some convenience functions
  43 class NcReader:
  44         
  45         ''' As an example, this particular Class is basically 
  46                 a set of convenience functions that are meant 
  47                 to speed up some of your routine work with NetCDF files '''
  48         
  49         def __init__(self, file_path):
  50                 ''' Initialize object '''
  51                 self.fpath  = file_path
  52                 self.ncfile = Nio.open_file(self.fpath)
  53                 self.variables = self.ncfile.variables
  54         
  55         def printVars(self):
  56                 ''' prints variables dictionary ''' 
  57                 for i in self.variables: 
  58                         print i
  59         
  60         def plotVar(self, var_name):
  61                 ''' plots single 1d variable '''
  62                 variable = self.ncfile.variables[var_name][:]
  63                 plt.plot(variable)
  64                 plt.show()
  65                 
  66         def plot2dVar(self, *args, **kwargs):
  67                 '''plots multiple 2d variables '''
  68                 
  69                 # args is a tuple
  70                 # kwargs is a keyworded dictionary
  71                 
  72                 for i in args:
  73                         try:
  74                                 var = self.variables[i]
  75                                 print var[:].shape
  76                                 plt.imshow(self.variables[i][0,:])
  77                         except:
  78                                 raise #KeyError("variable %s not found" %i)
  79                         
  80                         if kwargs['colorbar'] == True:
  81                                 plt.colorbar()  
  82                         plt.show()
  83                         
  84 
  85 # "parse_options" is meant to parse command line arguments and options
  86 # there can be unknown number of arguments, but options are predefined
  87 # mandatory arguments are actually options
  88 
  89 def parse_options():
  90     
  91     ''' Parse command line options and arguments '''
  92 
  93     usage = "usage: %prog [options] <input_files>";
  94     version = "%prog 0.1"
  95     parser = OptionParser(usage)
  96     
  97     parser.add_option("-d", "--pdb_switch", dest = 'pdb_switch',
  98                        action = "store_true", default = "False")
  99     parser.add_option("-i", "--input_file", dest = 'input_file')
 100                                                 
 101     (options, args) = parser.parse_args()
 102     
 103     return (options, args)
 104 
 105 
 106 # It is a good practice to separate code execution and objects like classes
 107 # and functions
 108 # Main function is used for executing python code as a standalone program
 109 #  
 110 def main():
 111 
 112     options, arguments = parse_options()
 113 
 114     input_file = options.input_file
 115     
 116     variables = arguments[:]
 117     
 118     a = NcReader(input_file)
 119     a.printVars()
 120     
 121     # keyworded arguments - normally used as options for fuctions
 122     # non keyworded arguments - just arguments
 123     a.plotVar('plev')
 124     a.plot2dVar(*variables, colorbar = True)
 125     
 126     # debugger?
 127     pdb_switch = options.pdb_switch
 128 
 129 
 130 # The following structure is useful if 
 131 # the code to be run as a standalone program AND a module which 
 132 # can be imported in other python scripts
 133 if __name__ == "__main__":
 134     main()

LehreWiki: PythonCourse/PythonLES/SeminarLog5 (last edited 2012-09-13 00:22:20 by MikhailItkin)