1
2
3
4
5
6
7
8
9
10 """utils.py -- Utility functions used by Gnuplot.
11
12 This module contains utility functions used by Gnuplot.py which aren't
13 particularly gnuplot-related.
14
15 """
16
17 __cvs_version__ = '$Revision: 2.4 $'
18
19 import string
20 import Numeric
21
22
24 """Return the argument as a Numeric array of type at least 'Float32'.
25
26 Leave 'Float64' unchanged, but upcast all other types to
27 'Float32'. Allow also for the possibility that the argument is a
28 python native type that can be converted to a Numeric array using
29 'Numeric.asarray()', but in that case don't worry about
30 downcasting to single-precision float.
31
32 """
33
34 try:
35
36 return Numeric.asarray(m, Numeric.Float32)
37 except TypeError:
38
39
40
41 return Numeric.asarray(m, Numeric.Float)
42
43
44 -def write_array(f, set,
45 item_sep=' ',
46 nest_prefix='', nest_suffix='\n', nest_sep=''):
47 """Write an array of arbitrary dimension to a file.
48
49 A general recursive array writer. The last four parameters allow
50 a great deal of freedom in choosing the output format of the
51 array. The defaults for those parameters give output that is
52 gnuplot-readable. But using '(",", "{", "}", ",\n")' would output
53 an array in a format that Mathematica could read. 'item_sep'
54 should not contain '%' (or if it does, it should be escaped to
55 '%%') since it is put into a format string.
56
57 The default 2-d file organization::
58
59 set[0,0] set[0,1] ...
60 set[1,0] set[1,1] ...
61
62 The 3-d format::
63
64 set[0,0,0] set[0,0,1] ...
65 set[0,1,0] set[0,1,1] ...
66
67 set[1,0,0] set[1,0,1] ...
68 set[1,1,0] set[1,1,1] ...
69
70 """
71
72 if len(set.shape) == 1:
73 (columns,) = set.shape
74 assert columns > 0
75 fmt = string.join(['%s'] * columns, item_sep)
76 f.write(nest_prefix)
77 f.write(fmt % tuple(set.tolist()))
78 f.write(nest_suffix)
79 elif len(set.shape) == 2:
80
81
82 (points, columns) = set.shape
83 assert points > 0 and columns > 0
84 fmt = string.join(['%s'] * columns, item_sep)
85 f.write(nest_prefix + nest_prefix)
86 f.write(fmt % tuple(set[0].tolist()))
87 f.write(nest_suffix)
88 for point in set[1:]:
89 f.write(nest_sep + nest_prefix)
90 f.write(fmt % tuple(point.tolist()))
91 f.write(nest_suffix)
92 f.write(nest_suffix)
93 else:
94
95 assert set.shape[0] > 0
96 f.write(nest_prefix)
97 write_array(f, set[0],
98 item_sep, nest_prefix, nest_suffix, nest_sep)
99 for subset in set[1:]:
100 f.write(nest_sep)
101 write_array(f, subset,
102 item_sep, nest_prefix, nest_suffix, nest_sep)
103 f.write(nest_suffix)
104