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