~mrol-dev/mrol/trunk

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
"""
Launch a mayavi server and execute plotting methods on the server by passing
data over the network

Usage:
    t = np.linspace(0, 2*np.pi, 50)
    u = np.cos(t) * np.pi
    x, y, z = np.sin(u), np.cos(u), np.sin(t)
    mlabproxy = RemoteMlab()
    mlabproxy.points3d(x, y, z, z, scale_mode='none')
    mlabproxy.clf()
    mlabproxy.plot3d(x, y, z, z)
"""
import subprocess
import socket
import signal
import sys
import tempfile
import numpy as np
import cPickle
import cStringIO
import base64
import os
import errno
import time

HOST = 'localhost' # changing this won't suffice
PORT = 8007
devnull = open(os.devnull, 'wb')

def launch_server(port, log_stdout, log_stderr):
    dir = os.path.dirname(__file__)
    serverscript = os.path.join(dir, "mayaviserver.py")
    cmd = ['python', serverscript, str(port)]
    print("Launching " + " ".join(cmd))
    return subprocess.Popen(cmd,
                            stdout=log_stdout,
                            stderr=log_stderr)


class RemoteMlab(object):
    def __init__(self, port=PORT, log_stdout=sys.stdout, log_stderr=sys.stderr):
        # Don't launch the server if already running
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((HOST, PORT))
        except socket.error, e:
            if e.errno != errno.ECONNREFUSED:
                raise
            # server not running, let's launch
            self.subprocess = launch_server(port, log_stdout, log_stderr)
            # Wait for server to start
            print("Waiting for server")
            time.sleep(4)

        # keep trying 
        for i in range(5):
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.connect((HOST, PORT))
                break
            except socket.error, e:
                if e.errno != errno.ECONNREFUSED:
                    raise
                # Wait for server to start
                print("Waiting for server")
                time.sleep(2)
        sockfile = sock.makefile()
        sock.send("""import numpy as np\n""")
        sock.send("""import cPickle\n""")
        sock.send("""import base64\n""")
        sock.send("""import cStringIO\n""")
        sock.send("""args = []\n""")
        sock.send("""kwargs = {}\n""")
        self.sock = sock
        self.sockfile = sockfile
        self.tempfiles = []
        self.returnnumber = 0

    def pass_numpy_args(self, *args):
        """
        Pass numpy arrays by using numpy.ndarray.tostring() instead of
        cPickle.
        """
        nargs = len(args)
        names = ['a%d' % i for i in range(nargs)]
        tf = tempfile.NamedTemporaryFile(delete=False)
        np.savez(tf, **dict(zip(names, args)))
        tf.close()
        self.sock.send("""tf = open('{0}', 'rb')\n""".format(tf.name))
        self.sock.send("""arguments = np.load(tf)\n""")
        for n, a in zip(names, args):
            self.sock.send("""{n} = arguments['{n}']\n""".format(n=n))
        return names

    def pass_args(self, *args, **kwargs):
        """
        Pass arbitrary Python arguments and kwargs by using cPickle and base64
        encoding.
        """
        tf = tempfile.NamedTemporaryFile(delete=False)
        cPickle.dump(dict(args=args, kwargs=kwargs), tf)
        tf.close()
        self.sock.send("""tf = open('{0}', 'rb')\n""".format(tf.name))
        self.sock.send("""arguments = cPickle.load(tf)\n""")
        self.sock.send("""args = arguments['args']\n""")
        self.sock.send("""kwargs = arguments['kwargs']\n""")
        self.tempfiles.append(tf.name)

    def _set_args(self, *args, **kwargs):
        if 'numpyargs' in kwargs:
            numpyargs = kwargs['numpyargs']
            del kwargs['numpyargs']
        else:
            numpyargs = 0
        if numpyargs:
            numpynames = self.pass_numpy_args(*args[:numpyargs])
        nonnumpyargs = args[numpyargs:]
        self.pass_args(*nonnumpyargs, **kwargs)
        return numpynames if (numpyargs) else None

    def exec_func(self, funcname, *args, **kwargs):
        numpynames = 0
        if 'numpyargs' in kwargs:
            numpyargs = kwargs['numpyargs']
            del kwargs['numpyargs']
        else:
            numpyargs = 0

        self.pass_args(*args, **kwargs)
        if numpynames:
            self.sock.send(
                """ret{rn} = mlab.{func}({numpyargs}, *args,**kwargs)\n""".format(
                    rn=self.returnnumber, func=funcname, numpyargs=(', '.join(numpynames))))
        else:
            self.sock.send(
                """ret{rn} = mlab.{func}(*args,**kwargs)\n""".format(
                    rn=self.returnnumber, func=funcname))

    def getreturnvar(self):
        r = self.returnnumber
        self.returnnumber += 1
        return "ret{rn}".format(rn=r)

    def ex(self, statement, *args, **kwargs):
        """
        Execute the given statement assuming the args are
        """
        self._set_args(*args, **kwargs)
        self.sock.send(statement + "\n")

    def points3d(self, x, y, z, t, **kwargs):
        self.exec_func("points3d", x, y, z, t, numpyargs=4, **kwargs)

    def __getattr__(self, name):
        def func(*args, **kwargs):
            self.exec_func(name, *args, **kwargs)
        return func

    def close(self, client_only=False):
        self.sock.shutdown(socket.SHUT_WR)
        self.sock.close()
        for tf in self.tempfiles:
            os.remove(tf)
        if not client_only:
            self.subprocess.kill()
            os.wait()