class LivePlotClient(object): def __init__(self, timeout=2000, size=2**20): self.app = QCoreApplication.instance() if self.app is None: self.app = QCoreApplication([]) self.sock = QLocalSocket() self.sock.connectToServer("LivePlot") if not self.sock.waitForConnected(): raise EnvironmentError("Couldn't find LivePlotter instance") self.sock.disconnected.connect(self.disconnect_received) key = str(uuid.uuid4()) self.shared_mem = QSharedMemory(key) if not self.shared_mem.create(size): raise Exception("Couldn't create shared memory %s" % self.shared_mem.errorString()) logging.debug('Memory created with key %s and size %s' % (key, self.shared_mem.size())) self.sock.write(key) self.sock.waitForBytesWritten() self.is_connected = True self.timeout = timeout atexit.register(self.close) def close(self): self.shared_mem.detach() def send_to_plotter(self, meta, arr=None): if not self.is_connected: return if meta["name"] is None: meta["name"] = "*"; if arr is not None: arrbytes = bytearray(arr) arrsize = len(arrbytes) if arrsize > self.shared_mem.size(): raise ValueError("Array too big %s > %s" % (arrsize, self.shared_mem.size())) meta['arrsize'] = arrsize meta['dtype'] = str(arr.dtype) meta['shape'] = arr.shape else: meta['arrsize'] = 0 meta_bytes = json.dumps(meta).ljust(200) if len(meta_bytes) > 200: raise ValueError("meta object is too large (> 200 char)") if arr is None: self.sock.write(meta_bytes) else: if not self.sock.bytesAvailable(): self.sock.waitForReadyRead() self.sock.read(2) self.shared_mem.lock() self.sock.write(meta_bytes) region = self.shared_mem.data() region[:arrsize] = arrbytes self.shared_mem.unlock() def plot_y(self, name, arr, extent=None, start_step=None): arr = np.array(arr) if extent is not None and start_step is not None: raise ValueError('extent and start_step provide the same info and are thus mutually exclusive') if extent is not None: x0, x1 = extent nx = len(arr) start_step = x0, float(x1 - x0)/nx meta = { 'name': name, 'operation':'plot_y', 'start_step': start_step, 'rank': 1, } self.send_to_plotter(meta, arr) def plot_z(self, name, arr, extent=None, start_step=None): ''' extent is ((initial x, final x), (initial y, final y)) start_step is ((initial x, delta x), (initial_y, final_y)) ''' arr = np.array(arr) if extent is not None and start_step is not None: raise ValueError('extent and start_step provide the same info and are thus mutually exclusive') if extent is not None: (x0, x1), (y0, y1) = extent nx, ny = arr.shape start_step = (x0, float(x1 - x0)/nx), (y0, float(y1 - y0)/ny) meta = { 'name': name, 'operation':'plot_z', 'rank': 2, 'start_step': start_step, } self.send_to_plotter(meta, arr) def plot_xy(self, name, xs, ys): arr = np.array([xs, ys]) meta = { 'name': name, 'operation':'plot_xy', 'rank': 1, } self.send_to_plotter(meta, np.array([xs, ys])) def append_y(self, name, point, start_step=None): self.send_to_plotter({ 'name': name, 'operation': 'append_y', 'value': point, 'start_step': start_step, 'rank': 1, }) def append_xy(self, name, x, y): self.send_to_plotter({ 'name': name, 'operation': 'append_xy', 'value': (x, y), 'rank': 1, }) def append_z(self, name, arr, start_step=None): arr = np.array(arr) meta = { 'name': name, 'operation':'append_z', 'rank': 2, 'start_step': start_step, } self.send_to_plotter(meta, arr) def clear(self, name=None): self.send_to_plotter({ 'name': name, 'operation': 'clear' }) def hide(self, name=None): self.send_to_plotter({ 'name': name, 'operation': 'close' }) def remove(self, name=None): self.send_to_plotter({ 'name': name, 'operation': 'remove' }) def disconnect_received(self): self.is_connected = False warnings.warn('Disconnected from LivePlotter server, plotting has been disabled')
class SingletonApp(QApplication): timeout = 1000 def __init__(self, argv, application_id=None): QApplication.__init__(self, argv) self.socket_filename = unicode(os.path.expanduser("~/.ipc_%s" % self.generate_ipc_id()) ) self.shared_mem = QSharedMemory() self.shared_mem.setKey(self.socket_filename) if self.shared_mem.attach(): self.is_running = True return self.is_running = False if not self.shared_mem.create(1): print >>sys.stderr, "Unable to create single instance" return # start local server self.server = QLocalServer(self) # connect signal for incoming connections self.connect(self.server, SIGNAL("newConnection()"), self.receive_message) # if socket file exists, delete it if os.path.exists(self.socket_filename): os.remove(self.socket_filename) # listen self.server.listen(self.socket_filename) def __del__(self): self.shared_mem.detach() if not self.is_running: if os.path.exists(self.socket_filename): os.remove(self.socket_filename) def generate_ipc_id(self, channel=None): if channel is None: channel = os.path.basename(sys.argv[0]) return "%s_%s" % (channel, getpass.getuser()) def send_message(self, message): if not self.is_running: raise Exception("Client cannot connect to IPC server. Not running.") socket = QLocalSocket(self) socket.connectToServer(self.socket_filename, QIODevice.WriteOnly) if not socket.waitForConnected(self.timeout): raise Exception(str(socket.errorString())) socket.write(pickle.dumps(message)) if not socket.waitForBytesWritten(self.timeout): raise Exception(str(socket.errorString())) socket.disconnectFromServer() def receive_message(self): socket = self.server.nextPendingConnection() if not socket.waitForReadyRead(self.timeout): print >>sys.stderr, socket.errorString() return byte_array = socket.readAll() self.handle_new_message(pickle.loads(str(byte_array))) def handle_new_message(self, message): self.emit( SIGNAL("message"), message )
class SingletonApp(QApplication): timeout = 1000 def __init__(self, argv, application_id=None): QApplication.__init__(self, argv) self.socket_filename = unicode( os.path.expanduser("~/.ipc_%s" % self.generate_ipc_id())) self.shared_mem = QSharedMemory() self.shared_mem.setKey(self.socket_filename) if self.shared_mem.attach(): self.is_running = True return self.is_running = False if not self.shared_mem.create(1): print >> sys.stderr, "Unable to create single instance" return # start local server self.server = QLocalServer(self) # connect signal for incoming connections self.connect(self.server, SIGNAL("newConnection()"), self.receive_message) # if socket file exists, delete it if os.path.exists(self.socket_filename): os.remove(self.socket_filename) # listen self.server.listen(self.socket_filename) def __del__(self): self.shared_mem.detach() if not self.is_running: if os.path.exists(self.socket_filename): os.remove(self.socket_filename) def generate_ipc_id(self, channel=None): if channel is None: channel = os.path.basename(sys.argv[0]) return "%s_%s" % (channel, getpass.getuser()) def send_message(self, message): if not self.is_running: raise Exception( "Client cannot connect to IPC server. Not running.") socket = QLocalSocket(self) socket.connectToServer(self.socket_filename, QIODevice.WriteOnly) if not socket.waitForConnected(self.timeout): raise Exception(str(socket.errorString())) socket.write(pickle.dumps(message)) if not socket.waitForBytesWritten(self.timeout): raise Exception(str(socket.errorString())) socket.disconnectFromServer() def receive_message(self): socket = self.server.nextPendingConnection() if not socket.waitForReadyRead(self.timeout): print >> sys.stderr, socket.errorString() return byte_array = socket.readAll() self.handle_new_message(pickle.loads(str(byte_array))) def handle_new_message(self, message): self.emit(SIGNAL("loadPgLayer"), message)
class SingletonApp(QApplication): ''' Simple server based on QLocalServer, QLocalSocket, QSharedMemory that sends and receives messages and data with a socket connection and shared memory ''' timeout = 1000 running_apps = [] def __init__(self, argv=sys.argv, application_id=None, size=2**24): QApplication.__init__(self, argv) self.socket_filename = os.path.expanduser(os.path.join(os.getcwd(),'.ipc_%s' % self.generate_ipc_id())) self.shared_mem = QSharedMemory() self.shared_mem.setKey(self.socket_filename) if self.shared_mem.attach(): self.is_running = True return self.is_running = False if not self.shared_mem.create(size): print >>sys.stderr, "Unable to create single instance" return # start local server self.server = QLocalServer(self) # connect signal for incoming connections self.connect(self.server, SIGNAL("newConnection()"), self.receive_message) # if socket file exists, delete it if os.path.exists(self.socket_filename): os.remove(self.socket_filename) # listen self.server.listen(self.socket_filename) SingletonApp.running_apps.append(self) def __del__(self): logging.debug('Detaching shared memory and closing socket connection.') self.shared_mem.detach() if not self.is_running: if os.path.exists(self.socket_filename): os.remove(self.socket_filename) def generate_ipc_id(self, channel=None): if channel: return '%s_%s' %(channel,getpass.get_user()) else: return getpass.getuser() def send_message(self, message): if not self.is_running: raise Exception("Client cannot connect to IPC server. Not running.") socket = QLocalSocket(self) socket.connectToServer(self.socket_filename, QIODevice.WriteOnly) if not socket.waitForConnected(self.timeout): self.__del__() if not socket.waitForConnected(self.timeout): raise Exception(str(socket.errorString())) socket.write(pickle.dumps(message)) if not socket.waitForBytesWritten(self.timeout): raise Exception(str(socket.errorString())) socket.disconnectFromServer() def receive_message(self): socket = self.server.nextPendingConnection() if not socket.waitForReadyRead(self.timeout): print >>sys.stderr, socket.errorString() return byte_array = socket.readAll() self.handle_new_message(pickle.loads(byte_array)) def handle_new_message(self, message): logging.debug("Received: %s" %message)
class LivePlotClient(object): def __init__(self, timeout=2000, size=2**20): self.app = QCoreApplication.instance() if self.app is None: self.app = QCoreApplication([]) self.sock = QLocalSocket() self.sock.connectToServer("LivePlot") if not self.sock.waitForConnected(): raise EnvironmentError("Couldn't find LivePlotter instance") self.sock.disconnected.connect(self.disconnect_received) key = str(uuid.uuid4()) self.shared_mem = QSharedMemory(key) if not self.shared_mem.create(size): raise Exception("Couldn't create shared memory %s" % self.shared_mem.errorString()) logging.debug('Memory created with key %s and size %s' % (key, self.shared_mem.size())) self.sock.write(key) self.sock.waitForBytesWritten() self.is_connected = True self.timeout = timeout atexit.register(self.close) def close(self): self.shared_mem.detach() def send_to_plotter(self, meta, arr=None): if not self.is_connected: return if meta["name"] is None: meta["name"] = "*" if arr is not None: arrbytes = bytearray(arr) arrsize = len(arrbytes) if arrsize > self.shared_mem.size(): raise ValueError("Array too big %s > %s" % (arrsize, self.shared_mem.size())) meta['arrsize'] = arrsize meta['dtype'] = str(arr.dtype) meta['shape'] = arr.shape else: meta['arrsize'] = 0 meta_bytes = json.dumps(meta).ljust(200) if len(meta_bytes) > 200: raise ValueError("meta object is too large (> 200 char)") if arr is None: self.sock.write(meta_bytes) else: if not self.sock.bytesAvailable(): self.sock.waitForReadyRead() self.sock.read(2) self.shared_mem.lock() self.sock.write(meta_bytes) region = self.shared_mem.data() region[:arrsize] = arrbytes self.shared_mem.unlock() def plot_y(self, name, arr, extent=None, start_step=None): arr = np.array(arr) if extent is not None and start_step is not None: raise ValueError( 'extent and start_step provide the same info and are thus mutually exclusive' ) if extent is not None: x0, x1 = extent nx = len(arr) start_step = x0, float(x1 - x0) / nx meta = { 'name': name, 'operation': 'plot_y', 'start_step': start_step, 'rank': 1, } self.send_to_plotter(meta, arr) def plot_z(self, name, arr, extent=None, start_step=None): ''' extent is ((initial x, final x), (initial y, final y)) start_step is ((initial x, delta x), (initial_y, final_y)) ''' arr = np.array(arr) if extent is not None and start_step is not None: raise ValueError( 'extent and start_step provide the same info and are thus mutually exclusive' ) if extent is not None: (x0, x1), (y0, y1) = extent nx, ny = arr.shape start_step = (x0, float(x1 - x0) / nx), (y0, float(y1 - y0) / ny) meta = { 'name': name, 'operation': 'plot_z', 'rank': 2, 'start_step': start_step, } self.send_to_plotter(meta, arr) def plot_xy(self, name, xs, ys): arr = np.array([xs, ys]) meta = { 'name': name, 'operation': 'plot_xy', 'rank': 1, } self.send_to_plotter(meta, np.array([xs, ys])) def append_y(self, name, point, start_step=None): self.send_to_plotter({ 'name': name, 'operation': 'append_y', 'value': point, 'start_step': start_step, 'rank': 1, }) def append_xy(self, name, x, y): self.send_to_plotter({ 'name': name, 'operation': 'append_xy', 'value': (x, y), 'rank': 1, }) def append_z(self, name, arr, start_step=None): arr = np.array(arr) meta = { 'name': name, 'operation': 'append_z', 'rank': 2, 'start_step': start_step, } self.send_to_plotter(meta, arr) def clear(self, name=None): self.send_to_plotter({'name': name, 'operation': 'clear'}) def hide(self, name=None): self.send_to_plotter({'name': name, 'operation': 'close'}) def remove(self, name=None): self.send_to_plotter({'name': name, 'operation': 'remove'}) def disconnect_received(self): self.is_connected = False warnings.warn( 'Disconnected from LivePlotter server, plotting has been disabled')