-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathtest_db_experiment_data.py
1205 lines (1002 loc) · 47.6 KB
/
test_db_experiment_data.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-docstring
"""Test ExperimentData."""
from test.base import QiskitExperimentsTestCase
import os
from unittest import mock
import copy
from random import randrange
import time
import threading
import json
import re
import uuid
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import numpy as np
from qiskit.providers.fake_provider import FakeMelbourneV2
from qiskit.result import Result
from qiskit.providers import JobV1 as Job
from qiskit.providers import JobStatus
from qiskit_ibm_experiment import IBMExperimentService
from qiskit_experiments.framework import ExperimentData
from qiskit_experiments.framework import AnalysisResult
from qiskit_experiments.framework import BackendData
from qiskit_experiments.database_service.exceptions import (
ExperimentDataError,
ExperimentEntryNotFound,
)
from qiskit_experiments.database_service.device_component import Qubit
from qiskit_experiments.framework.experiment_data import (
AnalysisStatus,
ExperimentStatus,
)
from qiskit_experiments.framework.matplotlib import get_non_gui_ax
class TestDbExperimentData(QiskitExperimentsTestCase):
"""Test the ExperimentData class."""
def setUp(self):
super().setUp()
self.backend = FakeMelbourneV2()
def test_db_experiment_data_attributes(self):
"""Test DB experiment data attributes."""
attrs = {
"job_ids": ["job1"],
"share_level": "public",
"figure_names": ["figure1"],
"notes": "some notes",
}
exp_data = ExperimentData(
backend=self.backend,
experiment_type="qiskit_test",
experiment_id="1234",
tags=["tag1", "tag2"],
metadata={"foo": "bar"},
**attrs,
)
self.assertEqual(exp_data.backend.name, self.backend.name)
self.assertEqual(exp_data.experiment_type, "qiskit_test")
self.assertEqual(exp_data.experiment_id, "1234")
self.assertEqual(exp_data.tags, ["tag1", "tag2"])
self.assertEqual(exp_data.metadata["foo"], "bar")
for key, val in attrs.items():
self.assertEqual(getattr(exp_data, key), val)
def test_add_data_dict(self):
"""Test add data in dictionary."""
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
a_dict = {"counts": {"01": 518}}
dicts = [{"counts": {"00": 284}}, {"counts": {"00": 14}}]
exp_data.add_data(a_dict)
exp_data.add_data(dicts)
self.assertEqual([a_dict] + dicts, exp_data.data())
def test_add_data_result(self):
"""Test add result data."""
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
a_result = self._get_job_result(1)
results = [self._get_job_result(2), self._get_job_result(3)]
expected = [a_result.get_counts()]
for res in results:
expected.extend(res.get_counts())
exp_data.add_data(a_result)
exp_data.add_data(results)
self.assertEqual(expected, [sdata["counts"] for sdata in exp_data.data()])
self.assertIn(a_result.job_id, exp_data.job_ids)
def test_add_data_result_metadata(self):
"""Test add result metadata."""
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
result1 = self._get_job_result(1, no_metadata=True)
result2 = self._get_job_result(1)
exp_data.add_data(result1)
exp_data.add_data(result2)
self.assertNotIn("metadata", exp_data.data(0))
self.assertIn("metadata", exp_data.data(1))
def test_add_data_job(self):
"""Test add job data."""
a_job = mock.create_autospec(Job, instance=True)
a_job.result.return_value = self._get_job_result(3)
num_circs = 3
jobs = []
for _ in range(2):
job = mock.create_autospec(Job, instance=True)
job.result.return_value = self._get_job_result(2, label_from=num_circs)
job.status.return_value = JobStatus.DONE
jobs.append(job)
num_circs = num_circs + 2
expected = a_job.result().get_counts()
for job in jobs:
expected.extend(job.result().get_counts())
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
exp_data.add_jobs(a_job)
self.assertExperimentDone(exp_data)
exp_data.add_jobs(jobs)
self.assertExperimentDone(exp_data)
self.assertEqual(
expected,
[
sdata["counts"]
for sdata in sorted(exp_data.data(), key=lambda x: x["metadata"]["label"])
],
)
self.assertIn(a_job.job_id(), exp_data.job_ids)
def test_add_data_job_callback(self):
"""Test add job data with callback."""
def _callback(_exp_data):
self.assertIsInstance(_exp_data, ExperimentData)
self.assertEqual(
[dat["counts"] for dat in _exp_data.data()], a_job.result().get_counts()
)
exp_data.add_figures(str.encode("hello world"))
res = mock.MagicMock()
res.result_id = str(uuid.uuid4())
exp_data.add_analysis_results(res)
nonlocal called_back
called_back = True
a_job = mock.create_autospec(Job, instance=True)
a_job.result.return_value = self._get_job_result(2)
a_job.status.return_value = JobStatus.DONE
called_back = False
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
exp_data.add_jobs(a_job)
exp_data.add_analysis_callback(_callback)
self.assertExperimentDone(exp_data)
self.assertTrue(called_back)
def test_add_data_callback(self):
"""Test add data with callback."""
def _callback(_exp_data):
self.assertIsInstance(_exp_data, ExperimentData)
nonlocal called_back_count, expected_data, subtests
expected_data.extend(subtests[called_back_count][1])
self.assertEqual([dat["counts"] for dat in _exp_data.data()], expected_data)
called_back_count += 1
a_result = self._get_job_result(1)
results = [self._get_job_result(1), self._get_job_result(1)]
a_dict = {"counts": {"01": 518}}
dicts = [{"counts": {"00": 284}}, {"counts": {"00": 14}}]
subtests = [
(a_result, [a_result.get_counts()]),
(results, [res.get_counts() for res in results]),
(a_dict, [a_dict["counts"]]),
(dicts, [dat["counts"] for dat in dicts]),
]
called_back_count = 0
expected_data = []
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
for data, _ in subtests:
with self.subTest(data=data):
exp_data.add_data(data)
exp_data.add_analysis_callback(_callback)
self.assertExperimentDone(exp_data)
self.assertEqual(len(subtests), called_back_count)
def test_add_data_job_callback_kwargs(self):
"""Test add job data with callback and additional arguments."""
def _callback(_exp_data, **kwargs):
self.assertIsInstance(_exp_data, ExperimentData)
self.assertEqual({"foo": callback_kwargs}, kwargs)
nonlocal called_back
called_back = True
a_job = mock.create_autospec(Job, instance=True)
a_job.result.return_value = self._get_job_result(2)
a_job.status.return_value = JobStatus.DONE
called_back = False
callback_kwargs = "foo"
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
exp_data.add_jobs(a_job)
exp_data.add_analysis_callback(_callback, foo=callback_kwargs)
self.assertExperimentDone(exp_data)
self.assertTrue(called_back)
def test_add_data_pending_post_processing(self):
"""Test add job data while post processing is still running."""
def _callback(_exp_data, **kwargs):
kwargs["event"].wait(timeout=3)
a_job = mock.create_autospec(Job, instance=True)
a_job.result.return_value = self._get_job_result(2)
a_job.status.return_value = JobStatus.DONE
event = threading.Event()
self.addCleanup(event.set)
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_analysis_callback(_callback, event=event)
exp_data.add_jobs(a_job)
with self.assertLogs("qiskit_experiments", "WARNING"):
exp_data.add_data({"foo": "bar"})
def test_get_data(self):
"""Test getting data."""
data1 = []
for _ in range(5):
data1.append({"counts": {"00": randrange(1024)}})
results = self._get_job_result(3)
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_data(data1)
exp_data.add_data(results)
self.assertEqual(data1[1], exp_data.data(1))
self.assertEqual(data1[2:4], exp_data.data(slice(2, 4)))
self.assertEqual(
results.get_counts(), [sdata["counts"] for sdata in exp_data.data(results.job_id)]
)
def test_add_figure(self):
"""Test adding a new figure."""
hello_bytes = str.encode("hello world")
file_name = uuid.uuid4().hex
self.addCleanup(os.remove, file_name)
with open(file_name, "wb") as file:
file.write(hello_bytes)
sub_tests = [
("file name", file_name, None),
("file bytes", hello_bytes, None),
("new name", hello_bytes, "hello_again.svg"),
]
for name, figure, figure_name in sub_tests:
with self.subTest(name=name):
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
fn = exp_data.add_figures(figure, figure_name)
self.assertEqual(hello_bytes, exp_data.figure(fn).figure)
def test_add_figure_plot(self):
"""Test adding a matplotlib figure."""
figure, ax = plt.subplots()
ax.plot([1, 2, 3])
service = self._set_mock_service()
exp_data = ExperimentData(
backend=self.backend, experiment_type="qiskit_test", service=service
)
exp_data.add_figures(figure, save_figure=True)
self.assertEqual(figure, exp_data.figure(0).figure)
service.create_or_update_figure.assert_called_once()
_, kwargs = service.create_or_update_figure.call_args
self.assertIsInstance(kwargs["figure"], bytes)
def test_add_figures(self):
"""Test adding multiple new figures."""
hello_bytes = [str.encode("hello world"), str.encode("hello friend")]
file_names = [uuid.uuid4().hex, uuid.uuid4().hex]
for idx, fn in enumerate(file_names):
self.addCleanup(os.remove, fn)
with open(fn, "wb") as file:
file.write(hello_bytes[idx])
sub_tests = [
("file names", file_names, None),
("file bytes", hello_bytes, None),
("new names", hello_bytes, ["hello1.svg", "hello2.svg"]),
]
for name, figures, figure_names in sub_tests:
with self.subTest(name=name):
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
added_names = exp_data.add_figures(figures, figure_names)
for idx, added_fn in enumerate(added_names):
self.assertEqual(hello_bytes[idx], exp_data.figure(added_fn).figure)
def test_add_figure_overwrite(self):
"""Test updating an existing figure."""
hello_bytes = str.encode("hello world")
friend_bytes = str.encode("hello friend!")
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
fn = exp_data.add_figures(hello_bytes)
# pylint: disable=no-member
fn_prefix = fn.rsplit(".", 1)[0]
# Without overwrite on, the filename should have an incrementing suffix
self.assertEqual(exp_data.add_figures(friend_bytes, fn), f"{fn_prefix}-1.svg")
self.assertEqual(
exp_data.add_figures([friend_bytes, friend_bytes], [fn, fn]),
[f"{fn_prefix}-2.svg", f"{fn_prefix}-3.svg"],
)
self.assertEqual(exp_data.add_figures(friend_bytes, fn, overwrite=True), fn)
self.assertEqual(friend_bytes, exp_data.figure(fn).figure)
self.assertEqual(
exp_data.add_figures(friend_bytes, f"{fn_prefix}-a.svg"), f"{fn_prefix}-a.svg"
)
def test_add_figure_save(self):
"""Test saving a figure in the database."""
hello_bytes = str.encode("hello world")
service = self._set_mock_service()
exp_data = ExperimentData(
backend=self.backend, experiment_type="qiskit_test", service=service
)
exp_data.add_figures(hello_bytes, save_figure=True)
service.create_or_update_figure.assert_called_once()
_, kwargs = service.create_or_update_figure.call_args
self.assertEqual(kwargs["figure"], hello_bytes)
self.assertEqual(kwargs["experiment_id"], exp_data.experiment_id)
def test_add_figure_metadata(self):
hello_bytes = str.encode("hello world")
qubits = [0, 1, 2]
exp_data = ExperimentData(
backend=self.backend,
experiment_type="qiskit_test",
metadata={"physical_qubits": qubits, "device_components": list(map(Qubit, qubits))},
)
exp_data.add_figures(hello_bytes)
exp_data.figure(0).metadata["foo"] = "bar"
figure_data = exp_data.figure(0)
self.assertEqual(figure_data.metadata["qubits"], qubits)
self.assertEqual(figure_data.metadata["device_components"], list(map(Qubit, qubits)))
self.assertEqual(figure_data.metadata["foo"], "bar")
expected_name_prefix = "qiskit_test_Q0_Q1_Q2_"
self.assertEqual(figure_data.name[: len(expected_name_prefix)], expected_name_prefix)
exp_data2 = ExperimentData(
backend=self.backend,
experiment_type="qiskit_test",
metadata={"physical_qubits": [1, 2, 3, 4]},
)
exp_data2.add_figures(figure_data, "new_name.svg")
figure_data = exp_data2.figure("new_name.svg")
# metadata should not change when adding to new ExperimentData
self.assertEqual(figure_data.metadata["qubits"], qubits)
self.assertEqual(figure_data.metadata["foo"], "bar")
# name should change
self.assertEqual(figure_data.name, "new_name.svg")
# can set the metadata to new dictionary
figure_data.metadata = {"bar": "foo"}
self.assertEqual(figure_data.metadata["bar"], "foo")
# cannot set the metadata to something other than dictionary
with self.assertRaises(ValueError):
figure_data.metadata = ["foo", "bar"]
def test_add_figure_bad_input(self):
"""Test adding figures with bad input."""
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
self.assertRaises(ValueError, exp_data.add_figures, ["foo", "bar"], ["name"])
def test_get_figure(self):
"""Test getting figure."""
exp_data = ExperimentData(experiment_type="qiskit_test")
figure_template = "hello world {}"
name_template = "figure_{}.svg"
name_template_wo_ext = "figure_{}"
for idx in range(3):
exp_data.add_figures(
str.encode(figure_template.format(idx)), figure_names=name_template.format(idx)
)
idx = randrange(3)
expected_figure = str.encode(figure_template.format(idx))
self.assertEqual(expected_figure, exp_data.figure(name_template.format(idx)).figure)
self.assertEqual(expected_figure, exp_data.figure(idx).figure)
# Check that figure will be returned without file extension in name
expected_figure = str.encode(figure_template.format(idx))
self.assertEqual(expected_figure, exp_data.figure(name_template_wo_ext.format(idx)).figure)
self.assertEqual(expected_figure, exp_data.figure(idx).figure)
file_name = uuid.uuid4().hex
self.addCleanup(os.remove, file_name)
exp_data.figure(idx, file_name)
with open(file_name, "rb") as file:
self.assertEqual(expected_figure, file.read())
def test_delete_figure(self):
"""Test deleting a figure."""
exp_data = ExperimentData(experiment_type="qiskit_test")
id_template = "figure_{}.svg"
for idx in range(3):
exp_data.add_figures(str.encode("hello world"), id_template.format(idx))
sub_tests = [(1, id_template.format(1)), (id_template.format(2), id_template.format(2))]
for del_key, figure_name in sub_tests:
with self.subTest(del_key=del_key):
exp_data.delete_figure(del_key)
self.assertRaises(ExperimentEntryNotFound, exp_data.figure, figure_name)
def test_delayed_backend(self):
"""Test initializing experiment data without a backend."""
exp_data = ExperimentData(experiment_type="qiskit_test")
self.assertIsNone(exp_data.backend)
exp_data.save_metadata()
a_job = mock.create_autospec(Job, instance=True)
exp_data.add_jobs(a_job)
self.assertIsNotNone(exp_data.backend)
def test_different_backend(self):
"""Test setting a different backend."""
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
a_job = mock.create_autospec(Job, instance=True)
self.assertNotEqual(exp_data.backend, a_job.backend())
with self.assertLogs("qiskit_experiments", "WARNING"):
exp_data.add_jobs(a_job)
def test_add_get_analysis_result(self):
"""Test adding and getting analysis results."""
exp_data = ExperimentData(experiment_type="qiskit_test")
results = []
result_ids = list(map(str, range(5)))
for idx in result_ids:
res = mock.MagicMock()
res.result_id = idx
results.append(res)
with self.assertWarns(UserWarning):
# This is invalid result ID string and cause a warning
exp_data.add_analysis_results(res)
# We cannot compare results with exp_data.analysis_results()
# This test is too hacky since it tris to compare MagicMock with AnalysisResult.
self.assertEqual(
[res.result_id for res in exp_data.analysis_results()],
result_ids,
)
self.assertEqual(
exp_data.analysis_results(1).result_id,
result_ids[1],
)
self.assertEqual(
[res.result_id for res in exp_data.analysis_results(slice(2, 4))],
result_ids[2:4],
)
def test_add_get_analysis_results(self):
"""Test adding and getting a list of analysis results."""
exp_data = ExperimentData(experiment_type="qiskit_test")
results = []
result_ids = list(map(str, range(5)))
for idx in result_ids:
res = mock.MagicMock()
res.result_id = idx
results.append(res)
with self.assertWarns(UserWarning):
# This is invalid result ID string and cause a warning
exp_data.add_analysis_results(results)
get_result_ids = [res.result_id for res in exp_data.analysis_results()]
# We cannot compare results with exp_data.analysis_results()
# This test is too hacky since it tris to compare MagicMock with AnalysisResult.
self.assertEqual(get_result_ids, result_ids)
def test_delete_analysis_result(self):
"""Test deleting analysis result."""
exp_data = ExperimentData(experiment_type="qiskit_test")
id_template = "result_{}"
for idx in range(3):
res = mock.MagicMock()
res.result_id = id_template.format(idx)
with self.assertWarns(UserWarning):
# This is invalid result ID string and cause a warning
exp_data.add_analysis_results(res)
subtests = [(0, id_template.format(0)), (id_template.format(2), id_template.format(2))]
for del_key, res_id in subtests:
with self.subTest(del_key=del_key):
exp_data.delete_analysis_result(del_key)
self.assertRaises(ExperimentEntryNotFound, exp_data.analysis_results, res_id)
def test_save_metadata(self):
"""Test saving experiment metadata."""
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
service = mock.create_autospec(IBMExperimentService, instance=True)
exp_data.service = service
exp_data.save_metadata()
service.create_or_update_experiment.assert_called_once()
data = service.create_or_update_experiment.call_args[0][0]
self.assertEqual(exp_data.experiment_id, data.experiment_id)
def test_save(self):
"""Test saving all experiment related data."""
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
service = mock.create_autospec(IBMExperimentService, instance=True)
exp_data.add_figures(str.encode("hello world"))
analysis_result = mock.MagicMock()
analysis_result.result_id = str(uuid.uuid4())
exp_data.add_analysis_results(analysis_result)
exp_data.service = service
exp_data.save()
service.create_or_update_experiment.assert_called_once()
service.create_figures.assert_called_once()
service.create_analysis_results.assert_called_once()
def test_save_delete(self):
"""Test saving all deletion."""
exp_data = ExperimentData(backend=self.backend, experiment_type="qiskit_test")
service = mock.create_autospec(IBMExperimentService, instance=True)
exp_data.add_figures(str.encode("hello world"))
res = mock.MagicMock()
res.result_id = str(uuid.uuid4())
exp_data.add_analysis_results()
exp_data.delete_analysis_result(0)
exp_data.delete_figure(0)
exp_data.service = service
exp_data.save()
service.create_or_update_experiment.assert_called_once()
service.delete_figure.assert_called_once()
service.delete_analysis_result.assert_called_once()
def test_set_service_direct(self):
"""Test setting service directly."""
exp_data = ExperimentData(experiment_type="qiskit_test")
self.assertIsNone(exp_data.service)
mock_service = mock.MagicMock()
exp_data.service = mock_service
self.assertEqual(mock_service, exp_data.service)
with self.assertRaises(ExperimentDataError):
exp_data.service = mock_service
def test_auto_save(self):
"""Test auto save."""
service = self._set_mock_service()
exp_data = ExperimentData(
backend=self.backend, experiment_type="qiskit_test", service=service
)
exp_data.auto_save = True
mock_result = mock.MagicMock()
mock_result.result_id = str(uuid.uuid4())
subtests = [
# update function, update parameters, service called
(exp_data.add_analysis_results, (mock_result,), mock_result.save),
(exp_data.add_figures, (str.encode("hello world"),), service.create_or_update_figure),
(exp_data.delete_figure, (0,), service.delete_figure),
(exp_data.delete_analysis_result, (0,), service.delete_analysis_result),
(setattr, (exp_data, "tags", ["foo"]), service.create_or_update_experiment),
(setattr, (exp_data, "notes", "foo"), service.create_or_update_experiment),
(setattr, (exp_data, "share_level", "hub"), service.create_or_update_experiment),
]
for func, params, called in subtests:
with self.subTest(func=func):
func(*params)
if called:
called.assert_called_once()
service.reset_mock()
def test_status_job_pending(self):
"""Test experiment status when job is pending."""
job1 = mock.create_autospec(Job, instance=True)
job1.result.return_value = self._get_job_result(3)
job1.status.return_value = JobStatus.DONE
event = threading.Event()
job2 = mock.create_autospec(Job, instance=True)
job2.result = lambda *args, **kwargs: event.wait(timeout=15)
job2.status = lambda: JobStatus.CANCELLED if event.is_set() else JobStatus.RUNNING
self.addCleanup(event.set)
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_jobs(job1)
exp_data.add_jobs(job2)
exp_data.add_analysis_callback(lambda *args, **kwargs: event.wait(timeout=15))
self.assertEqual(ExperimentStatus.RUNNING, exp_data.status())
self.assertEqual(JobStatus.RUNNING, exp_data.job_status())
self.assertEqual(AnalysisStatus.QUEUED, exp_data.analysis_status())
# Cleanup
with self.assertLogs("qiskit_experiments", "WARNING"):
event.set()
exp_data.block_for_results()
def test_status_job_error(self):
"""Test experiment status when job failed."""
job1 = mock.create_autospec(Job, instance=True)
job1.result.return_value = self._get_job_result(3)
job1.status.return_value = JobStatus.DONE
job2 = mock.create_autospec(Job, instance=True)
job2.status.return_value = JobStatus.ERROR
exp_data = ExperimentData(experiment_type="qiskit_test")
with self.assertLogs(logger="qiskit_experiments.framework", level="WARN") as cm:
exp_data.add_jobs([job1, job2])
self.assertIn("Adding a job from a backend", ",".join(cm.output))
self.assertEqual(ExperimentStatus.ERROR, exp_data.status())
def test_status_post_processing(self):
"""Test experiment status during post processing."""
job = mock.create_autospec(Job, instance=True)
job.result.return_value = self._get_job_result(3)
job.status.return_value = JobStatus.DONE
event = threading.Event()
self.addCleanup(event.set)
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_jobs(job)
exp_data.add_analysis_callback((lambda *args, **kwargs: event.wait(timeout=15)))
status = exp_data.status()
self.assertEqual(ExperimentStatus.POST_PROCESSING, status)
def test_status_cancelled_analysis(self):
"""Test experiment status during post processing."""
job = mock.create_autospec(Job, instance=True)
job.result.return_value = self._get_job_result(3)
job.status.return_value = JobStatus.DONE
event = threading.Event()
self.addCleanup(event.set)
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_jobs(job)
exp_data.add_analysis_callback((lambda *args, **kwargs: event.wait(timeout=2)))
# Add second callback because the first can't be cancelled once it has started
exp_data.add_analysis_callback((lambda *args, **kwargs: event.wait(timeout=20)))
exp_data.cancel_analysis()
status = exp_data.status()
self.assertEqual(ExperimentStatus.CANCELLED, status)
def test_status_post_processing_error(self):
"""Test experiment status when post processing failed."""
def _post_processing(*args, **kwargs):
raise ValueError("Kaboom!")
job = mock.create_autospec(Job, instance=True)
job.result.return_value = self._get_job_result(3)
job.status.return_value = JobStatus.DONE
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_jobs(job)
with self.assertLogs(logger="qiskit_experiments.framework", level="WARN") as cm:
exp_data.add_jobs(job)
exp_data.add_analysis_callback(_post_processing)
exp_data.block_for_results()
self.assertEqual(ExperimentStatus.ERROR, exp_data.status())
self.assertIn("Kaboom!", ",".join(cm.output))
def test_status_done(self):
"""Test experiment status when all jobs are done."""
job = mock.create_autospec(Job, instance=True)
job.result.return_value = self._get_job_result(3)
job.status.return_value = JobStatus.DONE
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_jobs(job)
exp_data.add_jobs(job)
self.assertExperimentDone(exp_data)
self.assertEqual(ExperimentStatus.DONE, exp_data.status())
def test_set_tags(self):
"""Test updating experiment tags."""
exp_data = ExperimentData(experiment_type="qiskit_test", tags=["foo"])
self.assertEqual(["foo"], exp_data.tags)
exp_data.tags = ["bar"]
self.assertEqual(["bar"], exp_data.tags)
def test_cancel_jobs(self):
"""Test canceling experiment jobs."""
event = threading.Event()
cancel_count = 0
def _job_result():
event.wait(timeout=15)
raise ValueError("Job was cancelled.")
def _job_cancel():
nonlocal cancel_count
cancel_count += 1
event.set()
exp_data = ExperimentData(experiment_type="qiskit_test")
event = threading.Event()
self.addCleanup(event.set)
job = mock.create_autospec(Job, instance=True)
job.job_id.return_value = "1234"
job.cancel = _job_cancel
job.result = _job_result
job.status = lambda: JobStatus.CANCELLED if event.is_set() else JobStatus.RUNNING
exp_data.add_jobs(job)
with self.assertLogs("qiskit_experiments", "WARNING"):
exp_data.cancel_jobs()
self.assertEqual(cancel_count, 1)
self.assertEqual(exp_data.job_status(), JobStatus.CANCELLED)
self.assertEqual(exp_data.status(), ExperimentStatus.CANCELLED)
def test_cancel_analysis(self):
"""Test canceling experiment analysis."""
event = threading.Event()
self.addCleanup(event.set)
def _job_result():
event.wait(timeout=15)
return self._get_job_result(1)
def _analysis(*args): # pylint: disable = unused-argument
event.wait(timeout=15)
job = mock.create_autospec(Job, instance=True)
job.job_id.return_value = "1234"
job.result = _job_result
job.status = lambda: JobStatus.DONE if event.is_set() else JobStatus.RUNNING
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_jobs(job)
exp_data.add_analysis_callback(_analysis)
exp_data.cancel_analysis()
# Test status while job still running
self.assertEqual(exp_data.job_status(), JobStatus.RUNNING)
self.assertEqual(exp_data.analysis_status(), AnalysisStatus.CANCELLED)
self.assertEqual(exp_data.status(), ExperimentStatus.RUNNING)
# Test status after job finishes
event.set()
self.assertEqual(exp_data.job_status(), JobStatus.DONE)
self.assertEqual(exp_data.analysis_status(), AnalysisStatus.CANCELLED)
self.assertEqual(exp_data.status(), ExperimentStatus.CANCELLED)
def test_completion_times(self):
"""Test the completion_times property"""
jid = "1234"
job = mock.create_autospec(Job, instance=True)
job.job_id.return_value = jid
job.status = JobStatus.DONE
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_jobs(job)
completion_times = exp_data.completion_times
self.assertTrue(jid in completion_times)
self.assertTrue(isinstance(completion_times[jid], datetime))
def test_partial_cancel_analysis(self):
"""Test canceling experiment analysis."""
event = threading.Event()
self.addCleanup(event.set)
run_analysis = []
def _job_result():
event.wait(timeout=3)
return self._get_job_result(1)
def _analysis(expdata, name=None, timeout=0): # pylint: disable = unused-argument
event.wait(timeout=timeout)
run_analysis.append(name)
job = mock.create_autospec(Job, instance=True)
job.job_id.return_value = "1234"
job.result = _job_result
job.status = lambda: JobStatus.DONE if event.is_set() else JobStatus.RUNNING
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_jobs(job)
exp_data.add_analysis_callback(_analysis, name=1, timeout=1)
exp_data.add_analysis_callback(_analysis, name=2, timeout=30)
cancel_id = exp_data._analysis_callbacks.keys()[-1]
exp_data.add_analysis_callback(_analysis, name=3, timeout=1)
consequent_cancel_id = exp_data._analysis_callbacks.keys()[-1]
exp_data.cancel_analysis(cancel_id)
# Test status while job is still running
self.assertEqual(exp_data.job_status(), JobStatus.RUNNING)
self.assertEqual(exp_data.analysis_status(), AnalysisStatus.CANCELLED)
self.assertEqual(exp_data.status(), ExperimentStatus.RUNNING)
# Test status after job finishes
event.set()
self.assertEqual(exp_data.job_status(), JobStatus.DONE)
self.assertEqual(exp_data.analysis_status(), AnalysisStatus.CANCELLED)
self.assertEqual(exp_data.status(), ExperimentStatus.CANCELLED)
# Check that correct analysis callback was cancelled
exp_data.block_for_results()
self.assertEqual(run_analysis, [1])
for cid, analysis in exp_data._analysis_callbacks.items():
if cid in [cancel_id, consequent_cancel_id]:
self.assertEqual(analysis.status, AnalysisStatus.CANCELLED)
else:
self.assertEqual(analysis.status, AnalysisStatus.DONE)
def test_cancel(self):
"""Test canceling experiment jobs and analysis."""
event = threading.Event()
self.addCleanup(event.set)
def _job_result():
event.wait(timeout=15)
raise ValueError("Job was cancelled.")
def _analysis(*args): # pylint: disable = unused-argument
event.wait(timeout=15)
def _status():
if event.is_set():
return JobStatus.CANCELLED
return JobStatus.RUNNING
job = mock.create_autospec(Job, instance=True)
job.job_id.return_value = "1234"
job.result = _job_result
job.cancel = event.set
job.status = _status
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_jobs(job)
exp_data.add_analysis_callback(_analysis)
exp_data.cancel()
# Test status while job still running
self.assertEqual(exp_data.job_status(), JobStatus.CANCELLED)
self.assertEqual(exp_data.analysis_status(), AnalysisStatus.CANCELLED)
self.assertEqual(exp_data.status(), ExperimentStatus.CANCELLED)
def test_add_jobs_timeout(self):
"""Test timeout kwarg of add_jobs"""
event = threading.Event()
self.addCleanup(event.set)
def _job_result():
event.wait(timeout=15)
raise ValueError("Job was cancelled.")
job = mock.create_autospec(Job, instance=True)
job.job_id.return_value = "1234"
job.result = _job_result
job.cancel = event.set
job.status = lambda: JobStatus.CANCELLED if event.is_set() else JobStatus.RUNNING
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_jobs(job, timeout=0.5)
with self.assertLogs("qiskit_experiments", "WARNING"):
exp_data.block_for_results()
self.assertEqual(exp_data.job_status(), JobStatus.CANCELLED)
self.assertEqual(exp_data.status(), ExperimentStatus.CANCELLED)
def test_metadata_serialization(self):
"""Test experiment metadata serialization."""
metadata = {"complex": 2 + 3j, "numpy": np.zeros(2)}
exp_data = ExperimentData(experiment_type="qiskit_test", metadata=metadata)
serialized = json.dumps(exp_data.metadata, cls=exp_data._json_encoder)
self.assertIsInstance(serialized, str)
self.assertTrue(json.loads(serialized))
deserialized = json.loads(serialized, cls=exp_data._json_decoder)
self.assertEqual(metadata["complex"], deserialized["complex"])
self.assertEqual(metadata["numpy"].all(), deserialized["numpy"].all())
def test_errors(self):
"""Test getting experiment error message."""
def _post_processing(*args, **kwargs): # pylint: disable=unused-argument
raise ValueError("Kaboom!")
job1 = mock.create_autospec(Job, instance=True)
job1.job_id.return_value = "1234"
job1.status.return_value = JobStatus.DONE
job2 = mock.create_autospec(Job, instance=True)
job2.status.return_value = JobStatus.ERROR
job2.job_id.return_value = "5678"
exp_data = ExperimentData(experiment_type="qiskit_test")
with self.assertLogs(logger="qiskit_experiments.framework", level="WARN") as cm:
exp_data.add_jobs(job1)
exp_data.add_analysis_callback(_post_processing)
exp_data.add_jobs(job2)
exp_data.block_for_results()
self.assertEqual(ExperimentStatus.ERROR, exp_data.status())
self.assertIn("Kaboom", ",".join(cm.output))
self.assertTrue(re.match(r".*5678.*Kaboom!", exp_data.errors(), re.DOTALL))
def test_simple_methods_from_callback(self):
"""Test that simple methods used in call back function don't hang
This test runs through many of the public methods of ExperimentData
from analysis callbacks to make sure that they do not raise exceptions
or hang the analysis thread. Hangs have occurred in the past when one
of these methods blocks waiting for analysis to complete.
These methods are not tested because they explicitly assume they are
run from the main thread:
+ copy
+ block_for_results
These methods are not tested because they require additional setup.
They could be tested in separate tests:
+ save
+ save_metadata
+ add_jobs
+ cancel
+ cancel_analysis
+ cancel_jobs
"""
def callback1(exp_data):
"""Callback function that call add_analysis_callback"""
exp_data.add_analysis_callback(callback2)
result = AnalysisResult("result_name", 0, [Qubit(0)], "experiment_id")
exp_data.add_analysis_results(result)
figure = get_non_gui_ax().get_figure()
exp_data.add_figures(figure, "figure.svg")
exp_data.add_data({"key": 1.2})
exp_data.data()
def callback2(exp_data):
"""Callback function that exercises status lookups"""
exp_data.figure("figure.svg")
exp_data.jobs()
exp_data.analysis_results("result_name", block=False)
exp_data.delete_figure("figure.svg")
exp_data.delete_analysis_result("result_name")
exp_data.status()
exp_data.job_status()
exp_data.analysis_status()
exp_data.errors()
exp_data.job_errors()
exp_data.analysis_errors()
exp_data = ExperimentData(experiment_type="qiskit_test")
exp_data.add_analysis_callback(callback1)
exp_data.block_for_results(timeout=3)
self.assertEqual(exp_data.analysis_status(), AnalysisStatus.DONE)
def test_recursive_callback_raises(self):
"""Test handling of excepting callbacks"""