[Scipy-svn] r3017 - in trunk/Lib/sandbox/timeseries: . plotlib tests

scipy-svn at scipy.org scipy-svn at scipy.org
Fri May 18 18:45:20 EDT 2007


Author: pierregm
Date: 2007-05-18 17:45:16 -0500 (Fri, 18 May 2007)
New Revision: 3017

Modified:
   trunk/Lib/sandbox/timeseries/plotlib/mpl_timeseries.py
   trunk/Lib/sandbox/timeseries/tdates.py
   trunk/Lib/sandbox/timeseries/tests/test_timeseries.py
   trunk/Lib/sandbox/timeseries/tseries.py
Log:
mpl_timeseries : add self.format_dateaxis() to tsplot
tdates         : fixed the update of the cachedinfo in DateArray.__getitem__
tdates         : added mehotd DateArray.__getslice__
tseries        : added function align_with
tseries        : forced the dates to an empty DateArray in TimeSeries.__array_finalize__
tseries        : cleaned unused variables

Modified: trunk/Lib/sandbox/timeseries/plotlib/mpl_timeseries.py
===================================================================
--- trunk/Lib/sandbox/timeseries/plotlib/mpl_timeseries.py	2007-05-18 14:16:27 UTC (rev 3016)
+++ trunk/Lib/sandbox/timeseries/plotlib/mpl_timeseries.py	2007-05-18 22:45:16 UTC (rev 3017)
@@ -719,6 +719,7 @@
         parms = self._check_plot_params(*parms)
         self.legendlabels.append(kwargs.get('label',None))
         Subplot.plot(self, *parms,**kwargs)
+        self.format_dateaxis()
     #............................................
     def format_dateaxis(self,maj_spacing=None, min_spacing=None,
                         strformat="%Y", rotate=True):

Modified: trunk/Lib/sandbox/timeseries/tdates.py
===================================================================
--- trunk/Lib/sandbox/timeseries/tdates.py	2007-05-18 14:16:27 UTC (rev 3016)
+++ trunk/Lib/sandbox/timeseries/tdates.py	2007-05-18 22:45:16 UTC (rev 3017)
@@ -213,8 +213,10 @@
         return
 
     def __getitem__(self, indx):
+        reset_full = True
         if isinstance(indx, Date):
             indx = self.find_dates(indx)
+            reset_full = False
         elif numeric.asarray(indx).dtype.kind == 'O':
             try:
                 indx = self.find_dates(indx)
@@ -231,12 +233,27 @@
             return Date(self.freq, value=r.item())
         else:
             if hasattr(r, '_cachedinfo'):
-                r._cachedinfo.update(dict(steps=None, full=None, hasdups=None))
-                for attr in ('tostr','toobj','toord'):
-                    if r._cachedinfo[attr] is not None:
-                        r._cachedinfo[attr] = r._cachedinfo[attr][indx]
+                _cache = r._cachedinfo
+                _cache.update(dict([(k,_cache[k][indx])
+                                    for k in ('toobj', 'tostr', 'toord')
+                                    if _cache[k] is not None]))
+                _cache['steps'] = None
+            if reset_full:
+                _cache['full'] = None
+                _cache['hasdups'] = None
+                
             return r
 
+    def __getslice__(self, i, j):
+        r = ndarray.__getslice__(self, i, j)
+        if hasattr(r, '_cachedinfo'):
+            _cache = r._cachedinfo
+            _cache.update(dict([(k,_cache[k][i:j])
+                                for k in ('toobj', 'tostr', 'toord')
+                                if _cache[k] is not None]))
+            _cache['steps'] = None
+        return r
+
     def __repr__(self):
         return ndarray.__repr__(self)[:-1] + \
                ",\n          freq='%s')" % self.freqstr
@@ -676,7 +693,6 @@
         hodie = today('D')
         D = DateArray(today('D'))
         assert_equal(D.freq, 6000)
-
     if 0:
         freqs = [x[0] for x in corelib.freq_dict.values() if x[0] != 'U']
         print freqs
@@ -684,18 +700,20 @@
             print f
             today = thisday(f)
             assert(Date(freq=f, value=today.value) == today)
-
-    if 1:
+    if 0:
         D = date_array(freq='U', start_date=Date('U',1), length=10)
-
-    if 1:
+    if 0:
         dlist = ['2007-01-%02i' % i for i in (1,2,4,5,7,8,10,11,13)]
-
-
         ords = numpy.fromiter((DateTimeFromString(s).toordinal() for s in dlist),
                                float_)
-
-    if 1:
+    if 0:
         "Tests the automatic sorting of dates."
         D = date_array_fromlist(dlist=['2006-01','2005-01','2004-01'],freq='M')
         assert_equal(D.view(ndarray), [24037, 24049, 24061])
+
+    if 1:
+        dlist = ['2007-%02i' % i for i in range(1,5)+range(7,13)]
+        mdates = date_array_fromlist(dlist, 'M')
+        
+        print mdates.tostr()
+        
\ No newline at end of file

Modified: trunk/Lib/sandbox/timeseries/tests/test_timeseries.py
===================================================================
--- trunk/Lib/sandbox/timeseries/tests/test_timeseries.py	2007-05-18 14:16:27 UTC (rev 3016)
+++ trunk/Lib/sandbox/timeseries/tests/test_timeseries.py	2007-05-18 22:45:16 UTC (rev 3017)
@@ -346,11 +346,23 @@
                                    end_date=Date('D', string='2007-01-31'))
         assert_equal(dseries.size, 26)
         assert_equal(dseries._mask, N.r_[series._mask[5:], [1]*16])
+    #
+    def test_alignseries(self):
+        "Tests align_series & align_with"
+        (series, data, dates) = self.d
         #
         empty_series = time_series([], freq='d')
         a, b = align_series(series, empty_series)
         assert_equal(a.start_date, b.start_date)
         assert_equal(a.end_date, b.end_date)
+        #
+        aseries = time_series(data, dates+10)
+        bseries = time_series(data, dates-10)
+        (a, b) = align_with(series, aseries, bseries)
+        assert_equal(a._dates, series._dates)
+        assert_equal(b._dates, series._dates)
+        assert_equal(a[-5:], series[:5])
+        assert_equal(b[:5], series[-5:])
     #
     def test_tshift(self):
         "Test tshift function"

Modified: trunk/Lib/sandbox/timeseries/tseries.py
===================================================================
--- trunk/Lib/sandbox/timeseries/tseries.py	2007-05-18 14:16:27 UTC (rev 3016)
+++ trunk/Lib/sandbox/timeseries/tseries.py	2007-05-18 22:45:16 UTC (rev 3017)
@@ -366,7 +366,7 @@
     #............................................
     def __array_finalize__(self,obj):
         MaskedArray.__array_finalize__(self, obj)
-        self._dates = getattr(obj, '_dates', [])
+        self._dates = getattr(obj, '_dates', DateArray([]))
         self.observed = getattr(obj, 'observed', None)
         return
     #..................................
@@ -428,7 +428,6 @@
         (sindx, dindx) = self.__checkindex(indx)
         newdata = numeric.array(self._series[sindx], copy=False, subok=True)
         newdate = self._dates[dindx]
-        m = self._mask
         singlepoint = (len(numeric.shape(newdate))==0)
         if singlepoint:
             newdate = DateArray(newdate)
@@ -475,8 +474,7 @@
         """
         if self is masked:
             raise MAError, 'Cannot alter the masked element.'
-        (sindx, dindx) = self.__checkindex(indx)
-        #....
+        (sindx, _) = self.__checkindex(indx)
         super(TimeSeries, self).__setitem__(sindx, value)
     #........................
     def __getslice__(self, i, j):
@@ -1163,7 +1161,7 @@
         newseries[start_date:end_date] = a[start_date:end_date]
     newseries.copy_attributes(a)
     return newseries
-#....................................................................
+#.....................................................
 def align_series(*series, **kwargs):
     """Aligns several TimeSeries, so that their starting and ending dates match.
     Series are resized and filled with mased values accordingly.
@@ -1196,6 +1194,19 @@
 
     return [adjust_endpoints(x, start_date, end_date) for x in series]
 aligned = align_series
+
+#.....................................................
+def align_with(*series):
+    """Aligns several TimeSeries to the first of the list, so that their 
+    starting and ending dates match.
+    Series are resized and filled with mased values accordingly.
+    """
+    if len(series) < 2:
+        return series
+    dates = series[0]._dates[[0,-1]]
+    return [adjust_endpoints(x, dates[0], dates[-1]) for x in series[1:]]
+    
+    
 #....................................................................
 def _convert1d(series, freq, func='auto', position='END'):
     """Converts a series to a frequency. Private function called by convert
@@ -1538,56 +1549,17 @@
 ################################################################################
 if __name__ == '__main__':
     from maskedarray.testutils import assert_equal, assert_array_equal
-    import numpy as N
-
     if 1:
-        dlist = ['2007-01-%02i' % i for i in range(1,11)]
+        dlist = ['2007-01-%02i' % i for i in range(1,16)]
         dates = date_array_fromlist(dlist)
-        data = masked_array(numeric.arange(10), mask=[1,0,0,0,0]*2, dtype=float_)
+        data = masked_array(numeric.arange(15), mask=[1,0,0,0,0]*3)
+        series = time_series(data, dlist)
+        #
+        aseries = time_series(data, dates+10)
+        bseries = time_series(data, dates-10)
+        (a, b) = align_with(series, aseries, bseries)
+        assert_equal(a._dates, series._dates)
+        assert_equal(b._dates, series._dates)
+        assert_equal(a[-5:], series[:5])
+        assert_equal(b[:5], series[-5:])
 
-    if 0:
-        ser1d = time_series(data, dlist)
-
-        serfolded = ser1d.reshape((5,2))
-        assert_equal(serfolded._dates.shape, (5,2))
-        assert_equal(serfolded[0], time_series([0,1],mask=[1,0],
-                                               start_date=dates[0]))
-        assert_equal(serfolded[:,0],
-                     time_series(ser1d[::2], dates=dates[::2]))
-        sertrans = serfolded.transpose()
-        assert_equal(sertrans.shape, (2,5))
-
-    if 1:
-        data = dates
-        series = time_series(data, dates)
-        assert(isinstance(series, TimeSeries))
-        assert_equal(series._dates, dates)
-        assert_equal(series._data, data)
-        assert_equal(series.freqstr, 'D')
-
-        series[5] = MA.masked
-
-        # ensure that series can be represented by a string after masking a value
-        # (there was a bug before that prevented this from working when using a
-        # DateArray for the data)
-        strrep = str(series)
-    
-    if 0:
-        series = time_series(numpy.arange(1,501),
-                             start_date=Date('D', string='2007-01-01'))
-        mseries = convert(series, 'M')
-        aseries = convert(mseries, 'A')
-        (freq, func, position) = ('A', None, 'END')
-        
-        tmp = mseries[:,0].convert('A')
-        aseries = MA.concatenate([_convert1d(m,'A')._series for m in mseries.split()],
-                                 axis=-1).view(type(series))
-        aseries._dates = tmp._dates                                 
-        shp = aseries.shape
-        aseries.shape = (shp[0], shp[-1]//tmp.shape[-1], tmp.shape[-1])
-        numpy.swapaxes(aseries,1,2)
-    
-    if 1:
-        series = time_series(N.arange(124).reshape(62,2), 
-                             start_date=Date(freq='d', year=2005, month=7, day=1))
-        assert_equal(series.convert('M',sum), [[930,961],[2852,2883]])
\ No newline at end of file




More information about the Scipy-svn mailing list