-
Notifications
You must be signed in to change notification settings - Fork 6
/
tools.py
268 lines (224 loc) · 8.21 KB
/
tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as _np
import os as _os
import time as _time
import scipy.io as _sio
def indexS2M(sInd, dims):
'''Single- to multi-index.'''
return _np.array(_np.unravel_index(sInd, dims))
def indexM2S(mInd, dims):
'''Multi- to single-index.'''
return _np.ravel_multi_index(mInd, dims)
def printVector(x, name = None, k = 8):
'''Prints the vector like Matlab.'''
n = x.size
c = 0
if name != None: print(name + ' = ')
while c < n:
print('\033[94m (columns %s through %s)\033[0m' % (c, min(c+k, n)-1))
for j in range(c, min(c+k, n)):
print(' % 10.5f' % x[j], end = '')
print('')
c += k
def printMatrix(x, name = None, k = 8):
'''Prints the matrix like Matlab.'''
m, n = x.shape
c = 0
if name != None: print(name + ' = ')
while c < n:
print('\033[94m (columns %s through %s)\033[0m' % (c, min(c+k, n)-1))
for i in range(m):
for j in range(c, min(c+k, n)):
print(' % 10.5f' % x[i, j], end = '')
print('')
c += k
class Timer(object):
def __init__(self, name=None):
self.name = name
def __enter__(self):
self.tstart = _time.time()
def __exit__(self, type, value, traceback):
if self.name:
print('%s: ' % self.name, end = '')
print('%s s' % (_time.time() - self.tstart))
class matmux(object):
'''
Communicate with a running Matlab session, which needs to be started via:
$ tmux new -s matlab "matlab -nodesktop"
'''
def __init__(self):
self.cmd = 'tmux send-keys -t matlab "%s\n"' # tmux command to be augmented by Matlab code
self.tmpFile = '/tmp/matmux.mat' # for exchanging variables between Python and Matlab
def __call__(self, s):
'''
Execute Matlab code contained in the string s, e.g.:
this('X = rand(2, 4)')
'''
_os.system(self.cmd % s)
def __repr__(self):
return 'Matlab communicator.'
def _loadmat(self):
self('load %s;\ndelete %s;' % (self.tmpFile, self.tmpFile))
# wait until Matlab deleted the temporary file to make sure that the variables have been
# read and the file can be written again
while _os.path.isfile(self.tmpFile):
_time.sleep(0.05)
def exportVars(self, *args):
'''
Export variables to Matlab, e.g.:
x = 1
y = 2
this.exportVars('x', x, 'y', y)
'''
variableDict = dict(zip(args[::2], args[1::2]))
_sio.savemat(self.tmpFile, variableDict, do_compression=True)
self._loadmat()
def importVars(self, *args):
'''
Import variables from Matlab, e.g.:
x, y = this.importVars('x', 'y')
'''
self('save(\'%s\', %s)' % (self.tmpFile, ', '.join(['\'%s\'' % arg for arg in args])))
_time.sleep(10) # tmp. fix, othe
while not _os.path.isfile(self.tmpFile): # it might take a while until the file is written
_time.sleep(0.05)
data = _sio.loadmat(self.tmpFile, squeeze_me=True)
_os.remove(self.tmpFile) # delete file again
return tuple(data[arg] for arg in args)
def figure(self, i=-1):
if i == -1:
self('figure;')
else:
self('figure(%d);' % i)
def close(self, i=-1):
if i == -1:
self('close all;')
else:
self('close(%d);' % i)
def plot(self, x, y):
_sio.savemat(self.tmpFile, {'x':x, 'y':y})
self._loadmat()
self('plot(x, y);')
def surf(self, x, y, z):
_sio.savemat(self.tmpFile, {'x':x, 'y':y, 'z':z})
self._loadmat()
self("surf(x, y, z); xlabel('x'); ylabel('y'); zlabel('z');")
def scatter(self, x, y, c):
_sio.savemat(self.tmpFile, {'x':x, 'y':y, 'c':c})
self._loadmat()
self("scatter(x, y, 100, c, '.');")
def scatter3(self, x, y, z, c):
_sio.savemat(self.tmpFile, {'x':x, 'y':y, 'z':z, 'c':c})
self._loadmat()
self("scatter3(x, y, z, 100, c, '.'); xlabel('x'); ylabel('y'); zlabel('z');")
def pcolor(self, x, y, z):
_sio.savemat(self.tmpFile, {'x':x, 'y':y, 'z':z})
self._loadmat()
self('pcolor(x, y, z);')
def imagesc(self, x):
_sio.savemat(self.tmpFile, {'x':x})
self._loadmat()
self('imagesc(x);')
def plotDomain(self, Omega, x):
d = Omega._d
if d == 1:
self.plot(Omega.midpointGrid().squeeze(), x)
elif d == 2:
c = Omega.midpointGrid()
cx = c[0, :].reshape(Omega._boxes)
cy = c[1, :].reshape(Omega._boxes)
cz = x.reshape(Omega._boxes)
self.surf(cx, cy, cz)
else:
print('Not defined for d > 2.')
class octmux(object):
'''
Communicate with a running Octave session, which needs to be started via:
$ tmux new -s octave "octave --no-gui"
'''
def __init__(self):
self.cmd = 'tmux send-keys -t octave "%s" Enter' # tmux command to be augmented by Octave code
self.tmpFile = '/tmp/octmux.mat' # for exchanging variables between Python and Octave
def __call__(self, s):
'''
Execute Octave code contained in the string s, e.g.:
this('X = rand(2, 4)')
'''
_os.system(self.cmd % s.replace(';', '\;'))
def __repr__(self):
return 'Octave communicator.'
def _loadmat(self):
self('load %s;' % self.tmpFile)
self('delete %s;' % self.tmpFile)
# wait until Octave deleted the temporary file to make sure that the variables have been
# read and the file can be written again
while _os.path.isfile(self.tmpFile):
_time.sleep(0.05)
def exportVars(self, *args):
'''
Export variables to Octave, e.g.:
x = 1
y = 2
this.exportVars('x', x, 'y', y)
'''
variableDict = dict(zip(args[::2], args[1::2]))
_sio.savemat(self.tmpFile, variableDict, do_compression=True)
self._loadmat()
def importVars(self, *args):
'''
Import variables from Octave, e.g.:
x, y = this.importVars('x', 'y')
'''
self('save(\'%s\', %s, \'-v7\')' % (self.tmpFile, ', '.join(['\'%s\'' % arg for arg in args])))
while not _os.path.isfile(self.tmpFile): # it might take a while until the file is written
_time.sleep(0.05)
data = _sio.loadmat(self.tmpFile, squeeze_me=True)
_os.remove(self.tmpFile) # delete file again
return tuple(data[arg] for arg in args)
def figure(self, i=-1):
if i == -1:
self('figure;')
else:
self('figure(%d);' % i)
def close(self, i=-1):
if i == -1:
self('close all;')
else:
self('close(%d);' % i)
def plot(self, x, y):
_sio.savemat(self.tmpFile, {'x':x, 'y':y})
self._loadmat()
self('plot(x, y);')
def surf(self, x, y, z):
_sio.savemat(self.tmpFile, {'x':x, 'y':y, 'z':z})
self._loadmat()
self("surf(x, y, z); xlabel('x'); ylabel('y'); zlabel('z');")
def scatter(self, x, y, c):
_sio.savemat(self.tmpFile, {'x':x, 'y':y, 'c':c})
self._loadmat()
self("scatter(x, y, 100, c, '.');")
def scatter3(self, x, y, z, c):
_sio.savemat(self.tmpFile, {'x':x, 'y':y, 'z':z, 'c':c})
self._loadmat()
self("scatter3(x, y, z, 100, c, '.'); xlabel('x'); ylabel('y'); zlabel('z');")
def pcolor(self, x, y, z):
_sio.savemat(self.tmpFile, {'x':x, 'y':y, 'z':z})
self._loadmat()
self('pcolor(x, y, z);')
def imagesc(self, x):
_sio.savemat(self.tmpFile, {'x':x})
self._loadmat()
self('imagesc(x);')
def plotDomain(self, Omega, x):
d = Omega._d
if d == 1:
self.plot(Omega.midpointGrid().squeeze(), x)
elif d == 2:
c = Omega.midpointGrid()
cx = c[0, :].reshape(Omega._boxes)
cy = c[1, :].reshape(Omega._boxes)
cz = x.reshape(Omega._boxes)
self.surf(cx, cy, cz)
else:
print('Not defined for d > 2.')