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