Skip to content

Commit 5b301c4

Browse files
committed
Merged revisions 4735-4757 via svnmerge from
http://matplotlib.svn.sf.net/svnroot/matplotlib/trunk/matplotlib ........ r4745 | jdh2358 | 2007-12-15 16:33:38 -0500 (Sat, 15 Dec 2007) | 1 line changed %g to %r for rec2csv ........ r4747 | astraw | 2007-12-16 14:28:46 -0500 (Sun, 16 Dec 2007) | 1 line Add test for rec2csv and csv2rec roundtrip not losing precision. ........ r4748 | astraw | 2007-12-16 15:53:35 -0500 (Sun, 16 Dec 2007) | 1 line rec2csv does not close filehandles passed in open ........ r4749 | astraw | 2007-12-16 18:19:59 -0500 (Sun, 16 Dec 2007) | 1 line fix csv2rec roundtrip for funky strings, too ........ r4755 | jdh2358 | 2007-12-16 23:37:38 -0500 (Sun, 16 Dec 2007) | 1 line mods to support dates in csv2rec and friends ........ svn path=/branches/transforms/; revision=4758
2 parents bdbf7e2 + c3789d7 commit 5b301c4

File tree

5 files changed

+103
-22
lines changed

5 files changed

+103
-22
lines changed

CHANGELOG

+3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
2007-12-16 rec2csv saves doubles without losing precision. Also, it
2+
does not close filehandles passed in open. - JDH,ADS
3+
14
2007-12-13 Moved rec2gtk to matplotlib.toolkits.gtktools and rec2excel
25
to matplotlib.toolkits.exceltools - JDH
36

lib/matplotlib/cbook.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ def is_numlike(obj):
225225
except TypeError: return False
226226
else: return True
227227

228-
def to_filehandle(fname, flag='r'):
228+
def to_filehandle(fname, flag='r', return_opened=False):
229229
"""
230230
fname can be a filename or a file handle. Support for gzipped
231231
files is automatic, if the filename ends in .gz. flag is a
@@ -237,10 +237,14 @@ def to_filehandle(fname, flag='r'):
237237
fh = gzip.open(fname, flag)
238238
else:
239239
fh = file(fname, flag)
240+
opened = True
240241
elif hasattr(fname, 'seek'):
241242
fh = fname
243+
opened = False
242244
else:
243245
raise ValueError('fname must be a string or file handle')
246+
if return_opened:
247+
return fh, opened
244248
return fh
245249

246250
def flatten(seq, scalarp=is_scalar):

lib/matplotlib/mlab.py

+21-6
Original file line numberDiff line numberDiff line change
@@ -2129,16 +2129,26 @@ def process_skiprows(reader):
21292129

21302130
process_skiprows(reader)
21312131

2132+
dateparser = dateutil.parser.parse
21322133

21332134
def myfloat(x):
21342135
if x==missing:
21352136
return npy.nan
21362137
else:
21372138
return float(x)
21382139

2140+
def mydate(x):
2141+
# try and return a date object
2142+
d = dateparser(x)
2143+
2144+
if d.hour>0 or d.minute>0 or d.second>0:
2145+
raise ValueError('not a date')
2146+
return d.date()
2147+
2148+
21392149
def get_func(item, func):
21402150
# promote functions in this order
2141-
funcmap = {int:myfloat, myfloat:dateutil.parser.parse, dateutil.parser.parse:str}
2151+
funcmap = {int:myfloat, myfloat:mydate, mydate:dateparser, dateparser:str}
21422152
try: func(item)
21432153
except:
21442154
if func==str:
@@ -2238,8 +2248,12 @@ def toval(self, x):
22382248

22392249
class FormatString(FormatObj):
22402250
def tostr(self, x):
2241-
return '"%s"'%self.toval(x)
2251+
val = repr(x)
2252+
return val[1:-1]
22422253

2254+
#class FormatString(FormatObj):
2255+
# def tostr(self, x):
2256+
# return '"%r"'%self.toval(x)
22432257

22442258
class FormatFormatStr(FormatObj):
22452259
def __init__(self, fmt):
@@ -2297,7 +2311,7 @@ def __init__(self, fmt='%Y-%m-%d %H:%M:%S'):
22972311
npy.float32 : FormatFloat(),
22982312
npy.float64 : FormatFloat(),
22992313
npy.object_ : FormatObj(),
2300-
npy.string_ : FormatObj(),
2314+
npy.string_ : FormatString(),
23012315
}
23022316

23032317
def get_formatd(r, formatd=None):
@@ -2317,7 +2331,7 @@ def csvformat_factory(format):
23172331
format = copy.deepcopy(format)
23182332
if isinstance(format, FormatFloat):
23192333
format.scale = 1. # override scaling for storage
2320-
format.fmt = '%g' # maximal precision
2334+
format.fmt = '%r'
23212335
return format
23222336

23232337
def rec2csv(r, fname, delimiter=',', formatd=None):
@@ -2335,13 +2349,14 @@ def rec2csv(r, fname, delimiter=',', formatd=None):
23352349
for i, name in enumerate(r.dtype.names):
23362350
funcs.append(csvformat_factory(formatd[name]).tostr)
23372351

2338-
fh = cbook.to_filehandle(fname, 'w')
2352+
fh, opened = cbook.to_filehandle(fname, 'w', return_opened=True)
23392353
writer = csv.writer(fh, delimiter=delimiter)
23402354
header = r.dtype.names
23412355
writer.writerow(header)
23422356
for row in r:
23432357
writer.writerow([func(val) for func, val in zip(funcs, row)])
2344-
fh.close()
2358+
if opened:
2359+
fh.close()
23452360

23462361

23472362

lib/matplotlib/mpl-data/matplotlib.conf.template

+15-15
Original file line numberDiff line numberDiff line change
@@ -3,32 +3,32 @@
33
# This is a sample matplotlib configuration file. It should be placed
44
# in HOME/.matplotlib/matplotlibrc (unix/linux like systems) and
55
# C:\Documents and Settings\yourname\.matplotlib (win32 systems)
6-
#
6+
#
77
# By default, the installer will overwrite the existing file in the install
88
# path, so if you want to preserve yours, please move it to your HOME dir and
99
# set the environment variable if necessary.
10-
#
10+
#
1111
# This file is best viewed in a editor which supports ini or conf mode syntax
1212
# highlighting.
13-
#
13+
#
1414
# Blank lines, or lines starting with a comment symbol, are ignored,
1515
# as are trailing comments. Other lines must have the format
16-
#
16+
#
1717
# key = val optional comment
18-
#
18+
#
1919
# val should be valid python syntax, just as you would use when setting
2020
# properties using rcParams. This should become more obvious by inspecting
2121
# the default values listed herein.
22-
#
22+
#
2323
# Colors: for the color values below, you can either use
2424
# - a matplotlib color string, such as r | k | b
2525
# - an rgb tuple, such as (1.0, 0.5, 0.0)
2626
# - a hex string, such as #ff00ff or ff00ff
2727
# - a scalar grayscale intensity such as 0.75
2828
# - a legal html color name, eg red | blue | darkslategray
29-
#
29+
#
3030
# Interactivity: see http://matplotlib.sourceforge.net/interactive.html.
31-
#
31+
#
3232
# ### CONFIGURATION BEGINS HERE ###
3333

3434
# a value of type 'str'
@@ -42,7 +42,7 @@ numerix = 'numpy'
4242
# 'Africa/Abidjan' or 'Africa/Accra' or 'Africa/Addis_Ababa' or
4343
# 'Africa/Algiers' or 'Africa/Asmara' or 'Africa/Asmera' or 'Africa/Bamako' or
4444
# 'Africa/Bangui' or 'Africa/Banjul' or 'Africa/Bissau' or 'Africa/Blantyre'
45-
# <...snipped 156 lines...>
45+
# <...snipped 156 lines...>
4646
# 'US/Michigan' or 'US/Mountain' or 'US/Pacific' or 'US/Pacific-New' or
4747
# 'US/Samoa' or 'UTC' or 'Universal' or 'W-SU' or 'WET' or 'Zulu' or
4848
# 'posixrules'
@@ -108,10 +108,10 @@ units = False
108108
[[ps]]
109109
# 3 or 42
110110
fonttype = 3
111-
# 'auto' or 'letter' or 'legal' or 'ledger' or 'A0' or 'A1' or 'A2' or
112-
# 'A3' or 'A4' or 'A5' or 'A6' or 'A7' or 'A8' or 'A9' or 'A10' or
113-
# 'B0' or 'B1' or 'B2' or 'B3' or 'B4' or 'B5' or 'B6' or 'B7' or 'B8'
114-
# or 'B9' or 'B10'
111+
# auto | letter | legal | ledger | A0 | A1 | A2 |
112+
# A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 |
113+
# B0 | B1 | B2 | B3 | B4 | B5 | B6 | B7 | B8
114+
# | B9 | B10
115115
papersize = 'letter'
116116
# a value of type 'bool'
117117
useafm = False
@@ -216,7 +216,7 @@ units = False
216216
# 'Accent' or 'Accent_r' or 'Blues' or 'Blues_r' or 'BrBG' or 'BrBG_r' or
217217
# 'BuGn' or 'BuGn_r' or 'BuPu' or 'BuPu_r' or 'Dark2' or 'Dark2_r' or
218218
# 'GnBu' or 'GnBu_r' or 'Greens' or 'Greens_r' or 'Greys' or 'Greys_r' or
219-
# <...snipped 16 lines...>
219+
# <...snipped 16 lines...>
220220
# 'pink_r' or 'prism' or 'prism_r' or 'spectral' or 'spectral_r' or
221221
# 'spring' or 'spring_r' or 'summer' or 'summer_r' or 'winter' or
222222
# 'winter_r'
@@ -404,4 +404,4 @@ units = False
404404
# a value of type 'float'
405405
pad = 4.0
406406
# a value of type 'float'
407-
size = 2.0
407+
size = 2.0

unit/mlab_unit.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import datetime, StringIO, unittest
2+
import matplotlib.mlab as mlab
3+
import numpy
4+
5+
class TestMlab(unittest.TestCase):
6+
def test_csv2rec_closefile(self):
7+
# If passed a file-like object, rec2csv should not close it.
8+
ra=numpy.rec.array([(123, 1197346475.0137341), (456, 123.456)],
9+
dtype=[('a', '<i8'), ('b', '<f8')])
10+
fh = StringIO.StringIO()
11+
mlab.rec2csv( ra, fh )
12+
self.failIf( fh.closed )
13+
14+
def test_csv2rec_roundtrip(self):
15+
16+
# Make sure double-precision floats and strings pass through a
17+
# roundtrip unaltered.
18+
19+
# A bug in numpy (fixed in r4602) meant that numpy scalars
20+
# lost precision when passing through repr(). csv2rec was
21+
# affected by this. This test will only pass on numpy >=
22+
# 1.0.5.
23+
delta = datetime.timedelta(days=1)
24+
date0 = datetime.date(2007,12,16)
25+
date1 = date0 + delta
26+
date2 = date1 + delta
27+
28+
delta = datetime.timedelta(days=1)
29+
datetime0 = datetime.datetime(2007,12,16,22,29,34,924122)
30+
datetime1 = datetime0 + delta
31+
datetime2 = datetime1 + delta
32+
ra=numpy.rec.fromrecords([
33+
(123, date0, datetime0, 1197346475.0137341, 'a,bc'),
34+
(456, date1, datetime1, 123.456, 'd\'ef'),
35+
(789, date2, datetime2, 0.000000001, 'ghi'),
36+
],
37+
names='intdata,datedata,datetimedata,floatdata,stringdata')
38+
39+
fh = StringIO.StringIO()
40+
mlab.rec2csv( ra, fh )
41+
fh.seek(0)
42+
if 0:
43+
print 'CSV contents:','-'*40
44+
print fh.read()
45+
print '-'*40
46+
fh.seek(0)
47+
ra2 = mlab.csv2rec(fh)
48+
fh.close()
49+
#print 'ra', ra
50+
#print 'ra2', ra2
51+
for name in ra.dtype.names:
52+
if 0:
53+
print name, repr(ra[name]), repr(ra2[name])
54+
dt = ra.dtype[name]
55+
print 'repr(dt.type)',repr(dt.type)
56+
self.failUnless( numpy.all(ra[name] == ra2[name]) ) # should not fail with numpy 1.0.5
57+
58+
if __name__=='__main__':
59+
unittest.main()

0 commit comments

Comments
 (0)