QuLab 2.0.2__cp310-cp310-macosx_10_9_universal2.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.
Files changed (84) hide show
  1. QuLab-2.0.2.dist-info/LICENSE +21 -0
  2. QuLab-2.0.2.dist-info/METADATA +98 -0
  3. QuLab-2.0.2.dist-info/RECORD +84 -0
  4. QuLab-2.0.2.dist-info/WHEEL +5 -0
  5. QuLab-2.0.2.dist-info/entry_points.txt +2 -0
  6. QuLab-2.0.2.dist-info/top_level.txt +1 -0
  7. qulab/__init__.py +1 -0
  8. qulab/__main__.py +26 -0
  9. qulab/fun.cpython-310-darwin.so +0 -0
  10. qulab/monitor/__init__.py +1 -0
  11. qulab/monitor/__main__.py +8 -0
  12. qulab/monitor/config.py +41 -0
  13. qulab/monitor/dataset.py +77 -0
  14. qulab/monitor/event_queue.py +54 -0
  15. qulab/monitor/mainwindow.py +234 -0
  16. qulab/monitor/monitor.py +93 -0
  17. qulab/monitor/ploter.py +123 -0
  18. qulab/monitor/qt_compat.py +16 -0
  19. qulab/monitor/toolbar.py +265 -0
  20. qulab/scan/__init__.py +3 -0
  21. qulab/scan/curd.py +144 -0
  22. qulab/scan/expression.py +505 -0
  23. qulab/scan/models.py +540 -0
  24. qulab/scan/optimize.py +69 -0
  25. qulab/scan/query_record.py +361 -0
  26. qulab/scan/recorder.py +447 -0
  27. qulab/scan/scan.py +701 -0
  28. qulab/scan/utils.py +37 -0
  29. qulab/storage/__init__.py +0 -0
  30. qulab/storage/__main__.py +51 -0
  31. qulab/storage/backend/__init__.py +0 -0
  32. qulab/storage/backend/redis.py +204 -0
  33. qulab/storage/base_dataset.py +352 -0
  34. qulab/storage/chunk.py +60 -0
  35. qulab/storage/dataset.py +127 -0
  36. qulab/storage/file.py +273 -0
  37. qulab/storage/models/__init__.py +22 -0
  38. qulab/storage/models/base.py +4 -0
  39. qulab/storage/models/config.py +28 -0
  40. qulab/storage/models/file.py +89 -0
  41. qulab/storage/models/ipy.py +58 -0
  42. qulab/storage/models/models.py +88 -0
  43. qulab/storage/models/record.py +161 -0
  44. qulab/storage/models/report.py +22 -0
  45. qulab/storage/models/tag.py +93 -0
  46. qulab/storage/storage.py +95 -0
  47. qulab/sys/__init__.py +0 -0
  48. qulab/sys/chat.py +688 -0
  49. qulab/sys/device/__init__.py +3 -0
  50. qulab/sys/device/basedevice.py +221 -0
  51. qulab/sys/device/loader.py +86 -0
  52. qulab/sys/device/utils.py +46 -0
  53. qulab/sys/drivers/FakeInstrument.py +52 -0
  54. qulab/sys/drivers/__init__.py +0 -0
  55. qulab/sys/ipy_events.py +125 -0
  56. qulab/sys/net/__init__.py +0 -0
  57. qulab/sys/net/bencoder.py +205 -0
  58. qulab/sys/net/cli.py +169 -0
  59. qulab/sys/net/dhcp.py +543 -0
  60. qulab/sys/net/dhcpd.py +176 -0
  61. qulab/sys/net/kad.py +1142 -0
  62. qulab/sys/net/kcp.py +192 -0
  63. qulab/sys/net/nginx.py +192 -0
  64. qulab/sys/progress.py +190 -0
  65. qulab/sys/rpc/__init__.py +0 -0
  66. qulab/sys/rpc/client.py +0 -0
  67. qulab/sys/rpc/exceptions.py +96 -0
  68. qulab/sys/rpc/msgpack.py +1052 -0
  69. qulab/sys/rpc/msgpack.pyi +41 -0
  70. qulab/sys/rpc/rpc.py +412 -0
  71. qulab/sys/rpc/serialize.py +139 -0
  72. qulab/sys/rpc/server.py +29 -0
  73. qulab/sys/rpc/socket.py +29 -0
  74. qulab/sys/rpc/utils.py +25 -0
  75. qulab/sys/rpc/worker.py +0 -0
  76. qulab/sys/rpc/zmq_socket.py +209 -0
  77. qulab/version.py +1 -0
  78. qulab/visualization/__init__.py +188 -0
  79. qulab/visualization/__main__.py +71 -0
  80. qulab/visualization/_autoplot.py +463 -0
  81. qulab/visualization/plot_layout.py +408 -0
  82. qulab/visualization/plot_seq.py +90 -0
  83. qulab/visualization/qdat.py +152 -0
  84. qulab/visualization/widgets.py +86 -0
qulab/scan/models.py ADDED
@@ -0,0 +1,540 @@
1
+ import hashlib
2
+ import pickle
3
+ import time
4
+ from datetime import datetime, timezone
5
+ from functools import singledispatchmethod
6
+ from typing import Optional
7
+
8
+ from sqlalchemy import (JSON, Column, DateTime, Float, ForeignKey, Integer,
9
+ LargeBinary, String, Table, Text, create_engine)
10
+ from sqlalchemy.orm import (backref, declarative_base, relationship,
11
+ sessionmaker)
12
+ from sqlalchemy.orm.session import Session
13
+ from waveforms.security import InvalidKey, encryptPassword, verifyPassword
14
+
15
+
16
+ def utcnow():
17
+ return datetime.now(timezone.utc)
18
+
19
+
20
+ Base = declarative_base()
21
+
22
+ # association table
23
+ user_roles = Table('user_roles', Base.metadata,
24
+ Column('user_id', ForeignKey('users.id'), primary_key=True),
25
+ Column('role_id', ForeignKey('roles.id'), primary_key=True))
26
+
27
+ record_reports = Table(
28
+ 'record_reports', Base.metadata,
29
+ Column('record_id', ForeignKey('records.id'), primary_key=True),
30
+ Column('report_id', ForeignKey('reports.id'), primary_key=True))
31
+
32
+ comment_tags = Table(
33
+ 'comment_tags', Base.metadata,
34
+ Column('comment_id', ForeignKey('comments.id'), primary_key=True),
35
+ Column('tag_id', ForeignKey('tags.id'), primary_key=True))
36
+
37
+ snapshot_tags = Table(
38
+ 'snapshot_tags', Base.metadata,
39
+ Column('snapshot_id', ForeignKey('snapshots.id'), primary_key=True),
40
+ Column('tag_id', ForeignKey('tags.id'), primary_key=True))
41
+
42
+ record_tags = Table(
43
+ 'record_tags', Base.metadata,
44
+ Column('record_id', ForeignKey('records.id'), primary_key=True),
45
+ Column('tag_id', ForeignKey('tags.id'), primary_key=True))
46
+
47
+ report_tags = Table(
48
+ 'report_tags', Base.metadata,
49
+ Column('report_id', ForeignKey('reports.id'), primary_key=True),
50
+ Column('tag_id', ForeignKey('tags.id'), primary_key=True))
51
+
52
+ sample_tags = Table(
53
+ 'sample_tags', Base.metadata,
54
+ Column('sample_id', ForeignKey('samples.id'), primary_key=True),
55
+ Column('tag_id', ForeignKey('tags.id'), primary_key=True))
56
+
57
+ sample_reports = Table(
58
+ 'sample_reports', Base.metadata,
59
+ Column('sample_id', ForeignKey('samples.id'), primary_key=True),
60
+ Column('report_id', ForeignKey('reports.id'), primary_key=True))
61
+
62
+ sample_records = Table(
63
+ 'sample_records', Base.metadata,
64
+ Column('sample_id', ForeignKey('samples.id'), primary_key=True),
65
+ Column('record_id', ForeignKey('records.id'), primary_key=True))
66
+
67
+ sample_comments = Table(
68
+ 'sample_comments', Base.metadata,
69
+ Column('sample_id', ForeignKey('samples.id'), primary_key=True),
70
+ Column('comment_id', ForeignKey('comments.id'), primary_key=True))
71
+
72
+ sample_transfer_comments = Table(
73
+ 'sample_transfer_comments', Base.metadata,
74
+ Column('transfer_id', ForeignKey('sample_transfer.id'), primary_key=True),
75
+ Column('comment_id', ForeignKey('comments.id'), primary_key=True))
76
+
77
+ report_comments = Table(
78
+ 'report_comments', Base.metadata,
79
+ Column('report_id', ForeignKey('reports.id'), primary_key=True),
80
+ Column('comment_id', ForeignKey('comments.id'), primary_key=True))
81
+
82
+ record_comments = Table(
83
+ 'record_comments', Base.metadata,
84
+ Column('record_id', ForeignKey('records.id'), primary_key=True),
85
+ Column('comment_id', ForeignKey('comments.id'), primary_key=True))
86
+
87
+
88
+ class Role(Base):
89
+ __tablename__ = 'roles'
90
+
91
+ id = Column(Integer, primary_key=True)
92
+ name = Column(String)
93
+
94
+ users = relationship('User', secondary=user_roles, back_populates='roles')
95
+
96
+ def __repr__(self):
97
+ return f"Role(name='{self.name}')"
98
+
99
+
100
+ class User(Base):
101
+ __tablename__ = 'users'
102
+
103
+ id = Column(Integer, primary_key=True)
104
+ name = Column(String, unique=True)
105
+ hashed_password = Column(LargeBinary(64))
106
+ fullname = Column(String)
107
+
108
+ roles = relationship('Role', secondary=user_roles, back_populates='users')
109
+ attachments = relationship('Attachment', back_populates='user')
110
+ comments = relationship('Comment', back_populates='user')
111
+
112
+ def setPassword(self, password):
113
+ self.hashed_password = encryptPassword(password)
114
+
115
+ def verify(self, password):
116
+ try:
117
+ verifyPassword(password, self.hashed_password)
118
+ return True
119
+ except InvalidKey:
120
+ return False
121
+
122
+ def __repr__(self):
123
+ return f"User(name='{self.name}')"
124
+
125
+
126
+ class ParameterEdge(Base):
127
+ __tablename__ = 'parameter_edges'
128
+ parent_id = Column(ForeignKey('parameters.id'), primary_key=True)
129
+ child_id = Column(ForeignKey('parameters.id'), primary_key=True)
130
+ key = Column(String(50), primary_key=True)
131
+
132
+
133
+ class Parameter(Base):
134
+ __tablename__ = 'parameters'
135
+
136
+ id = Column(Integer, primary_key=True)
137
+ type = Column(String)
138
+ unit = Column(String)
139
+ integer = Column(Integer)
140
+ real = Column(Float)
141
+ imag = Column(Float)
142
+ string = Column(String)
143
+ buff = Column(LargeBinary)
144
+
145
+ children = relationship("ParameterEdge",
146
+ foreign_keys=[ParameterEdge.parent_id],
147
+ backref="parent")
148
+ parents = relationship("ParameterEdge",
149
+ foreign_keys=[ParameterEdge.child_id],
150
+ backref="child")
151
+
152
+ @property
153
+ def value(self):
154
+ if self.type == 'integer':
155
+ return self.integer
156
+ elif self.type == 'real':
157
+ return self.real
158
+ elif self.type == 'complex':
159
+ return self.real + 1j * self.imag
160
+ elif self.type == 'string':
161
+ return self.string
162
+ elif self.type == 'buffer':
163
+ return self.buff
164
+ elif self.type == 'boolean':
165
+ return self.integer == 1
166
+ elif self.type is None or self.type == 'none':
167
+ return None
168
+ elif self.type == 'tree':
169
+ return self.export()
170
+ else:
171
+ return pickle.loads(self.buff)
172
+
173
+ @value.setter
174
+ def value(self, value):
175
+ self._set_value(value)
176
+
177
+ @singledispatchmethod
178
+ def _set_value(self, value):
179
+ self.buff = pickle.dumps(value)
180
+ self.type = 'pickle'
181
+
182
+ @_set_value.register
183
+ def _(self, value: int):
184
+ self.integer = value
185
+ self.type = 'integer'
186
+
187
+ @_set_value.register
188
+ def _(self, value: bool):
189
+ self.integer = int(value)
190
+ self.type = 'boolean'
191
+
192
+ @_set_value.register
193
+ def _(self, value: float):
194
+ self.real = value
195
+ self.type = 'real'
196
+
197
+ @_set_value.register
198
+ def _(self, value: complex):
199
+ self.real = value.real
200
+ self.imag = value.imag
201
+ self.type = 'complex'
202
+
203
+ @_set_value.register
204
+ def _(self, value: str):
205
+ self.string = value
206
+ self.type = 'string'
207
+
208
+ @_set_value.register
209
+ def _(self, value: bytes):
210
+ self.buff = value
211
+ self.type = 'buffer'
212
+
213
+ @_set_value.register
214
+ def _(self, value: None):
215
+ self.type = 'none'
216
+
217
+ def export(self):
218
+ if self.type == 'tree':
219
+ return {a.key: a.child.export() for a in self.children}
220
+ else:
221
+ return self.value
222
+
223
+
224
+ class Snapshot(Base):
225
+ __tablename__ = 'snapshots'
226
+
227
+ id = Column(Integer, primary_key=True)
228
+ root_id = Column(ForeignKey('parameters.id'))
229
+ previous_id = Column(Integer, ForeignKey('snapshots.id'))
230
+
231
+ followers = relationship("Snapshot",
232
+ backref=backref('previous', remote_side=[id]))
233
+
234
+ root = relationship('Parameter')
235
+ tags = relationship('Tag',
236
+ secondary=snapshot_tags,
237
+ back_populates='snapshots')
238
+
239
+ def export(self):
240
+ return self.root.export()
241
+
242
+
243
+ class ReportParameters(Base):
244
+ __tablename__ = 'report_parameters'
245
+ parent_id = Column(ForeignKey('reports.id'), primary_key=True)
246
+ child_id = Column(ForeignKey('parameters.id'), primary_key=True)
247
+ key = Column(String(50), primary_key=True)
248
+
249
+ parameter = relationship('Parameter')
250
+
251
+ @property
252
+ def value(self):
253
+ return self.parameter.value
254
+
255
+
256
+ class Tag(Base):
257
+ __tablename__ = 'tags'
258
+
259
+ id = Column(Integer, primary_key=True)
260
+ text = Column(String, unique=True)
261
+
262
+ comments = relationship('Comment',
263
+ secondary=comment_tags,
264
+ back_populates='tags')
265
+ records = relationship('Record',
266
+ secondary=record_tags,
267
+ back_populates='tags')
268
+ reports = relationship('Report',
269
+ secondary=report_tags,
270
+ back_populates='tags')
271
+ samples = relationship('Sample',
272
+ secondary=sample_tags,
273
+ back_populates='tags')
274
+ snapshots = relationship('Snapshot',
275
+ secondary=snapshot_tags,
276
+ back_populates='tags')
277
+
278
+ def __init__(self, text) -> None:
279
+ super().__init__()
280
+ self.text = text
281
+
282
+ def __repr__(self):
283
+ return f"Tag('{self.text}')"
284
+
285
+
286
+ class Comment(Base):
287
+ __tablename__ = 'comments'
288
+
289
+ id = Column(Integer, primary_key=True)
290
+ text = Column(String)
291
+ user_id = Column(Integer, ForeignKey('users.id'))
292
+ ctime = Column(DateTime, default=utcnow)
293
+ mtime = Column(DateTime, default=utcnow)
294
+ atime = Column(DateTime, default=utcnow)
295
+ parent_id = Column(Integer, ForeignKey('comments.id'))
296
+
297
+ replies = relationship("Comment", lazy="joined", join_depth=2)
298
+ user = relationship('User', back_populates='comments')
299
+ tags = relationship('Tag',
300
+ secondary=comment_tags,
301
+ back_populates='comments')
302
+ attachments = relationship('Attachment', back_populates='comment')
303
+
304
+
305
+ class Attachment(Base):
306
+ __tablename__ = 'attachments'
307
+
308
+ id = Column(Integer, primary_key=True)
309
+ filename = Column(String)
310
+ mime_type = Column(String, default='application/octet-stream')
311
+ user_id = Column(Integer, ForeignKey('users.id'))
312
+ comment_id = Column(Integer, ForeignKey('comments.id'))
313
+ ctime = Column(DateTime, default=utcnow)
314
+ mtime = Column(DateTime, default=utcnow)
315
+ atime = Column(DateTime, default=utcnow)
316
+ size = Column(Integer)
317
+ sha1 = Column(String)
318
+ description = Column(Text)
319
+
320
+ user = relationship('User', back_populates='attachments')
321
+ comment = relationship('Comment', back_populates='attachments')
322
+
323
+
324
+ class InputText(Base):
325
+ __tablename__ = 'inputs'
326
+
327
+ id = Column(Integer, primary_key=True)
328
+ hash = Column(LargeBinary(20))
329
+ text_field = Column(Text, unique=True)
330
+
331
+ @property
332
+ def text(self):
333
+ return self.text_field
334
+
335
+ @text.setter
336
+ def text(self, text):
337
+ self.hash = hashlib.sha1(text.encode('utf-8')).digest()
338
+ self.text_field = text
339
+
340
+ def __repr__(self) -> str:
341
+ return self.text
342
+
343
+
344
+ class Cell(Base):
345
+ __tablename__ = 'cells'
346
+
347
+ id = Column(Integer, primary_key=True)
348
+ notebook_id = Column(Integer, ForeignKey("notebooks.id"))
349
+ index = Column(Integer)
350
+ ctime = Column(DateTime, default=utcnow)
351
+ ftime = Column(DateTime, default=utcnow)
352
+ input_id = Column(Integer, ForeignKey("inputs.id"))
353
+
354
+ notebook = relationship("Notebook", back_populates="cells")
355
+ input = relationship("InputText")
356
+
357
+ def __repr__(self) -> str:
358
+ return str(f"Cell(index={self.index}, input='{self.input}')")
359
+
360
+
361
+ class Notebook(Base):
362
+ __tablename__ = 'notebooks'
363
+
364
+ id = Column(Integer, primary_key=True)
365
+ name = Column(String)
366
+ ctime = Column(DateTime, default=utcnow)
367
+ atime = Column(DateTime, default=utcnow)
368
+
369
+ cells = relationship("Cell",
370
+ order_by=Cell.index,
371
+ back_populates="notebook")
372
+
373
+
374
+ class Sample(Base):
375
+ __tablename__ = 'samples'
376
+
377
+ id = Column(Integer, primary_key=True)
378
+ name = Column(String)
379
+
380
+ account_id = Column(Integer, ForeignKey("sample_accounts.id"))
381
+
382
+ tags = relationship("Tag", secondary=sample_tags, back_populates="samples")
383
+ records = relationship("Record",
384
+ secondary=sample_records,
385
+ back_populates="samples")
386
+ reports = relationship("Report",
387
+ secondary=sample_reports,
388
+ back_populates="samples")
389
+ transfers = relationship("SampleTransfer",
390
+ order_by="SampleTransfer.ctime",
391
+ back_populates="sample")
392
+ account = relationship("SampleAccount", back_populates="samples")
393
+ comments = relationship("Comment", secondary=sample_comments)
394
+
395
+
396
+ class SampleAccountType(Base):
397
+ __tablename__ = 'sample_account_types'
398
+ id = Column(Integer, primary_key=True)
399
+ name = Column(String)
400
+ description = Column(String)
401
+
402
+ accounts = relationship("SampleAccount", back_populates="type")
403
+
404
+
405
+ class SampleAccount(Base):
406
+ __tablename__ = 'sample_accounts'
407
+
408
+ id = Column(Integer, primary_key=True)
409
+ name = Column(String)
410
+ type_id = Column(Integer, ForeignKey("sample_account_types.id"))
411
+ description = Column(String)
412
+
413
+ type = relationship("SampleAccountType", back_populates="accounts")
414
+
415
+ samples = relationship("Sample", back_populates="account")
416
+
417
+
418
+ class SampleTransfer(Base):
419
+ __tablename__ = 'sample_transfer'
420
+
421
+ id = Column(Integer, primary_key=True)
422
+ sample_id = Column(Integer, ForeignKey("samples.id"))
423
+ user_id = Column(Integer, ForeignKey("users.id"))
424
+ ctime = Column(DateTime, default=utcnow)
425
+ debtor_id = Column(Integer, ForeignKey("sample_accounts.id"))
426
+ creditor_id = Column(Integer, ForeignKey("sample_accounts.id"))
427
+
428
+ user = relationship("User")
429
+ sample = relationship("Sample", back_populates="transfers")
430
+ debtor = relationship("SampleAccount", foreign_keys=[debtor_id])
431
+ creditor = relationship("SampleAccount", foreign_keys=[creditor_id])
432
+ comments = relationship("Comment", secondary=sample_transfer_comments)
433
+
434
+
435
+ class Record(Base):
436
+ __tablename__ = 'records'
437
+
438
+ id = Column(Integer, primary_key=True)
439
+ ctime = Column(DateTime, default=utcnow)
440
+ mtime = Column(DateTime, default=utcnow)
441
+ atime = Column(DateTime, default=utcnow)
442
+ user_id = Column(Integer, ForeignKey('users.id'))
443
+ parent_id = Column(Integer, ForeignKey('records.id'))
444
+ cell_id = Column(Integer, ForeignKey('cells.id'))
445
+
446
+ app = Column(String)
447
+ file = Column(String)
448
+ key = Column(String)
449
+ config = Column(JSON)
450
+ task_hash = Column(LargeBinary(32))
451
+
452
+ parent = relationship("Record",
453
+ remote_side=[id],
454
+ back_populates="children")
455
+ children = relationship("Record",
456
+ remote_side=[parent_id],
457
+ back_populates="parent")
458
+
459
+ user = relationship("User")
460
+ samples = relationship("Sample",
461
+ secondary=sample_records,
462
+ back_populates="records")
463
+ cell = relationship("Cell")
464
+
465
+ reports = relationship('Report',
466
+ secondary=record_reports,
467
+ back_populates='records')
468
+ tags = relationship('Tag', secondary=record_tags, back_populates='records')
469
+ comments = relationship('Comment', secondary=record_comments)
470
+
471
+
472
+ class Report(Base):
473
+ __tablename__ = 'reports'
474
+
475
+ id = Column(Integer, primary_key=True)
476
+ ctime = Column(DateTime, default=utcnow)
477
+ mtime = Column(DateTime, default=utcnow)
478
+ atime = Column(DateTime, default=utcnow)
479
+ user_id = Column(Integer, ForeignKey('users.id'))
480
+
481
+ category = Column(String)
482
+ title = Column(String)
483
+ content = Column(Text)
484
+ file = Column(String)
485
+ key = Column(String)
486
+ task_hash = Column(LargeBinary(32))
487
+
488
+ user = relationship("User")
489
+ samples = relationship("Sample",
490
+ secondary=sample_reports,
491
+ back_populates="reports")
492
+
493
+ records = relationship('Record',
494
+ secondary=record_reports,
495
+ back_populates='reports')
496
+
497
+ tags = relationship('Tag', secondary=report_tags, back_populates='reports')
498
+ comments = relationship('Comment', secondary=report_comments)
499
+ _parameters = relationship('ReportParameters')
500
+
501
+
502
+ def create_tables(engine, tables_only=False):
503
+ Base.metadata.create_all(engine)
504
+ if tables_only:
505
+ return
506
+
507
+ sys_role = Role(name='sys')
508
+ kernel = User(name='BIG BROTHER')
509
+ kernel.roles.append(sys_role)
510
+
511
+ root_role = Role(name='root')
512
+ admin_role = Role(name='admin')
513
+ root_user = User(name='root')
514
+ root_user.setPassword('123')
515
+ root_user.roles.append(root_role)
516
+ root_user.roles.append(admin_role)
517
+
518
+ guest_role = Role(name='guest')
519
+ guest_user = User(name='guest')
520
+ guest_user.setPassword('')
521
+ guest_user.roles.append(guest_role)
522
+
523
+ t1 = SampleAccountType(name='factory')
524
+ t2 = SampleAccountType(name='destroyed')
525
+ t3 = SampleAccountType(name='storage')
526
+ t4 = SampleAccountType(name='fridge')
527
+ a = SampleAccount(name='destroyed')
528
+ a.type = t2
529
+
530
+ Session = sessionmaker(bind=engine)
531
+ session = Session()
532
+
533
+ session.add(root_user)
534
+ session.add(guest_user)
535
+ session.add(kernel)
536
+ session.add_all([t1, t2, t3, t4, a])
537
+ try:
538
+ session.commit()
539
+ except:
540
+ session.rollback()
qulab/scan/optimize.py ADDED
@@ -0,0 +1,69 @@
1
+ from typing import Any, Sequence
2
+
3
+ import nevergrad as ng
4
+ import numpy as np
5
+ from scipy.optimize import OptimizeResult
6
+
7
+
8
+ class NgOptimizer():
9
+
10
+ def __init__(self, variables, **kwds):
11
+ self._all_x, self._all_y = [], []
12
+ self.config = {
13
+ 'method': 'TBPSA',
14
+ 'budget': 100,
15
+ }
16
+ self.config.update(kwds)
17
+ instrum = []
18
+ self.dimensions = variables
19
+ for space in variables:
20
+
21
+ if space.transform_ == "normalize":
22
+ instrum.append(ng.p.Scalar(init=0.5, lower=0, upper=1))
23
+ else:
24
+ if space.prior == "log-uniform":
25
+ instrum.append(
26
+ ng.p.Log(init=None,
27
+ exponent=space.base,
28
+ lower=space.low,
29
+ upper=space.high))
30
+ else:
31
+ instrum.append(
32
+ ng.p.Scalar(init=None,
33
+ lower=space.low,
34
+ upper=space.high))
35
+ self.instrum = ng.p.Instrumentation(*instrum)
36
+ self.opt = getattr(ng.optimizers,
37
+ self.config['method'])(self.instrum,
38
+ budget=self.config['budget'])
39
+
40
+ def ask(self):
41
+ tmp = self.opt.ask()
42
+ return [
43
+ space.inverse_transform(x)
44
+ for x, space in zip(tmp.args, self.dimensions)
45
+ ]
46
+
47
+ def tell(self, suggested: Sequence, value: Any):
48
+ self._all_x.append(suggested)
49
+ self._all_y.append(value)
50
+ suggested = [
51
+ space.transform(x) for x, space in zip(suggested, self.dimensions)
52
+ ]
53
+ self.opt.suggest(*suggested)
54
+ x = self.opt.ask()
55
+ self.opt.tell(x, value)
56
+
57
+ def get_result(self, history: bool = False) -> OptimizeResult:
58
+ recommendation = self.opt.recommend()
59
+ ret = OptimizeResult({
60
+ 'x': [
61
+ space.inverse_transform(x)
62
+ for x, space in zip(recommendation.args, self.dimensions)
63
+ ]
64
+ })
65
+ if history:
66
+ ret.x_iters = self._all_x
67
+ ret.func_vals = self._all_y
68
+ ret.fun = recommendation.value
69
+ return ret