Ejemplo n.º 1
0
def zeros(var, ref='mean', mean=None, getref=True, **kwargs):
    """Get the zeros of a tidal signal

    :Returns: A :mod:`cdms2` variable of signs (-1,1) with a time axis

    :Usage:

    >>> tidal_zeros = zeros(sea_level,ref='demerliac')
    >>> print tidal_zeros[0:1]
    >>> print tidal_zeros[0:1].getTime().asComponentTime()
    """
    # Get anomaly
    ref = kwargs.pop('reference', ref)
    vara, varref = _get_anomaly_(var, ref=ref, mean=mean)
    taxis = vara.getTime()
    vara = vara.filled()
    longref = hasattr(varref, '__len__')

    # Find indices
    sign = N.sign(vara)
    izeros = N.arange(len(vara) - 1).compress(sign[:-1] != sign[1:])

    # Interpolate
    units = taxis.units
    times = taxis.getValue()
    zeros = N.zeros((len(izeros), ))
    if getref:
        ret = MV2.zeros(len(zeros), id='zeros')
        if not longref:
            ret[:] = varref
    for i, i0 in enumerate(izeros):
        dv = vara[i0 + 1] - vara[i0]
        zeros[i] = times[i0] * vara[i0 + 1] / dv - times[i0 +
                                                         1] * vara[i0] / dv
        if getref and longref:
            dt = times[i0 + 1] - times[i0]
            ret[i] = var_ref[i0] * vara[i0 + 1] / dv - var_ref[
                i0 + 1] * vara[i0] / dv

    # Format
    if not getref:
        ret = MV2.array(sign[izeros], id='zeros')
        ret.units = '1 up and -1 down'
    else:
        cp_atts(var, ret)
    ret.long_name = 'Zeros'
    zeros = create_time(zeros, units)
    ret.setAxis(0, zeros)
    return ret
Ejemplo n.º 2
0
def zeros(var, ref='mean',mean=None, getref=True, **kwargs):
    """Get the zeros of a tidal signal

    :Returns: A :mod:`cdms2` variable of signs (-1,1) with a time axis

    :Usage:

    >>> tidal_zeros = zeros(sea_level,ref='demerliac')
    >>> print tidal_zeros[0:1]
    >>> print tidal_zeros[0:1].getTime().asComponentTime()
    """
    # Get anomaly
    ref = kwargs.pop('reference', ref)
    vara, varref = _get_anomaly_(var, ref=ref,mean=mean)
    taxis = vara.getTime()
    vara = vara.filled()
    longref = hasattr(varref, '__len__')

    # Find indices
    sign = N.sign(vara)
    izeros =  N.arange(len(vara)-1).compress(sign[:-1]!=sign[1:])

    # Interpolate
    units = taxis.units
    times = taxis.getValue()
    zeros = N.zeros((len(izeros), ))
    if getref:
        ret = MV2.zeros(len(zeros), id='zeros')
        if not longref:
            ret[:] = varref
    for i, i0 in enumerate(izeros):
        dv = vara[i0+1]-vara[i0]
        zeros[i] = times[i0]*vara[i0+1]/dv - times[i0+1]*vara[i0]/dv
        if getref and longref:
            dt = times[i0+1]-times[i0]
            ret[i] = var_ref[i0]*vara[i0+1]/dv - var_ref[i0+1]*vara[i0]/dv

    # Format
    if not getref:
        ret = MV2.array(sign[izeros], id='zeros')
        ret.units = '1 up and -1 down'
    else:
        cp_atts(var, ret)
    ret.long_name = 'Zeros'
    zeros = create_time(zeros, units)
    ret.setAxis(0, zeros)
    return ret
Ejemplo n.º 3
0
    def load(self, restart_file=None, iterindex=None, nowtime=None):
        """Load the current instance from a netcdf file

        :Params:

            - **restart_file**, optional: Netcdf restart file.
            - **iterindex**, optional: If given, the restart file is not loaded if
              ``iterindex`` is greater or equal to the file's ``iterindex`` attribute.
            - **nowtime**, optional: If given, the restart file is not loaded if
              ``nowtime`` is greater or equal to the file's ``lasttime`` attribute.
        """

        # File
        if restart_file is None:
            restart_file = self.restart_file
        if restart_file is None:
            restart_file = self.default_restart_file
        self.restart_file = restart_file
        f = cdms2.open(restart_file)

        # Config
        # - check status
        if iterindex is not None:
            self.iterindex = iterindex
        if hasattr(self, 'iterindex') and f.iterindex<=self.iterindex:
            return -1
        if nowtime is not None:
            self.lasttime = comptime(nowtime)
        if (hasattr(self, 'lasttime') and f.withtime>0 and self.lasttime
                and reltime(f.lasttime, 'hours since 2000').value <=
                reltime(self.lasttime, 'hours since 2000').value):
            return -1
        # - what was initially asked and some more
        for sname in self.all_stats + ('sum', 'sqr', 'prod', 'stats'):
            for st in 'st':
                if not hasattr(f, st+sname): continue
                value = getattr(f, st+sname)
                setattr(self, st+sname, bool(value))
        # - current status
        self.iterindex = int(f.iterindex)
        self.nitems = int(f.nitems)
        if f.withtime==-1:
           self.withtime  = None
        else:
            self.withtime  = bool(f.withtime)
        if f.withtime:
            self.lasttime = cdtime.s2c(f.lasttime)
        if N.isscalar(f.bin_edges):
            self.bins = None
        else:
            self.bins = N.asarray(f.bin_edges)
            self.nbins = self.bins.shape[0]-1
            self._baxis = f.getAxis('hbin').clone()
        if self.nitems==0: # Still no data
            f.close()
            return 0
        # - already had some data
        self.dual = bool(f.dual)
        self.ns = int(f.ns)
        self.nt = int(f.nt)
        self._nts = f.nts.tolist()
        self.tstats = bool(f.tstats)
        self.sstats = bool(f.sstats)
        if not self.withtime:
            self._stimes = None

        # Spatial statistics
        if self.sstats:

            # Time axes
            if self.withtime:
                self._stimes = tuple([[] for i in xrange(self.nitems)])
                for i, tt in enumerate(self._stimes):
                    taxis = f.getAxis('t'+str(i))
                    tvalues = self._aslist_(taxis[:])
                    oldid = taxis.stataccum_oldid
                    for tvals in tvalues:
                        tx = create_time(tvals, taxis.units, id=oldid)
                        cp_atts(taxis, tx, id=False, exclude=[oldid])
                        self._stimes[i].append(tx)

            # Count
            self._scount = self._load_array_(f, id='scount')

            # Other stats
            self._sstats = {}
            for key in self.single_stats:
                if not self.dual: # single var
                    vid = 's' + key
                    if vid not in f.variables:
                        continue
                    self._sstats[key] = self._load_array_(f, vid),
                else: # two vars
                    for i in xrange(self.nitems):
                        vid = 's%s%s'%(key, str(i))
                        if vid not in f.variables:
                            break
                        self._sstats.setdefault(key, ())
                        self._sstats[key] += self._load_array_(f, vid),
            for key in self.dual_stats:
                vid = 's%s'%key
                if vid in f.variables:
                    self._sstats[key] = self._load_array_(f, vid)

        # Temporal statistics
        if self.tstats:

            # Count
            self._tcount = self._load_array_(f, 'tcount')

            # Other stats
            for key in self._dual_accums+self._single_accums:
                tid = 't'+key
                if not getattr(self, tid): continue
                if key in self._dual_accums:
                    value = self._load_array_(f, tid)
                    setattr(self, '_'+tid, value)
                else:
                    value = ()
                    for i in xrange(self.nitems):
                        value += self._load_array_(f, tid+str(i)),
                    setattr(self, '_'+tid, value)

            # Templates
            # - base arrays
            self._tbase = N.zeros(self.ns)
            if self.thist:
                self._thbase = N.zeros((self.nbins, self.ns), 'l')
            # - cdat templates
            self._ttemplates = ()
            self._thtemplates = None
            if self.thist:
                self._thtemplates = ()
            for i in xrange(self.nitems):
                prefix = 'var%i_'%i
                for vname in f.variables:
                    if vname.startswith(prefix) and vname != prefix+'atts': break
                ttpl = f(vname)
                _rm_id_prefix_(ttpl, 'var%i_'%i, exc=self._baxis)
                self._ttemplates += ttpl,
                if self.thist:
                    self._thtemplates += self._template_t2ht_(ttpl),

        # Attributes
        self._atts = ()
        for ivar in xrange(self.nitems):
            attrs = f['var%i_atts'%ivar].attributes.copy()
            attrs['id'] = attrs['stataccum_id']
            del attrs['stataccum_id']
            self._atts += attrs,

        f.close()
        return self.iterindex
Ejemplo n.º 4
0
 def _template_t2ht_(self, tpl):
     htpl = MV2.resize(tpl.astype('l'), (self.nbins,)+tpl.shape)
     htpl.setAxisList([self._baxis]+tpl.getAxisList())
     set_grid(htpl, get_grid(tpl))
     cp_atts(tpl, htpl)
     return htpl
Ejemplo n.º 5
0
    def load(self, restart_file=None, iterindex=None, nowtime=None):
        """Load the current instance from a netcdf file

        :Params:

            - **restart_file**, optional: Netcdf restart file.
            - **iterindex**, optional: If given, the restart file is not loaded if
              ``iterindex`` is greater or equal to the file's ``iterindex`` attribute.
            - **nowtime**, optional: If given, the restart file is not loaded if
              ``nowtime`` is greater or equal to the file's ``lasttime`` attribute.
        """

        # File
        if restart_file is None:
            restart_file = self.restart_file
        if restart_file is None:
            restart_file = self.default_restart_file
        self.restart_file = restart_file
        f = cdms2.open(restart_file)

        # Config
        # - check status
        if iterindex is not None:
            self.iterindex = iterindex
        if hasattr(self, 'iterindex') and f.iterindex<=self.iterindex:
            return -1
        if nowtime is not None:
            self.lasttime = comptime(nowtime)
        if (hasattr(self, 'lasttime') and f.withtime>0 and self.lasttime
                and comptime(f.lasttime)<=comptime(self.lasttime)):
            return -1
        # - what was initially asked and some more
        for sname in self.all_stats + ('sum', 'sqr', 'prod', 'stats'):
            for st in 'st':
                if not hasattr(f, st+sname): continue
                value = getattr(f, st+sname)
                setattr(self, st+sname, bool(value))
        # - current status
        self.iterindex = int(f.iterindex)
        self.nitems = int(f.nitems)
        if f.withtime==-1:
           self.withtime  = None
        else:
            self.withtime  = bool(f.withtime)
        if f.withtime:
            self.lasttime = cdtime.s2c(f.lasttime)
        if N.isscalar(f.bin_edges):
            self.bins = None
        else:
            self.bins = N.asarray(f.bin_edges)
            self.nbins = self.bins.shape[0]-1
            self._baxis = f.getAxis('hbin').clone()
        if self.nitems==0: # Still no data
            f.close()
            return 0
        # - already had some data
        self.dual = bool(f.dual)
        self.ns = int(f.ns)
        self.nt = int(f.nt)
        self._nts = f.nts.tolist()
        self.tstats = bool(f.tstats)
        self.sstats = bool(f.sstats)
        if not self.withtime:
            self._stimes = None

        # Spatial statistics
        if self.sstats:

            # Time axes
            if self.withtime:
                self._stimes = tuple([[] for i in xrange(self.nitems)])
                for i, tt in enumerate(self._stimes):
                    taxis = f.getAxis('t'+str(i))
                    tvalues = self._aslist_(taxis[:])
                    oldid = taxis.stataccum_oldid
                    for tvals in tvalues:
                        tx = create_time(tvals, taxis.units, id=oldid)
                        cp_atts(taxis, tx, id=False, exclude=[oldid])
                        self._stimes[i].append(tx)

            # Count
            self._scount = self._load_array_(f, id='scount')

            # Other stats
            self._sstats = {}
            for key in self.single_stats:
                self._sstats[key] = ()
                for i in xrange(self.nitems):
                    self._sstats[key] += self._load_array_(f, 's%s%s'%(key, str(i))),
            for key in self.dual_stats:
                 self._sstats[key] = self._load_array_(f, 's%s'%key)

        # Temporal statistics
        if self.tstats:

            # Count
            self._tcount = self._load_array_(f, 'tcount')

            # Other stats
            for key in self._dual_accums+self._single_accums:
                tid = 't'+key
                if not getattr(self, tid): continue
                if key in self._dual_accums:
                    value = self._load_array_(f, tid)
                    setattr(self, '_'+tid, value)
                else:
                    value = ()
                    for i in xrange(self.nitems):
                        value += self._load_array_(f, tid+str(i)),
                    setattr(self, '_'+tid, value)

            # Templates
            # - base arrays
            self._tbase = N.zeros(self.ns)
            if self.thist:
                self._thbase = N.zeros((self.nbins, self.ns), 'l')
            # - cdat templates
            self._ttemplates = ()
            if self.thist:
                self._thtemplates = ()
            for i in xrange(self.nitems):
                prefix = 'var%i_'%i
                for vname in f.variables:
                    if vname.startswith(prefix): break
                ttpl = f(vname)
                _rm_id_prefix_(ttpl, 'var%i_'%i, exc=self._baxis)
                self._ttemplates += ttpl,
                if self.thist:
                    self._thtemplates += self._template_t2ht_(ttpl),

        # Attributes
        self._atts = ()
        for ivar in xrange(self.nitems):
            attrs = f['var%i_atts'%ivar].attributes.copy()
            attrs['id'] = attrs['stataccum_id']
            del attrs['stataccum_id']
            self._atts += attrs,

        f.close()
        return self.iterindex
Ejemplo n.º 6
0
 def _template_t2ht_(self, tpl):
     htpl = MV2.resize(tpl.astype('l'), (self.nbins,)+tpl.shape)
     htpl.setAxisList([self._baxis]+tpl.getAxisList())
     set_grid(htpl, get_grid(tpl))
     cp_atts(tpl, htpl)
     return htpl