[Scipy-svn] r3717 - trunk/scipy/sandbox/timeseries

scipy-svn at scipy.org scipy-svn at scipy.org
Tue Dec 25 12:09:39 EST 2007


Author: pierregm
Date: 2007-12-25 11:09:35 -0600 (Tue, 25 Dec 2007)
New Revision: 3717

Modified:
   trunk/scipy/sandbox/timeseries/plotlib.py
   trunk/scipy/sandbox/timeseries/tseries.py
Log:
tofile()                 : fixed. Now uses the same arguments as scipy.io.write_array
TimeSeries._update_from  : Fixed dates update
plotlib                  : ensures that TimeSeriesPlot.tsplot returns the plotted elements

Modified: trunk/scipy/sandbox/timeseries/plotlib.py
===================================================================
--- trunk/scipy/sandbox/timeseries/plotlib.py	2007-12-25 04:34:09 UTC (rev 3716)
+++ trunk/scipy/sandbox/timeseries/plotlib.py	2007-12-25 17:09:35 UTC (rev 3717)
@@ -39,6 +39,7 @@
 
 import warnings
 
+
 #####---------------------------------------------------------------------------
 #---- --- Matplotlib extensions ---
 #####---------------------------------------------------------------------------
@@ -197,6 +198,7 @@
                        dtype=[('val',int_),('maj',bool_),('min',bool_),('fmt','|S10')])
     info['val'] = numpy.arange(vmin, vmax+1)
     info['fmt'] = ''
+    info['maj'][[0,-1]] = True
 
     def first_label(label_flags):
         if label_flags[0] == 0: return label_flags[1]
@@ -240,18 +242,14 @@
                     info['fmt'][first_label(month_start)] = '\n\n%b\n%Y'
     # Case 3. Less than 14 months ...............
     elif span <= 1.15 * periodsperyear:
-        d_minus_1 = dates_-1
-
-        month_diff = numpy.abs(dates_.month - d_minus_1.month)
-        week_diff = numpy.abs(dates_.week - d_minus_1.week)
-        minor_idx = (month_diff + week_diff).nonzero()[0]
-
-        info['maj'][month_diff != 0] = True
-        info['min'][minor_idx] = True
+        year_start = period_break(dates_,'year')
+        month_start = period_break(dates_,'month')
+        week_start = period_break(dates_,'week')
+        info['maj'][month_start] = True
+        info['min'][week_start] = True     
+        info['min'][year_start] = False  
+        info['min'][month_start] = False  
         if asformatter:
-            year_start = period_break(dates_,'year')
-            month_start = period_break(dates_,'month')
-
             info['fmt'][month_start] = '%b'
             info['fmt'][year_start] = '%b\n%Y'
             if not has_level_label(year_start):
@@ -259,11 +257,11 @@
     # Case 4. Less than 2.5 years ...............
     elif span <= 2.5 * periodsperyear:
         year_start = period_break(dates_,'year')
-        month_start = period_break(dates_, 'quarter')
-        info['maj'][year_start] = True
+        quarter_start = period_break(dates_, 'quarter')
+        month_start = period_break(dates_, 'month')
+        info['maj'][quarter_start] = True
         info['min'][month_start] = True
         if asformatter:
-            quarter_start = period_break(dates_, 'quarter')
             info['fmt'][quarter_start] = '%b'
             info['fmt'][year_start] = '%b\n%Y'
     # Case 4. Less than 4 years .................
@@ -272,6 +270,7 @@
         month_start = period_break(dates_, 'month')
         info['maj'][year_start] = True
         info['min'][month_start] = True
+        info['min'][year_start] = False
         if asformatter:
             month_break = dates_[month_start].month
             jan_or_jul = month_start[(month_break == 1) | (month_break == 7)]
@@ -283,6 +282,7 @@
         quarter_start = period_break(dates_, 'quarter')
         info['maj'][year_start] = True
         info['min'][quarter_start] = True
+        info['min'][year_start] = False
         if asformatter:
             info['fmt'][year_start] = '%Y'
     # Case 6. More than 12 years ................
@@ -332,6 +332,7 @@
     #........................
     elif span <= 2.5 * periodsperyear:
         info['maj'][year_start] = True
+        info['fmt'][quarter_start] = True
         info['min'] = True
         if asformatter:
             quarter_start = (dates_ % 3 == 1).nonzero()
@@ -509,7 +510,7 @@
         self.format = None
         self.freq = freq
         self.locs = []
-        self.formatdict = {}
+        self.formatdict = None
         self.isminor = minor_locator
         self.isdynamic = dynamic_mode
         self.offset = 0
@@ -536,9 +537,10 @@
 
     def _set_default_format(self, vmin, vmax):
         "Returns the default ticks spacing."
+        print "CALLING FINDER",vmin,vmax
         info = self.finder(vmin, vmax, self.freq, True)
         if self.isminor:
-            format = numpy.compress(info['min'] & numpy.logical_not(info['maj']),
+            format = numpy.compress(info['min'] & numpy.logical_not(info['maj']), 
                                     info)
         else:
             format = numpy.compress(info['maj'], info)
@@ -576,7 +578,8 @@
 
         """
         # Retrieve the series ...................
-        _series = kwargs.pop('series',None)
+        _series = kwargs.pop('series',
+                             getattr(fig,'series',None))
         Subplot.__init__(self,fig,*args,**kwargs)
 #        # Force fig to be defined .....
 #        if fig is None:

Modified: trunk/scipy/sandbox/timeseries/tseries.py
===================================================================
--- trunk/scipy/sandbox/timeseries/tseries.py	2007-12-25 04:34:09 UTC (rev 3716)
+++ trunk/scipy/sandbox/timeseries/tseries.py	2007-12-25 17:09:35 UTC (rev 3717)
@@ -29,6 +29,8 @@
 from maskedarray import MaskedArray, MAError, masked, nomask, \
     filled, getmask, getmaskarray, hsplit, make_mask_none, mask_or, make_mask, \
     masked_array
+    
+import scipy.io    
 
 import const as _c
 
@@ -399,15 +401,24 @@
         return _data
     #.........................................................................
     def __array_finalize__(self,obj):
+        self._dates = getattr(obj, '_dates', DateArray([]))
         MaskedArray.__array_finalize__(self, obj)
-        self._dates = getattr(obj, '_dates', DateArray([]))
         return
     #.........................................................................
-    def __array_wrap__(self, obj, context=None):
-        result = super(TimeSeries, self).__array_wrap__(obj, context)
-        result._dates = self._dates
-        return result
+#    def __array_wrap__(self, obj, context=None):
+#        result = super(TimeSeries, self).__array_wrap__(obj, context)
+#        result._dates = self._dates
+#        return result
     #.........................................................................
+    def _update_from(self, obj):
+        super(TimeSeries, self)._update_from(obj)
+        newdates = getattr(obj, '_dates', DateArray([]))
+        if self._dates.size == 0:
+            self._dates = newdates
+        elif newdates.size > 0:
+            _timeseriescompat(self,obj)
+        return    
+    #.........................................................................
     def _get_series(self):
         "Returns the series as a regular masked array."
         if self._mask.ndim == 0 and self._mask:
@@ -895,25 +906,54 @@
 ##### ---------------------------------------------------------------------------
 #---- ... Additional methods ...
 ##### ---------------------------------------------------------------------------
-def tofile(self, output, sep='\t', format_dates=None):
-    """Writes the TimeSeries to a file.
+def tofile(self, fileobject, format=None,
+           separator=" ", linesep='\n', precision=5,
+           suppress_small=False, keep_open=False): 
+    """Writes the TimeSeries to a file. The series should be 2D at most
 
-:Parameters:
-    - `output` (String) : Name or handle of the output file.
-    - `sep` (String) : Column separator *['\t']*.
-    - `format` (String) : Data format *['%s']*.
-    """
-    if not hasattr(output, 'writeline'):
-        ofile = open(output,'w')
+*Parameters*:
+    series : {TimeSeries}
+        The array to write.
+    fileobject:
+        An open file object or a string to a valid filename.
+    format : {string}
+        Format string for the date. If None, uses the default date format.
+    separator : {string}
+        Separator to write between elements of the array.
+    linesep : {string}
+        Separator to write between rows of array.
+    precision : {integer}
+        Number of digits after the decimal place to write.
+    suppress_small : {boolean}
+        Whether on-zero to round small numbers down to 0.0
+    keep_open : {boolean} 
+        Whether to close the file or to return the open file.
+    
+*Returns*:
+    file : {file object}
+        The open file (if keep_open is non-zero)
+    """   
+    (_dates, _data) = (self._dates, self._series)
+    optpars = dict(separator=separator,linesep=linesep,precision=precision,
+                   suppress_small=suppress_small,keep_open=keep_open)
+    if _dates.size == _data.size:
+        # 1D version
+        tmpfiller = maskedarray.empty((_dates.size,2), dtype=numpy.object_)
+        _data = _data.reshape(-1)
+        tmpfiller[:,1:] = maskedarray.atleast_2d(_data).T
     else:
-        ofile = output
-    if format_dates is None:
-        format_dates = self.dates[0].default_fmtstr()
-    oformat = "%%s%s%s" % (sep,format_dates)
-    for (_dates,_data) in numpy.broadcast(self._dates.ravel().asstrings(),
-                                          filled(self)):
-        ofile.write('%s\n' % sep.join([oformat % (_dates, _data) ]))
-    ofile.close()
+        sshape = list(_data.shape)
+        sshape[-1] += 1
+        tmpfiller = maskedarray.empty(sshape, dtype=numpy.object_)
+        tmpfiller[:,1:] = _data
+    #
+    if format is None:
+        tmpfiller[:,0] = _dates.ravel().tostring()
+    else:
+        tmpfiller[:,0] = [_.strftime(format) for _ in _dates.ravel()]
+    return scipy.io.write_array(fileobject, tmpfiller, **optpars)
+    
+
 TimeSeries.tofile = tofile
 
 #............................................




More information about the Scipy-svn mailing list