import cdms2 as cdm
import cdutil as cdu
from genutil import statistics
from cdms2.selectors import Selector
import MV2 as mv

#
# Libray to compute ENSO metrics
# These procedures have file names as inputs and metric as output
#

def EnsoAmpl (sstfile, varname, ninobox):
    '''
    The EnsoAmpl() function compute the standard deviation in a ninobox

    Author:    Eric Guilyardi : Eric.Guilyardi@locean-ipsl.upmc.fr
    Co-author:

    Created on Mon Jan  9 11:05:18 CET 2017

    Inputs:
    ------
    - sstfile    - time/lat/lon array using Omon values
    - varname    - name of sst variable (tos, ts)
    - ninobox    - name of box ('nino3','nino3.4')

    Output:
    - amplMetric dict:
        - name, value, units, method, nyears, ref

    Notes:
    -----
    - could add error calculation

    '''
    cdm.setAutoBounds('on')

    # Define metric attributes
    Name   = 'ENSO amplitude'
    Units  = 'C'
    Method = 'Standard deviation of SST in '+ninobox
    Ref    = 'using CDAT calculation'

    # Open file and get time dimension
    fi = cdm.open(sstfile)
    ssth = fi[varname] # Create variable handle
    # Number of months and years
    timN = ssth.shape[0]
    yearN = timN / 12

    # define ninobox
    if ninobox =='nino3':
        nbox = cdu.region.domain(latitude=(-5.,5.),longitude=(210.,270.))
    else:
        print '!!! ninobox not defined in EnsoAmpl', ninobox

    # Read SST in box and average
    sst = fi(varname, nbox)
    sstAveBox = cdu.averager(sst,axis='12',weights=cdu.area_weights(sst)).squeeze()

    # Compute anomaly wrt annual cycle and average
    sstAC = mv.average(sstAveBox[:12],axis=0)
    print sstAC
    cdu.setTimeBoundsMonthly(sstAveBox)
    sstAnom = cdu.ANNUALCYCLE.departures(sstAveBox)

    # Compute standard deviation
    sstStd = statistics.std(sstAnom)

    # Create output
    amplMetric = {'name':Name, 'value':sstStd, 'units':Units, 'method':Method, 'ref':Ref, 'nyears':yearN}

    return amplMetric
@@ -13,16 +13,36 @@
  as cdm%0A
+import numpy as npy%0A
 import c
@@ -1619,70 +1619,9 @@
     
-sstAC = mv.average(sstAveBox%5B:12%5D,axis=0)%0A    print sstAC%0A    
+#
 cdu.
@@ -1652,24 +1652,25 @@
 AveBox)%0A    
+#
 sstAnom = cd
@@ -1704,16 +1704,60 @@
 tAveBox)
+%0A    sstAnom = computeAnom(sstAveBox, yearN)
 %0A%0A    # 
@@ -1948,16 +1948,16 @@
 yearN%7D%0A%0A
-
     retu
@@ -1961,16 +1961,486 @@
 eturn amplMetric
+%0A%0Adef computeAnom(var1d, nYears):%0A    '''%0A    Compute internannual anomaly of 1D time serie as cdu.ANNUALCYCLE.departures complains about units%0A    :param var:%0A    :return:%0A    '''%0A    varAC = npy.ma.ones(%5B12%5D, dtype='float32')*0.%0A    for m in range(12):%0A        d = var1d%5Bm::12%5D # select indices for month m every 12 months%0A        varAC%5Bm%5D   = mv.average(d) # average along time axis%0A    varInter = var1d - npy.tile(varAC, nYears) # compute anomaly%0A    return varInter

Debug first commit of EnsoMetricsLib.py