field (version 0.1.1, 12 Jan 2005)
index
field.py

Define object and mathematical functions for model fields.
 
The Field container class is the fundamental building block for all
fields that are part of models supported by package modelutil.  Any 
quantity can be a Field object, whether a parameter, diagnostic var-
iable, prognostic variable, or axis variable.  Collections of Field 
objects describe the state of the model at a particular time.
 
This module defines the Field class and functions that operate on
or with Field objects.  Much of the functionality of Numeric/num-
array and MA/ma is reproduced for Field objects.  Use the interpre-
ter dir() and help() commands to list all the functions in the mo-
dule.
 
Supporting classes defined in this module include:  BinaryFunction
BinaryOperationExtraMetaNullaryOperationUnaryFunction, and 
UnaryOperation.  ExtraMeta holds all metadata of a Field object 
besides field id, long_name, and units.  The other supporting clas-
ses are explained as follows.
 
The underlying functions of *aryOperation and *aryFunction field 
functions are either Numeric/numarray or MA/ma functions of the 
same name.  The *aryOperation and *aryFunction classes enable the 
module to make intelligent choices as whether to use the Numeric/
numarray or MA/ma version of a function.  As long the two versions
of the function have the same name and can take the same number of 
Field objects (replacing array objects) as arguments, these suppor-
ting classes can be used.  Note however field functions should not
be assumed to have the same methods as Numeric/numarray ufuncs.
 
The terms nullary, unary, and binary refer to the number of Field
objects that are function arguments (in the binary case, one of 
the arguments can be a non-Field array or scalar).  The *ary ob-
jects are assumed to be at the beginning of the parameter list. 
The *aryOperation class is for functions that return a Field ob-
ject.  This includes functions that sometimes return numeric sca-
lars or masks (e.g. where), since such masks are often used in 
arithmetic operations with model variables (to turn on/off a par-
ticular element).  The returned object never shares any storage 
with its input arguments and all non-data attributes are empty.  
The *aryFunction class is for functions that always return non-
array (and thus non-Field) objects, Booleans or scalars under-
stood to be Boolean, or array objects that should not function 
as Field objects (e.g. shape tuples, list of indices, strings) 
and it follows the same rules as its underlying Numeric/numarray 
or MA/ma function as to whether its return value shares storage 
with its input arguments (generally not).  There are no Nullary-
Functions.
 
In order to improve speed, *aryOperation and *aryFunction objects
apply the Numeric/numarray function whenever the data in any *ary
inputs are not a masked MA/ma array.  If an exception is returned, 
the corresponding MA/ma function is tried; arrays output by that
function will be MA/ma.  Thus, if you want to force use of the
MA/ma function in the field version, make sure the data of one of 
the *ary inputs is an MA/ma array.
 
Numeric/numarray and MA/ma have callable attributes associated
with every binary universal function (ufunc), such as accumulate,
outer, etc.  The *aryOperation and *aryFunction objects in this
module do not support those callable attributes.
 
Note that the usage in field of "*ary operation" and "*ary func-
tion" is slightly different than in Numeric/numarray and MA/ma.

 
Modules
       
numarray.ma.MA
numarray.linear_algebra.mlab
numarray
copy
gemath
os
user

 
Classes
       
__builtin__.object
BinaryFunction
BinaryOperation
ExtraMeta
Field
NullaryOperation
UnaryFunction
UnaryOperation

 
class BinaryFunction(__builtin__.object)
    Binary functions on/with Field objects.
 
See the module docstring for details.
 
  Methods defined here:
__call__(self, x, y, *more_args, **kwds)
Calling function.
 
Returns non-numeric objects given two inputs (see argument de-
scription below).
 
Method Arguments:
* x:  Positional argument.  1st Field object, Numeric/numarray
  or MA/ma array or scalar being operated on.
* y:  Positional argument.  2nd Field object, Numeric/numarray
  or MA/ma array or scalar being operated on.
* more_args:  Any additional positional arguments.  Passed to 
  the underlying Numeric/numarray or MA/ma function without 
  change.
* kwds:  Any keyword arguments.  Passed to the underlying Numer-
  ic/numarray or MA/ma function without change.
__init__(self, op_name)
Initialization function.
 
Input Argument:
* op_name:  String that specifies the name of a Numeric/numarray 
  and MA/ma function (e.g. allclose).  The name of the function 
  must be the same for both Numeric/numarray and MA/ma.

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'BinaryFunction' objects>
list of weak references to the object (if defined)

 
class BinaryOperation(__builtin__.object)
    Binary operations on Field objects.
 
See the module docstring for details.
 
  Methods defined here:
__call__(self, x, y, *more_args, **kwds)
Calling function.
 
Returns a Field object whose data is the result of the binary
operation on x and y.  The returned Field object has empty non-
data attributes.  The return Field object does not share any 
data with the input arguments.
 
Method arguments:
* x:  Positional argument.  1st Field object, Numeric/numarray
  or MA/ma array or scalar being operated on.
* y:  Positional argument.  2nd Field object, Numeric/numarray
  or MA/ma array or scalar being operated on.
* more_args:  Any additional positional arguments.  Passed to 
  the underlying Numeric/numarray or MA/ma function without 
  change.
* kwds:  Any keyword arguments.  Passed to the underlying Numer-
  ic/numarray or MA/ma function without change.
__init__(self, op_name)
Initialization function.
 
Input Argument:
* op_name:  String that specifies the name of a Numeric/numarray 
  and MA/ma function (e.g. add).  The name of the function must 
  be the same for both Numeric/numarray and MA/ma.

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'BinaryOperation' objects>
list of weak references to the object (if defined)

 
class ExtraMeta(__builtin__.object)
    Object of all metadata besides id, long_name, and units.
 
Attributes of the object are the names of the metadata and the
values of the attributes are the values of the metadata.  The
class ignores attempts to create or add attributes id, long_name, 
and units.  Metadata are usually strings, lists, or dictionaries.
 
Objects are instantiated by any number of keyword inputs in the
calling line.  Keywords and their values should correspond to a
standard list of possible values, which are specific to a given
model.  For more information see:
 
   http://geosci.uchicago.edu/csc/modelutil/doc/fieldmeta.html
 
Additional metadata is added by setting the attributes of this
object directly.
 
If one of the keywords is extra_meta (set to an ExtraMeta object),
on instantiation of an ExtraMeta object the extra_meta setting is 
used as the basis of the ExtraMeta object, and additional keywords 
are added to those values.
 
Examples:
 
>>> a = ExtraMeta(id='u', axis=['Pressure units'])
>>> print a.__dict__
{'axis': ['Pressure units']}
>>> print a.axis[0]
Pressure units
>>> print a.id
Traceback (most recent call last):
    ...
AttributeError: 'ExtraMetaobject has no attribute 'id'
 
>>> a.axis = ['Latitude']
>>> print a.axis[0]
Latitude
>>> a.id = 'u'
>>> print a.id
Traceback (most recent call last):
    ...
AttributeError: 'ExtraMetaobject has no attribute 'id'
 
  Methods defined here:
__init__(self, **keywords)
__setattr__(self, name, value)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'ExtraMeta' objects>
list of weak references to the object (if defined)

 
class Field(__builtin__.object)
    Class for a single model field.
 
Container object for a model parameter or quantity.  The data 
for a Field object is imported from either a Numeric/numarray 
or MA/ma array or scalar.
 
Public Instance Attributes:
* extra_meta:  Object containing all metadata associated with the 
  field besides id, long_name, and units.  Instance of class Ex-
  traMeta.  Default is an empty ExtraMeta object.
* id:  Unique name of the field.  String.  Default value is None.
* long_name:  Description of the field.  String.  Default value 
  is None.
* units:  Units of the field.  String.  Default value is None.
 
 
The names of all accepted public and private instance attributes 
is given in the field module tuple _ok_field_attrib.
 
All metadata for the object (especially self.id and self.units)
should follow an accepted convention with an appropriate mapping.
Such a mapping is specific to a given model.  For more information
see:
 
   http://geosci.uchicago.edu/csc/modelutil/doc/fieldmeta.html
 
See the docstring for __init__ for details about object instanti-
ation.  Note that the data for the Field container is stored in
private attribute self._data, which is either a Numeric/numarray 
or MA/ma array or scalar.  (Some of the Numeric/numarray and MA/ma
methods are also defined for Field objects.)  Please do not access 
the _data attribute directly but rather use the predefined methods 
for the Field class (e.g. setdata and refdata).  The field module 
also contains functions that operate on Field objects.
 
 
(1) Example without metadata:
 
>>> data = [1., 2., 5., -3., -4.4]
>>> a = Field(data)
>>> ['%.6g' % a[i] for i in range(len(a))]
['1', '2', '5', '-3', '-4.4']
>>> print a.typecode()
d
>>> print a.id
None
>>> print a.extra_meta.__dict__
{}
 
 
(2) Example setting data as Float32 and with some metadata:
 
>>> data = N.array([1., 2., 5., -3., -4.4])
>>> a = Field(data.astype(N.Float32), id='u', axis=['Latitude'])
>>> ['%.6g' % a[i] for i in range(len(a))]
['1', '2', '5', '-3', '-4.4']
>>> print a.typecode()
f
>>> print a.id
u
>>> print a.extra_meta.axis[0]
Latitude
 
>>> a[2:4] = N.array([-3.4, 55.32])
>>> ['%.6g' % a[i] for i in range(len(a))]
['1', '2', '-3.4', '55.32', '-4.4']
 
 
(3) Example of using a field function on a Field object:
 
>>> b = sin(a)
>>> print b.id
None
>>> print b.extra_meta.__dict__
{}
>>> ['%.6g' % b[i] for i in range(len(b))]
['0.841471', '0.909297', '0.255541', '-0.942043', '0.951602']
 
  Methods defined here:
__abs__(self)
__add__(self, other)
__call__(self)
__contains__(self, item)
Result of Boolean test on data in Field object.
__delitem__(self, key)
__div__(self, other)
__divmod__(self, other)
__eq__(self, other)
__floordiv__(self, other)
__ge__(self, other)
__getitem__(self, key)
__gt__(self, other)
__iadd__(self, other)
__idiv__(self, other)
__ifloordiv__(self, other)
__imod__(self, other)
__imul__(self, other)
__init__(self, data, **keywords)
Initialize Field class object.
 
Method arguments:
* data:  A list, tuple, scalar, Numeric/numarray array, MA/
  ma array, or Field object of field data.  If data is a list,
  tuple, or scalar (a scalar is defined as an object with an 
  empty shape tuple), the input is converted into a Numeric/
  numarray object (or MA/ma object if the scalar is the masked 
  value) and set by value.  If data is a Numeric/numarray ar-
  ray, MA/ma array, or Field object, the data is passed into
  the new Field object by reference.  If data is a Field object
  the metadata in the new Field object is taken from the in-
  stantiation argument line as opposed to the input Field ob-
  ject; only the data comes from the input Field object.
 
* keywords:  A dictionary of keywords and values that specify
  metadata attributes of the object to set.  Keywords id, 
  long_name, and units are set as attributes while all other 
  keywords are set as attributes of the ExtraMeta object sto-
  red in attribute extra_meta.  Attribute names (either in 
  the Field or ExtraMeta objects) are the keyword keys and 
  their values the keyword values.
 
If one of the keywords is extra_meta (set to an ExtraMeta
object), that object is used as the basis of the extra_meta
attribute, and additional keywords are added in to that key-
word specified ExtraMeta object.
 
See class header for additional details of instance attributes
of this class.
__isub__(self, other)
__itruediv__(self, other)
__le__(self, other)
__len__(self)
Result of len() on data in Field object.
__lt__(self, other)
__mod__(self, other)
__mul__(self, other)
__ne__(self, other)
__neg__(self)
__pos__(self)
__pow__(self, other)
__radd__ = __add__(self, other)
__rdiv__(self, other)
__rmod__(self, other)
__rmul__ = __mul__(self, other)
__rsub__(self, other)
__setattr__(self, name, value)
Set attribute for Field class.
 
The Field class should only have the attributes defined in the
module tuple _ok_field_attrib.  This overloaded __setattr__ 
function ensures no other attributes are set, raising an excep-
tion if you attempt to add an unaccepted attribute.
__setitem__(self, key, value)
Set item in container.
 
If value is a Field object, self._data[key] is set to the _data
attribute of value.  Otherwise, value is set to self._data.
__str__(self)
Return human-readable representation of Field object.
 
Method returns a string representation of the data in the Field
object, using the __repr__ method in Numeric/numarray or MA/ma.
Metadata attributes in the Field object are not printed.
__sub__(self, other)
__truediv__(self, other)
asMA(self)
Returns deepcopy of Field object with data as ma/MA array.
astype(self, typecode)
Returns deepcopy of Field object with data cast to typecode.
clear_all_meta(self)
Clears all metadata fields.
 
Sets metadata attributes (listed in _key_meta) to None and 
extra_meta attribute to an empty ExtraMeta object.
clear_extra_meta(self)
Sets the extra_meta attribute to an empty ExtraMeta object.
copy(self)
Returns deepcopy of Field object.
copydata(self)
Returns deepcopy (if possible) of data of Field object.
 
Result returned is a Numeric/numarray or MA/ma array object.
Deepcopy returns a TypeError when executed on a deepcopy of
Field object, and thus in the TypeError case a shallow
copy is returned.
copymeta(self)
Returns deepcopy of Field object metadata.
 
The entire Field object is copied, except for the data held 
in the container (i.e. in private variable _data).  Instead, 
the returned Field object has an empty array for the object's 
data, in addition to a copy of the original Field object's 
metadata.
fill_value(self)
Returns fill value of Field object data if data is MA.
 
If the data fill value is None or if the data is not an MA/ma 
array, None is returned.
filled(self, fill_value=None)
Returns deepcopy of Field object with data as Numeric/numarray array.
 
Masked values are filled in by fill_value.  If fill_value is 
None, fill_value() is used.
isMA(self)
Returns True if data of Field object is MA.
is_scalar(self)
Returns True if data of Field object has shape == ().
is_size1(self)
Returns True if data of Field object has size == 1.
 
This is True for scalars (empty shape tuple) and one element
arrays (of any shape).
meta_ok_to_interface(self, IMobj, check_long_name=False)
Returns True if metadata passes checks for interfaces.
 
Tests whether the Field object metadata passes consistency
checks in accordance with the description given in Interface-
Meta object IMobj.
 
Positional Input Argument:
* IMobj:  InterfaceMeta object that defines the accepted
  metadata that you wish to check this Field variable's
  metadata against.  For details see:
 
     http://geosci.uchicago.edu/csc/modelutil/doc/imeta.html
 
Keyword Input Arguments:
* check_long_name:  If set to True, the method not only
  checks units but also long_name.  Default is False.
 
For this method to return True the Field variable does not 
have to be one defined in the IMobj definition, but if it is 
defined, it has to have the same metadata as given in IMobj.
 
The consistency checks are simple and include:
* If this Field variable's id is found in IMobj.axis, the
  isaxis attribute must be true and the units must match the
  id in IMobj.
* If this Field variable's id is found in IMobj.id, the units 
  must match the id in IMobj.
* If this Field variable's id is found in IMobj.id, and the
  extra_meta attribute axis exists, that the value is in
  IMobj, that the corresponding values of axis_units match
  (if axis_units exists), and whether the number of dimen-
  sions of the data matches the number of axis and axis_units 
  labels.  If isaxis is True and extra_meta.axis (or related 
  attributes) exist an exception is raised.
* An exception is raised if axis is defined but axis_units 
  is not (or vice versa).
* If the check_long_name flag is True, the above tests on 
  units and axis_units are also applied to long_name and
  axis_long_name.  Each test, of course, is only conducted
  when long_name or axis_long_name, respectively, are defined.
  Also, if long_name is None, the test of that attribute is
  ignored.
refdata(self)
Returns reference to data of Field object.
 
This returns a reference to the private attribute _data, which
is a Numeric/numarray or MA/ma array.
replace_all_meta(self, *arg, **keywords)
Clear all metadata fields and replace.
 
Erases all metadata values.  Sets metadata to the metadata val-
ues given in Field object *arg or by the input keyword para-
meters given in **keywords.  The data in the Field container 
object is unaltered.
 
Method arguments:
* arg:  A single argument specifying a Field object whose
  metadata will be copied in its entirety and used to replace
  the metadata of the current Field object.  If arg is set,
  any keywords specified are ignored.
 
* keywords:  A dictionary of keywords and values that specify
  metadata attributes of the object to set.  Keywords id,
  long_name, and units are set as attributes (default value
  of None) while all other keywords are set as attributes of
  the extra_meta object.  Attribute names are the keyword
  keys and their values the keyword values.
 
See class header for additional details of instance attributes
of the Field class.
 
Examples:
>>> data = [1., 2., 5., -3., -4.4]
>>> a = Field( data, id='Ts', long_name='Surface temperature'                      , units='K' )
>>> print a.id
Ts
>>> print a.extra_meta.__dict__
{}
 
>>> a.replace_all_meta( id='F_sens', long_name='Sensible heat'                               , units='W/m**2', axis=['Latitude'] )
>>> print a.id
F_sens
>>> print a.extra_meta.__dict__
{'axis': ['Latitude']}
 
>>> b = Field([4.3, -6.45], id='FL')
>>> a.replace_all_meta(b)
>>> print a.id
FL
>>> print a.extra_meta.__dict__
{}
setdata(self, data)
Set private _data attribute to equal Field object data.
 
Positional input argument:
* data:  If data is a Numeric/numarray or MA/ma array, the
  method makes a reference of data to the private attribute 
  _data.  If data is a list, tuple, or scalar (defined as
  having an empty shape tuple), the private attribute _data 
  is set to N.array(data).  Any other input throws an excep-
  tion.
 
All occurrences in this module that set _data to reference 
the specified data use this method.  Other types of set co-
mmands (e.g. in-place operations) may not use this method, 
instead operating on _data directly.
 
Note when the setdata method is used in setting the Field in-
stance to data the data is set by reference.
slice_fixed(self, axes_State, **kwds)
Return slice of Field object with selected fixed axis(es).
 
The general array slicing syntax used in Numeric/numarray and
MA/ma arrays is supported in Field objects and is appropriate 
for most purposes.  However, one common slicing operation is 
to fix one or more axis and extract the resulting subarray.  
For instance, if you have an array dimensioned (level, lati-
tude, longitude), you might want to extract a latitude-longi-
tude slice at a given level.  This method enables you to do 
this by specifying the level value (as opposed to index) you 
wish to fix and the State object which contains the Field var-
iables that describe the axes of the present Field object.
The method accepts both a single fixed axis value to apply to
all the other elements in the data, or an array of values to
make the slice at.  The examples below will help describe
these two types of slicing capabilities.
 
The returned subarray is a Field object and has all the meta-
data from the original Field object, with the axis attribute
(and related attributes like axis_units) altered as appropriate.
The returned slice is a reference to or copy of the original 
data based upon the following criteria:
 
   If:  Field data  and  Kwd Size 1  | Then:  subarray is
   ---------------------------------------------------------
   masked            |    False      | Copy of orig. data
   not masked        |    False      | Copy of orig. data
   masked            |     True      | Copy of orig. data
   not masked        |     True      | References orig. data
 
Where "Kwd Size 1" is True if all keywords in the calling line
are scalars/arrays of size 1.  In all cases, the metadata is 
a copy.  If the Field object is a scalar or 1-element array 
(i.e. is_size1() returns True), the above chart does not
apply and this method always returns a reference to the Field 
object.
 
Note that this method will only work if self has the axis
attribute in extra_meta.  It will also alter the axis_units 
and axis_long_name attributes, as appropriate, if they exist
in extra_meta, but those two attributes are not required for
this method to work.
 
If you want to set a fixed slice of data to a different value,
use the slice_fixed_setdata method.
 
 
Positional Input Parameter:
* axes_State:  A State object that contains the Field objects
  that describe the axes for self.  axes_State can contain
  other Field objects too.
 
Keyword Input Parameters:
* kwds:  Dictionary of axes to fix in taking the subarray of
  self.  The keys are the Field ids of the axes for self and
  the values are the values of where to fix the axes to ex-
  tract the subarray.  Those values should be scalars or 1-
  element arrays, or arrays with the shape of the slice if
  all the axes labeled by the keywords were removed from the
  data array (masked or unmasked arrays are both ok, although
  if the array is masked it cannot have any elements where
  the mask is True/1).  Keywords that are not in the list of 
  axis ids for the Field object are ignored in making the 
  slice.
 
 
The metadata (e.g. list of axis ids) attached to the Field
object is assumed correct:  There are no explicit checks for 
this done by this method (e.g. it does not check whether the 
number of dimensions of the data equals the number of elements 
in extra_meta.axis).
 
 
Examples:
(1) The simplest case is making a slice at a constant level
    for all elements of the array.  Take for instance the ex-
    ample of a slice at pressure level 500 hPa:
 
    >>> from state import State
    >>> data = N.reshape(N.arange(36.)*0.2+290., (3,3,4))
    >>> lon = N.arange(4.)*90.
    >>> lat = N.array([-90., 0., 90.])
    >>> lev = N.array([850., 500., 250.])
    >>> f1 = Field( data, id='Ts', units='K'                           , axis=['lev', 'lat', 'lon'] )
    >>> f2 = Field(lon, id='lon', units='degrees_east', isaxis=True)
    >>> f3 = Field(lat, id='lat', units='degrees_north', isaxis=True)
    >>> f4 = Field(lev, id='lev', units='hPa', isaxis=True)
    >>> s = State(f1, f2, f3, f4, id='t0')
    >>> print shape(f1)
    (3, 3, 4)
    >>> print f1.extra_meta.axis
    ['lev', 'lat', 'lon']
    >>> data[1,:,:]
    array([[ 292.4,  292.6,  292.8,  293. ],
           [ 293.2,  293.4,  293.6,  293.8],
           [ 294. ,  294.2,  294.4,  294.6]])
 
    >>> subarray = f1.slice_fixed(s, lev=500)
    >>> print subarray
    array([[ 292.4,  292.6,  292.8,  293. ],
           [ 293.2,  293.4,  293.6,  293.8],
           [ 294. ,  294.2,  294.4,  294.6]])
    >>> print shape(subarray)
    (3, 4)
    >>> print subarray.extra_meta.axis
    ['lat', 'lon']
 
    The slicing operation that created subarray is equivalent 
    to the slicing operation f1.refdata()[1,:,:] (which in
    turn is equivalent to slicing data[1,:,:], since f1 refer-
    ences data.  The result subarray is of shape (3,4); the
    first axis in data is removed since the slice occurs at a
    fixed value of the axis.
 
(2) Using the same data f1 above, here we give the case of 
    making a slice in pressure levels, but at different levels
    at each lat-lon location:
 
    >>> levels =                     N.array([[ 500,  850,  850,  250 ],                              [ 500,  250,  500,  500 ],                              [ 250,  500,  850,  250 ]])
    >>> subarray = f1.slice_fixed(s, lev=levels)
    >>> print subarray
    array([[ 292.4,  290.2,  290.4,  295.4],
           [ 293.2,  295.8,  293.6,  293.8],
           [ 296.4,  294.2,  292. ,  297. ]])
    >>> print shape(subarray)
    (3, 4)
    >>> print subarray.extra_meta.axis
    ['lat', 'lon']
 
    Note again the result subarray has shape (3,4), which is
    the same shape as the array used to specify levels.
 
(3) When you make a slice so only a single element remains,
    the returned Field object is a scalar with axis related
    metadata attributes removed.  Using f1 from above:
 
    >>> subarray = f1.slice_fixed(s, lev=500, lat=-90, lon=0)
    >>> print subarray
    array(292.39999999999998)
    >>> print shape(subarray)
    ()
    >>> print hasattr(subarray.extra_meta, 'axis')
    False
 
(4) There is an exception to (3) above.  If you slice a single
    element out of an array which has axes of length 1, the
    returned sliced array will retain those axes.  Thus, if
    f1 has shape (4,1,1), f1.extra_meta.axis equals the list
    ['x','y','z'], the axis are each equal to N.arange, and 
    the axis are in State object s, then:
 
        subarray = f1.slice_fixed(s, x=2, y=0, z=0)
 
    will return subarray of shape (1,1), and the value of
    subarray.extra_meta.axis = ['y', 'z'].
slice_fixed_setdata(self, axes_State, setvalue, **kwds)
Set data in a selected fixed axis slice of Field object.
 
The general array slicing syntax used in Numeric/numarray and
MA/ma arrays is supported in Field objects and is appropriate 
for most purposes.  However, one common slicing operation is 
to fix one or more axis and extract the resulting subarray.
The slice_fixed method accomplishes that task.
 
Sometimes you wish to replace the elements selected by the
slice_fixed method with values from another array or a scalar.
This method (slice_fixed_setdata) accomplishes that.  See the
docstring for slice_fixed for a fuller description of what
kind of slicing (i.e. selection for replacement) is done.
 
Only the data in self is changed, and the elements of the 
slice specified by the keywords are set to the elements of po-
sitional input parameter setvalue.  In all cases the data in 
self are set to setvalue by value, not reference, due to how 
the Numeric/numarray and MA/ma packages handle setting slices.
 
If the data in self is of size 1, any slicing keywords and the
value of self is set to setvalue (which of course must also be
of size 1).  Also note that this method will only work if self 
has the axis attribute in extra_meta.  
 
 
Positional Input Parameter:
* axes_State:  A State object that contains the Field objects
  that describe the axes for self.  axes_State can contain
  other Field objects too.
 
* setvalue:  A scalar, list, array, or Field object whose data
  values the data slice of self will be set to.  setvalue must 
  be conformable to the data in self; if setvalue is a scalar 
  and the slicing rules result in an array, all elements of 
  that slice are set to the setvalue value.
  
Keyword Input Parameters:
* kwds:  Dictionary of axes to fix in specifying the subarray 
  of self.  The keys are the Field ids of the axes for self
  and the values are the values of where to fix the axes to
  set the data to setvalue.  kwds values should be scalars or
  1-element arrays, or arrays with the shape of the slice if
  all the axes labeled by the keywords were removed from the
  data array (masked or unmasked arrays are both ok, although
  if the array is masked it cannot have any elements where the
  mask is True/1).  Keywords that are not in the list of axis 
  ids for the Field object are ignored in making the slice.
 
The metadata (e.g. list of axis ids) attached to the Field
object is assumed correct:  There are no explicit checks for
this done by this method (e.g. it does not check whether the
number of dimensions of the data equals the number of elements
in extra_meta.axis).
 
Examples:
(1) Simple case of replacing a slice at pressure level 500 hPa
    using scalar keywords:
 
    >>> from state import State
    >>> data = N.reshape(N.arange(36.)*0.2+290., (3,3,4))
    >>> lon = N.arange(4.)*90.
    >>> lat = N.array([-90., 0., 90.])
    >>> lev = N.array([850., 500., 250.])
    >>> f1 = Field( data, id='Ts', units='K'                           , axis=['lev', 'lat', 'lon'] )
    >>> f2 = Field( lon, id='lon', units='degrees_east'                           , isaxis=True )
    >>> f3 = Field( lat, id='lat', units='degrees_north'                           , isaxis=True )
    >>> f4 = Field( lev, id='lev', units='hPa', isaxis=True )
    >>> s = State(f1, f2, f3, f4, id='t0')
    >>> print shape(f1)
    (3, 3, 4)
    >>> print f1.extra_meta.axis
    ['lev', 'lat', 'lon']
    >>> data[1,:,:]
    array([[ 292.4,  292.6,  292.8,  293. ],
           [ 293.2,  293.4,  293.6,  293.8],
           [ 294. ,  294.2,  294.4,  294.6]])
 
    >>> subarray = f1.slice_fixed(s, lev=500)
    >>> print subarray
    array([[ 292.4,  292.6,  292.8,  293. ],
           [ 293.2,  293.4,  293.6,  293.8],
           [ 294. ,  294.2,  294.4,  294.6]])
    >>> print shape(subarray)
    (3, 4)
    >>> print subarray.extra_meta.axis
    ['lat', 'lon']
 
    >>> tmp = N.array([[ 282.4,  282.6,  293.8,  294. ],                                [ 313.2,  293.9,  299.6,  293.2],                                [ 295. ,  294.1,  292.4,  291.6]])
    >>> f1.slice_fixed_setdata(s, tmp, lev=500)
    >>> f1[1,:,:]
    array([[ 282.4,  282.6,  293.8,  294. ],
           [ 313.2,  293.9,  299.6,  293.2],
           [ 295. ,  294.1,  292.4,  291.6]])
    >>> print subarray
    array([[ 282.4,  282.6,  293.8,  294. ],
           [ 313.2,  293.9,  299.6,  293.2],
           [ 295. ,  294.1,  292.4,  291.6]])
 
(2) Using the same data f1 above, here we give the case of re-
    placing a slice in pressure levels, but at different le-
    vels at each lat-lon location:
 
    >>> f1 = Field( data, id='Ts', units='K'                           , axis=['lev', 'lat', 'lon'] )
    >>> tmp = N.array([[ 282.4,  282.6,  293.8,  294. ],                                [ 313.2,  293.9,  299.6,  293.2],                                [ 295. ,  294.1,  292.4,  291.6]])
    >>> levels =                     N.array([[ 500,  850,  850,  250 ],                              [ 500,  250,  500,  500 ],                              [ 250,  500,  850,  250 ]])
    >>> subarray = f1.slice_fixed(s, lev=levels)
    >>> f1.slice_fixed_setdata(s, tmp, lev=levels)
    >>> N.array([f1[1,0,0], f1[0,0,1], f1[0,0,2], f1[2,0,3]])
    array([ 282.4,  282.6,  293.8,  294. ])
typecode(self)
Returns typecode of the data in the Field object.
wrap(self)
Connect the MPI parallel subdomains of Field variable.
 
Currently this is just a placeholder function and doesn't do
anything.

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Field' objects>
list of weak references to the object (if defined)

 
class NullaryOperation(__builtin__.object)
    Nullary operations on Field objects.
 
See the module docstring for details.
 
  Methods defined here:
__call__(self, *more_args, **kwds)
Calling function.
 
Returns a Field object whose data is the result of the operation
based on the input arguments.  The object has empty non-data
attributes and shares no memory with inputs.
 
Method Arguments:
* more_args:  Positional arguments.  Passed to the underlying 
  Numeric/numarray or MA/ma function without change.
* kwds:  Keyword arguments.  Passed to the underlying Numeric/
  numarray or MA/ma function without change.
__init__(self, op_name)
Initialization function.
 
Input Argument:
* op_name:  String that specifies the name of a Numeric/numarray 
  and MA/ma function (e.g. zeros).  The name of the function must 
  be the same for both Numeric/numarray and MA/ma.

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'NullaryOperation' objects>
list of weak references to the object (if defined)

 
class UnaryFunction(__builtin__.object)
    Unary functions on/with Field objects.
 
See the module docstring for details.
 
  Methods defined here:
__call__(self, x, *more_args, **kwds)
Calling function.
 
Returns non-numeric objects given operations on one input (see 
argument description below).
 
Method arguments:
* x:  Positional argument.  Field object being operated on/with.
* more_args:  Any additional positional arguments.  Passed to 
  the underlying Numeric/numarray or MA/ma function without 
  change.
* kwds:  Any keyword arguments.  Passed to the underlying Numer-
  ic/numarray or MA/ma function without change.
__init__(self, op_name)
Initialization function.
 
Input Argument:
* op_name:  String that specifies the name of a Numeric/numarray 
  and MA/ma function (e.g. shape).  The name of the function must 
  be the same for both Numeric/numarray and MA/ma.

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'UnaryFunction' objects>
list of weak references to the object (if defined)

 
class UnaryOperation(__builtin__.object)
    Unary operations on Field objects.
 
See the module docstring for details.
 
  Methods defined here:
__call__(self, x, *more_args, **kwds)
Calling function.
 
Returns a Field object is returned with empty non-data attri-
butes, whose data is the result of the unary operation.  The
returned object does not share data memory with input object.
 
Method Arguments:
* x:  Positional argument.  Field object being operated on.
* more_args:  Any additional positional arguments.  Passed to
  the underlying Numeric/numarray or MA/ma function without 
  change.
* kwds:  Any keyword arguments.  Passed to the underlying Numer-
  ic/numarray or MA/ma function without change.
__init__(self, op_name)
Initialization function.
 
Input Argument:
* op_name:  String that specifies the name of a Numeric/numarray 
  and MA/ma function (e.g. sinh).  The name of the function must 
  be the same for both Numeric/numarray and MA/ma.

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'UnaryOperation' objects>
list of weak references to the object (if defined)

 
Functions
       
average(*args, **kwds)
clip(*args, **kwds)
compress(*args, **kwds)
concatenate(*args, **kwds)
copymeta_largest(*args)
Returns deepcopy of metadata from the "largest" object in args.
 
The function finds the "largest" Field object in args, creates a
Field object that is a copy of all the metadata and only the meta-
data (i.e. the entire object except the data), and returns that 
Field object.  "Largest" in this case is defined as the Field ob-
ject whose data array has:
 
1) The largest number of total elements.
2) The largest number of dimensions (rank).
3) The largest number of elements in each dimension, starting 
   with the last dimension, and comparing backwards in dimension
   until the first dimension.
4) If there are more than one objects that tie after going through
   criteria 1-3, the metadata returned is from the earliest object 
   (i.e. earliest in the order in the args list) that meet those 
   criteria.
 
The order of criteria given above is the order in which evaluation
of "largest" is made.  Evaluation of criteria continues only as 
long as needed to converge to a single candidate.  Thus, a (3,2) 
array will be "larger" than a (6,) array, a (7,) array larger than 
the (3,2) array, and a (2,3) array is larger than a (3,2) array.
 
Input Positional Parameter(s):
* args:  Field objects.  All Field objects must have unique ids
  (this condition is not checked for, however, by this function).
 
Example:
>>> f1 = Field(N.array([[2., 4., 1.],[4., 2., -5.]]), id='u')
>>> f2 = Field(N.array([2., 4., 1., 4., 2., -5.]), id='v')
>>> f3 = Field(N.array(3.), id='w')
>>> tmp = copymeta_largest(f1, f2, f3)
>>> print tmp.__class__.__name__
Field
>>> print tmp.id
u
>>> print tmp.units
None
>>> print tmp.refdata()
[]
put(*args, **kwds)
ravel(a)
Ravel data in Field object a to flat form.
 
Returns a Field object whose metadata (except for the metadata
in extra_meta) is a deep copy of the metadata in a, but whose 
data is a raveled reference of the data in Field object a.  The
extra_meta attribute of the returned Field object is set to an 
empty ExtraMeta object, since the ExtraMeta object often holds 
information about the axis of the Field object.
 
Input Argument:
* a:  Field object.  Unchanged by function.
 
Example:
>>> data = N.array([[-0.11, 2.1, 5.3], [3.9, 4.4, -2.0]])
>>> x = Field( data, id='u', long_name='Zonal wind'                  , axis=['lat', 'lon'] )
>>> print x.extra_meta.__dict__
{'axis': ['lat', 'lon']}
>>> print shape(x)
(2, 3)
>>> y = ravel(x)
>>> print y
array([-0.11,  2.1 ,  5.3 ,  3.9 ,  4.4 , -2.  ])
>>> print y.extra_meta.__dict__
{}
>>> print shape(y)
(6,)
>>> print shape(x)
(2, 3)
reshape(a, shapetuple)
Reshape data in Field object a to shapetuple.
 
Returns a Field object whose metadata (except for the metadata
in extra_meta) is a deep copy of the metadata in a, but whose 
data is a reference to the data in Field object a, reshaped to
shapetuple.  The extra_meta attribute of the returned Field ob-
ject is set to an empty ExtraMeta object, since the ExtraMeta 
object often holds information about the axis of the Field ob-
ject.
 
Input Arguments:
* a:  Field object.  Unchanged by function.
* shapetuple:  Tuple describing the new shape of the data.
 
Example:
>>> data = N.array([-0.11, 2.1, 5.3, 3.9, 4.4, -2.0])
>>> x = Field(data, id='u', long_name='Zonal wind', axis=['Latitude'])
>>> print x.extra_meta.__dict__
{'axis': ['Latitude']}
>>> print shape(x)
(6,)
>>> y = reshape(x, (3,2))
>>> print x
array([-0.11,  2.1 ,  5.3 ,  3.9 ,  4.4 , -2.  ])
>>> print y
array([[-0.11,  2.1 ],
       [ 5.3 ,  3.9 ],
       [ 4.4 , -2.  ]])
>>> print shape(y)
(3, 2)
>>> print x.extra_meta.__dict__
{'axis': ['Latitude']}
>>> print y.extra_meta.__dict__
{}
take(*args, **kwds)
where(condition, x, y)
Returns Field object with x where condition is true, else y.
 
Positional input parameters:
* condition:  A condition expressed as a Numeric/numarray, MA/ma 
  masked array, or Field object with array data of True (1) or 
  False (0) elements.
* x:  Value for elements where condition is True.
* y:  Value for elements where condition is not True.
 
Result returned is of the same shape as condition.  x and y are 
either the same shape as condition or scalars, and can be Numeric/
numarray arrays, MA/ma arrays, or Field objects.  Result returned 
is Field object with data as Numeric/numarray or MA/ma masked ar-
ray; which one is dependent on whether condition is the result of 
operating on data that is of type Numeric/numarray or MA/ma.  The 
result is masked if either the condition is masked, or x or y is 
masked.  Result shares no memory with inputs and all metadata
attributes are empty.
 
Examples:
>>> a = Field(N.array([1., 2., 3.]))
>>> b = where(a > 1.5, 1, 0)
>>> ['%.6g' % b[i] for i in range(len(b))]
['0', '1', '1']
>>> print b.isMA()
False
 
>>> a = Field(MA.masked_array([1., 2., 3.]))
>>> y = Field([-999., -999., -999.])
>>> b = where(a > 1.5, 1, y)
>>> ['%.6g' % b[i] for i in range(len(b))]
['-999', '1', '1']
>>> print b.isMA()
True
where_close(x, y, rtol=1.0000000000000001e-05, atol=1e-08)
Mask of where x and y are element-wise "equal" to each other.
 
Returns an integer Field object with elements equal to 1 where x 
and y are "equal", and 0 otherwise.  If x or y are floating point, 
"equal" means where abs(x-y) <= atol + rtol * abs(y).  This is 
essentially the same algorithm used in the Numeric/numarray func-
tion allclose.  If x and y are integer, "equal" means strict equal-
ity.  Shape and size of output is the same as x and y; if one is 
an array and the other is scalar, shape and size of the output is 
the same as the array.  
 
Data of the output Field object is an MA/ma masked array, unless 
the data for both objects are not MA/ma objects, in which case the 
output Field object's data is a Numeric/numarray array.  If inputs 
are both unmasked scalars the output is a scalar Field object.  
Result shares no memory with inputs and all metadata attributes 
are empty.
 
Positional Input Arguments:
* x:  Scalar, Numeric/numarray array, MA/ma array, Python list/
  tuple of any size and shape, or Field object.  Floating or inte-
  ger type.
* y:  Scalar, Numeric/numarray array, MA/ma array, Python list/
  tuple of any size and shape, or Field object.  Floating or inte-
  ger type.
 
Keyword Input Arguments:
* rtol:   "Relative" tolerance.  Default is 1.e-5.  Used in the
          comparison between x and y only if the two are floating 
          point.
* atol:   "Absolute" tolerance.  Default is 1.e-8.  Used in the
          comparison between x and y only if the two are floating 
          point.
 
If either of the inputs are MA/ma masked objects, this function
uses the MA/ma default algorithm for comparison, i.e. masked val-
ues are always considered equal.
 
Examples:
>>> x = Field([20.,  -32., -1., 2.  , 5., 29.])
>>> y = Field([20.1, -31., -1., 2.01, 3., 28.99])
>>> ind = where_close(x, y)
>>> ['%.1g' % ind[i] for i in range(len(ind))]
['0', '0', '1', '0', '0', '0']
 
>>> x = Field([20.,  -32., -1., 2.            , 5., 29.])
>>> y = Field([20.1, -31., -1., 2.000000000001, 3., 28.99])
>>> ind = where_close(x, y)
>>> ['%.1g' % ind[i] for i in range(len(ind))]
['0', '0', '1', '1', '0', '0']
 
>>> x = N.array([1,  5,  7, -2, 10])
>>> y = N.array([1, -5, 17, -2,  0])
>>> ind = where_close(x, y)
>>> ['%.1g' % ind[i] for i in range(len(ind))]
['1', '0', '0', '1', '0']
 
>>> x = -2 
>>> y = Field([1,  5,  7, -2, 10])
>>> ind = where_close(x, y)
>>> ['%.1g' % ind[i] for i in range(len(ind))]
['0', '0', '0', '1', '0']

 
Data
        __author__ = 'Johnny Lin <http://www.johnny-lin.com/>'
__credits__ = 'Thanks to the CSC group at the University of Chicago.'
__date__ = '12 Jan 2005'
__test__ = {'Additional Test 1: Simple array': "\n#- Test Field initialization and access data:\n\n...'5.1', '-2.9', '-4.3']\n\n>>> print a.typecode()\nd\n", 'Additional Test 2: Complex arrays': "\n#- Test in-place numeric binary functions and m...1.32', '2.32', '5.32', '-2.68', '-4.08', '2.52']\n", 'Additional Test 3: Check functions/operations for results sharing memory': '\n#- Check nullary operations results:\n\n * ara... [ 5.3 , 3.9 ],\n [ 4.4 , -88. ]])\n'}
__version__ = '0.1.1'
absolute = <field.UnaryOperation object>
add = <field.BinaryOperation object>
allclose = <field.BinaryFunction object>
alltrue = <field.UnaryOperation object>
arange = <field.NullaryOperation object>
arccos = <field.UnaryOperation object>
arcsin = <field.UnaryOperation object>
arctan = <field.UnaryOperation object>
arctan2 = <field.BinaryOperation object>
array = <field.UnaryOperation object>
ceil = <field.UnaryOperation object>
conjugate = <field.UnaryOperation object>
cos = <field.UnaryOperation object>
divide = <field.BinaryOperation object>
dot = <field.BinaryOperation object>
equal = <field.BinaryOperation object>
exp = <field.UnaryOperation object>
fabs = <field.UnaryOperation object>
floor = <field.UnaryOperation object>
floor_divide = <field.BinaryOperation object>
fmod = <field.BinaryOperation object>
gemath_num_package = 'numarray'
gemathrc = '/home/jlin/.gemathrc.py'
greater = <field.BinaryOperation object>
greater_equal = <field.BinaryOperation object>
home_dir = '/home/jlin'
innerproduct = <field.BinaryOperation object>
less = <field.BinaryOperation object>
less_equal = <field.BinaryOperation object>
log = <field.UnaryOperation object>
log10 = <field.UnaryOperation object>
logical_and = <field.BinaryOperation object>
logical_not = <field.UnaryOperation object>
logical_or = <field.BinaryOperation object>
logical_xor = <field.BinaryOperation object>
look_up_gemathrc = True
maximum = <field.BinaryOperation object>
minimum = <field.BinaryOperation object>
multiply = <field.BinaryOperation object>
negative = <field.UnaryOperation object>
nonzero = <field.UnaryFunction object>
not_equal = <field.BinaryOperation object>
ones = <field.NullaryOperation object>
outerproduct = <field.BinaryOperation object>
power = <field.BinaryOperation object>
rank = <field.UnaryOperation object>
remainder = <field.BinaryOperation object>
resize = <field.UnaryOperation object>
shape = <field.UnaryFunction object>
sin = <field.UnaryOperation object>
size = <field.UnaryOperation object>
sometrue = <field.UnaryOperation object>
sort = <field.UnaryOperation object>
sqrt = <field.UnaryOperation object>
subtract = <field.BinaryOperation object>
tan = <field.UnaryOperation object>
tanh = <field.UnaryOperation object>
transpose = <field.UnaryOperation object>
true_divide = <field.BinaryOperation object>
zeros = <field.NullaryOperation object>

 
Author
        Johnny Lin <http://www.johnny-lin.com/>

 
Credits
        Thanks to the CSC group at the University of Chicago.