QuLab 2.0.1__cp312-cp312-win_amd64.whl → 2.0.2__cp312-cp312-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,209 @@
1
+ from typing import Optional
2
+
3
+ import zmq
4
+ import zmq.asyncio
5
+ import zmq.auth
6
+ from watchdog.events import FileSystemEventHandler
7
+ from watchdog.observers import Observer
8
+ from zmq.auth.asyncio import AsyncioAuthenticator
9
+ from zmq.auth.thread import ThreadAuthenticator
10
+
11
+
12
+ class ReloadCertificatesHandler(FileSystemEventHandler):
13
+
14
+ def __init__(self, zmq: 'ZMQContextManager'):
15
+ self.zmq = zmq
16
+
17
+ def on_modified(self, event):
18
+ self.zmq.reload_certificates()
19
+
20
+
21
+ class ZMQContextManager:
22
+ """
23
+ A context manager for managing ZeroMQ sockets with asynchronous support.
24
+ It handles the creation, connection, binding, and security configuration of
25
+ the sockets and ensures proper resource cleanup.
26
+
27
+ The context manager can be used as a synchronous context manager or an
28
+ asynchronous context manager. When used as an asynchronous context manager,
29
+ the socket is created with an asyncio context and can be used with the
30
+ `await` keyword.
31
+
32
+ The security settings for the socket can be configured using the secret key
33
+ and public key parameters. If the secret key is provided, the socket is
34
+ configured to use ZeroMQ curve encryption. The public key of the server can
35
+ also be provided for client sockets to connect to a server with curve
36
+ encryption. You can also provide the paths to the secret key and public key
37
+ files, and the public key of the server to load the keys from files. The
38
+ keys can be reloaded automatically when the files are modified by setting
39
+ the `public_keys_location` parameter.
40
+
41
+ To generate a secret key and public key pair, you can use the following
42
+ commands:
43
+
44
+ ```bash
45
+ # Generate a secret key and public key pair
46
+ python -c "import zmq.auth; zmq.auth.create_certificates('.', 'filename')"
47
+ ```
48
+
49
+ Attributes:
50
+ socket_type: zmq.SocketType
51
+ The type of the socket to create (e.g., zmq.REP).
52
+ bind: str, optional
53
+ The address to bind the socket to.
54
+ connect: str, optional
55
+ The address to connect the socket to.
56
+ secret_key_file: str, optional
57
+ The path to the secret key file for ZeroMQ curve encryption.
58
+ server_public_key_file: str, optional
59
+ The path to the public key file for the server in ZeroMQ curve
60
+ encryption.
61
+ public_keys_location: str, optional
62
+ The location to store the public keys for ZeroMQ curve encryption.
63
+ secret_key: bytes, optional
64
+ The secret key for ZeroMQ curve encryption.
65
+ public_key: bytes, optional
66
+ The public key for ZeroMQ curve encryption.
67
+ server_public_key: bytes, optional
68
+ The public key for the server in ZeroMQ curve encryption.
69
+
70
+ Methods:
71
+ _create_socket: zmq.Socket
72
+ Creates and configures a ZeroMQ socket.
73
+ _close_socket: None
74
+ Closes the ZeroMQ socket and the context, and stops the authenticator
75
+ if it was started.
76
+
77
+ Examples:
78
+ Create a REP socket and bind it to an address:
79
+
80
+ >>> async with ZMQContextManager(zmq.REP, bind='tcp://*:5555') as socket:
81
+ ... while True:
82
+ ... message = await socket.recv()
83
+ ... await socket.send(message)
84
+
85
+ Create a REQ socket and connect it to an address:
86
+
87
+ >>> with ZMQContextManager(zmq.REQ, connect='tcp://localhost:5555') as socket:
88
+ ... socket.send(b'Hello')
89
+ ... message = socket.recv()
90
+ """
91
+
92
+ def __init__(self,
93
+ socket_type: zmq.SocketType,
94
+ bind: Optional[str] = None,
95
+ connect: Optional[str] = None,
96
+ secret_key_file: Optional[str] = None,
97
+ server_public_key_file: Optional[str] = None,
98
+ public_keys_location: Optional[str] = None,
99
+ secret_key: Optional[bytes] = None,
100
+ public_key: Optional[bytes] = None,
101
+ server_public_key: Optional[bytes] = None):
102
+ self.socket_type = socket_type
103
+ if bind is None and connect is None:
104
+ raise ValueError("Either 'bind' or 'connect' must be specified.")
105
+ if bind is not None and connect is not None:
106
+ raise ValueError("Both 'bind' and 'connect' cannot be specified.")
107
+ self.bind = bind
108
+ self.connect = connect
109
+ self.secret_key = secret_key
110
+ self.public_key = public_key
111
+ self.server_public_key = server_public_key
112
+
113
+ if secret_key_file:
114
+ self.public_key, self.secret_key = zmq.auth.load_certificate(
115
+ secret_key_file)
116
+
117
+ if (self.secret_key is not None and self.public_key is None
118
+ or self.secret_key is None and self.public_key is not None):
119
+ raise ValueError(
120
+ "Both secret key and public key must be specified.")
121
+
122
+ if server_public_key_file:
123
+ self.server_public_key = zmq.auth.load_certificate(
124
+ server_public_key_file)[0]
125
+
126
+ self.public_keys_location = public_keys_location
127
+
128
+ self.observer = None
129
+ self.auth = None
130
+ self.context = None
131
+ self.socket = None
132
+
133
+ def _create_socket(self, asyncio=False) -> zmq.Socket:
134
+ """
135
+ Creates and configures a ZeroMQ socket. Sets up security if required,
136
+ and binds or connects the socket according to the specified settings.
137
+
138
+ Returns:
139
+ zmq.Socket: The configured ZeroMQ socket.
140
+ """
141
+ if asyncio:
142
+ self.context = zmq.asyncio.Context()
143
+ else:
144
+ self.context = zmq.Context.instance()
145
+
146
+ self.socket = self.context.socket(self.socket_type)
147
+ self.auth = None
148
+
149
+ if self.bind and self.secret_key:
150
+ if asyncio:
151
+ self.auth = AsyncioAuthenticator(self.context)
152
+ else:
153
+ self.auth = ThreadAuthenticator(self.context)
154
+ self.auth.start()
155
+ self.reload_certificates()
156
+ self.auto_reload_certificates()
157
+ self.socket.curve_server = True # must come before bind
158
+
159
+ if self.secret_key:
160
+ self.socket.curve_secretkey = self.secret_key
161
+ self.socket.curve_publickey = self.public_key
162
+
163
+ if self.bind:
164
+ self.socket.bind(self.bind)
165
+ if self.connect:
166
+ if self.server_public_key:
167
+ self.socket.curve_serverkey = self.server_public_key
168
+ self.socket.connect(self.connect)
169
+ return self.socket
170
+
171
+ def reload_certificates(self):
172
+ if self.public_keys_location and self.auth:
173
+ self.auth.configure_curve(domain='*',
174
+ location=self.public_keys_location)
175
+
176
+ def auto_reload_certificates(self):
177
+ self.observer = Observer()
178
+ self.observer.schedule(ReloadCertificatesHandler(self),
179
+ self.public_keys_location,
180
+ recursive=False)
181
+ self.observer.start()
182
+
183
+ def _close_socket(self) -> None:
184
+ """
185
+ Closes the ZeroMQ socket and the context, and stops the authenticator
186
+ if it was started.
187
+ """
188
+ if self.observer:
189
+ self.observer.stop()
190
+ self.observer.join()
191
+ self.socket.close()
192
+ if self.auth:
193
+ self.auth.stop()
194
+ self.context.term()
195
+
196
+ def __enter__(self) -> zmq.Socket:
197
+ return self._create_socket(asyncio=False)
198
+
199
+ def __exit__(self, exc_type: Optional[type], exc_val: Optional[Exception],
200
+ exc_tb: Optional[type]) -> None:
201
+ self._close_socket()
202
+
203
+ async def __aenter__(self) -> zmq.Socket:
204
+ return self._create_socket(asyncio=True)
205
+
206
+ async def __aexit__(self, exc_type: Optional[type],
207
+ exc_val: Optional[Exception],
208
+ exc_tb: Optional[type]) -> None:
209
+ self._close_socket()
qulab/version.py CHANGED
@@ -1 +1 @@
1
- __version__ = "2.0.1"
1
+ __version__ = "2.0.2"
@@ -2,7 +2,7 @@ import math
2
2
 
3
3
  import matplotlib.pyplot as plt
4
4
  import numpy as np
5
- from matplotlib.colors import LogNorm
5
+ from matplotlib.colors import LogNorm, Normalize, SymLogNorm
6
6
  from matplotlib.ticker import EngFormatter, LogFormatterSciNotation
7
7
  from scipy.interpolate import griddata
8
8
 
@@ -239,10 +239,16 @@ def plot_img(x,
239
239
  kwds.setdefault('aspect', 'auto')
240
240
  kwds.setdefault('interpolation', 'nearest')
241
241
 
242
+ vmin = kwds.get('vmin', np.nanmin(z))
243
+ vmax = kwds.get('vmax', np.nanmax(z))
242
244
  if zscale == 'log':
243
- vmim = kwds.get('vmin', np.min(z))
244
- vmax = kwds.get('vmax', np.max(z))
245
- kwds.setdefault('norm', LogNorm(vmax=vmax, vmin=vmim))
245
+ kwds.setdefault('norm', LogNorm(vmax=vmax, vmin=vmin))
246
+ elif zscale == 'symlog':
247
+ kwds.setdefault('norm', SymLogNorm(vmax=vmax,
248
+ vmin=vmin,
249
+ linthresh=1e-5))
250
+ else:
251
+ kwds.setdefault('norm', Normalize(vmin=vmin, vmax=vmax))
246
252
  zlabel = f"{zlabel} [{z_unit}]" if z_unit else zlabel
247
253
 
248
254
  band_area = False
@@ -303,7 +309,7 @@ def plot_img(x,
303
309
  pass
304
310
  ax.set_xlabel(xlabel)
305
311
  ax.set_ylabel(ylabel)
306
- cb = fig.colorbar(img, ax=ax)
312
+ cb = fig.colorbar(img, ax=ax, norm=kwds.get('norm', None))
307
313
  cb.set_label(zlabel)
308
314
 
309
315