-
Notifications
You must be signed in to change notification settings - Fork 127
/
experiment_data.py
2931 lines (2513 loc) · 114 KB
/
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.
"""
Experiment Data class
"""
from __future__ import annotations
import logging
import re
from typing import Dict, Optional, List, Union, Any, Callable, Tuple, TYPE_CHECKING
from datetime import datetime, timezone
from concurrent import futures
from functools import wraps
from collections import deque, defaultdict
import contextlib
import copy
import uuid
import time
import sys
import json
import traceback
import warnings
import numpy as np
import pandas as pd
from dateutil import tz
from matplotlib import pyplot
from qiskit.result import Result
from qiskit.providers.jobstatus import JobStatus, JOB_FINAL_STATES
from qiskit.exceptions import QiskitError
from qiskit.providers import Job, Backend
from qiskit.utils.deprecation import deprecate_arg
from qiskit.primitives import BitArray, SamplerPubResult, BasePrimitiveJob
from qiskit_ibm_experiment import (
IBMExperimentService,
ExperimentData as ExperimentDataclass,
AnalysisResultData as AnalysisResultDataclass,
ResultQuality,
)
from qiskit_experiments.framework.json import ExperimentEncoder, ExperimentDecoder
from qiskit_experiments.database_service.utils import (
plot_to_svg_bytes,
ThreadSafeOrderedDict,
ThreadSafeList,
)
from qiskit_experiments.database_service.device_component import to_component, DeviceComponent
from qiskit_experiments.framework.analysis_result import AnalysisResult
from qiskit_experiments.framework.analysis_result_data import AnalysisResultData
from qiskit_experiments.framework.analysis_result_table import AnalysisResultTable
from qiskit_experiments.framework import BackendData
from qiskit_experiments.framework.containers import ArtifactData
from qiskit_experiments.framework import ExperimentStatus, AnalysisStatus, AnalysisCallback
from qiskit_experiments.framework.package_deps import qiskit_version
from qiskit_experiments.database_service.exceptions import (
ExperimentDataError,
ExperimentEntryNotFound,
ExperimentDataSaveFailed,
)
from qiskit_experiments.database_service.utils import objs_to_zip, zip_to_objs
from .containers.figure_data import FigureData, FigureType
if TYPE_CHECKING:
# There is a cyclical dependency here, but the name needs to exist for
# Sphinx on Python 3.9+ to link type hints correctly. The gating on
# `TYPE_CHECKING` means that the import will never be resolved by an actual
# interpreter, only static analysis.
from . import BaseExperiment
from qiskit.providers import Provider
LOG = logging.getLogger(__name__)
def do_auto_save(func: Callable):
"""Decorate the input function to auto save data."""
@wraps(func)
def _wrapped(self, *args, **kwargs):
return_val = func(self, *args, **kwargs)
if self.auto_save:
self.save_metadata()
return return_val
return _wrapped
def utc_to_local(utc_dt: datetime) -> datetime:
"""Convert input UTC timestamp to local timezone.
Args:
utc_dt: Input UTC timestamp.
Returns:
A ``datetime`` with the local timezone.
"""
if utc_dt is None:
return None
local_dt = utc_dt.astimezone(tz.tzlocal())
return local_dt
def local_to_utc(local_dt: datetime) -> datetime:
"""Convert input local timezone timestamp to UTC timezone.
Args:
local_dt: Input local timestamp.
Returns:
A ``datetime`` with the UTC timezone.
"""
if local_dt is None:
return None
utc_dt = local_dt.astimezone(tz.UTC)
return utc_dt
def parse_utc_datetime(dt_str: str) -> datetime:
"""Parses UTC datetime from a string"""
if dt_str is None:
return None
db_datetime_format = "%Y-%m-%dT%H:%M:%S.%fZ"
dt_utc = datetime.strptime(dt_str, db_datetime_format)
dt_utc = dt_utc.replace(tzinfo=timezone.utc)
return dt_utc
class ExperimentData:
"""Experiment data container class.
.. note::
Saving experiment data to the cloud database is currently a limited access feature. You can
check whether you have access by logging into the IBM Quantum interface
and seeing if you can see the `database <https://quantum.ibm.com/experiments>`__.
This class handles the following:
1. Storing the data related to an experiment: raw data, metadata, analysis results,
and figures
2. Managing jobs and adding data from jobs automatically
3. Saving and loading data from the database service
The field ``db_data`` is a dataclass (``ExperimentDataclass``) containing
all the data that can be stored in the database and loaded from it, and
as such is subject to strict conventions.
Other data fields can be added and used freely, but they won't be saved
to the database.
"""
_metadata_version = 1
_job_executor = futures.ThreadPoolExecutor()
_json_encoder = ExperimentEncoder
_json_decoder = ExperimentDecoder
_metadata_filename = "metadata.json"
_max_workers_cap = 10
def __init__(
self,
experiment: Optional["BaseExperiment"] = None,
backend: Optional[Backend] = None,
service: Optional[IBMExperimentService] = None,
provider: Optional[Provider] = None,
parent_id: Optional[str] = None,
job_ids: Optional[List[str]] = None,
child_data: Optional[List[ExperimentData]] = None,
verbose: Optional[bool] = True,
db_data: Optional[ExperimentDataclass] = None,
start_datetime: Optional[datetime] = None,
**kwargs,
):
"""Initialize experiment data.
Args:
experiment: Experiment object that generated the data.
backend: Backend the experiment runs on. This overrides the
backend in the experiment object.
service: The service that stores the experiment results to the database
provider: The provider used for the experiments
(can be used to automatically obtain the service)
parent_id: ID of the parent experiment data
in the setting of a composite experiment
job_ids: IDs of jobs submitted for the experiment.
child_data: List of child experiment data.
verbose: Whether to print messages.
db_data: A prepared ExperimentDataclass of the experiment info.
This overrides other db parameters.
start_datetime: The time when the experiment started running.
If none, defaults to the current time.
Additional info:
In order to save the experiment data to the cloud service, the class
needs access to the experiment service provider. It can be obtained
via three different methods, given here by priority:
1. Passing it directly via the ``service`` parameter.
2. Implicitly obtaining it from the ``provider`` parameter.
3. Implicitly obtaining it from the ``backend`` parameter, using that backend's provider.
"""
if experiment is not None:
backend = backend or experiment.backend
experiment_type = experiment.experiment_type
else:
# Don't use None since the resultDB won't accept that
experiment_type = ""
if job_ids is None:
job_ids = []
self._experiment = experiment
# data stored in the database
metadata = {}
if experiment is not None:
metadata = copy.deepcopy(experiment._metadata())
source = metadata.pop(
"_source",
{
"class": f"{self.__class__.__module__}.{self.__class__.__name__}",
"metadata_version": self.__class__._metadata_version,
"qiskit_version": qiskit_version(),
},
)
metadata["_source"] = source
experiment_id = kwargs.get("experiment_id", str(uuid.uuid4()))
if db_data is None:
self._db_data = ExperimentDataclass(
experiment_id=experiment_id,
experiment_type=experiment_type,
parent_id=parent_id,
job_ids=job_ids,
metadata=metadata,
)
else:
self._db_data = db_data
if self.start_datetime is None:
if start_datetime is None:
start_datetime = datetime.now()
self.start_datetime = start_datetime
for key, value in kwargs.items():
if hasattr(self._db_data, key):
setattr(self._db_data, key, value)
else:
LOG.warning("Key '%s' not stored in the database", key)
# general data related
self._backend = None
if backend is not None:
self._set_backend(backend, recursive=False)
self.provider = provider
if provider is None and backend is not None:
self.provider = backend.provider
self._service = service
if self._service is None and self.provider is not None:
self._service = self.get_service_from_provider(self.provider)
if self._service is None and self.provider is None and self.backend is not None:
self._service = self.get_service_from_backend(self.backend)
self._auto_save = False
self._created_in_db = False
self._extra_data = kwargs
self.verbose = verbose
# job handling related
self._jobs = ThreadSafeOrderedDict(job_ids)
self._job_futures = ThreadSafeOrderedDict()
self._running_time = None
self._analysis_callbacks = ThreadSafeOrderedDict()
self._analysis_futures = ThreadSafeOrderedDict()
# Set 2 workers for analysis executor so there can be 1 actively running
# future and one waiting "running" future. This is to allow the second
# future to be cancelled without waiting for the actively running future
# to finish first.
self._analysis_executor = futures.ThreadPoolExecutor(max_workers=2)
self._monitor_executor = futures.ThreadPoolExecutor()
# data storage
self._result_data = ThreadSafeList()
self._figures = ThreadSafeOrderedDict(self._db_data.figure_names)
self._analysis_results = AnalysisResultTable()
self._artifacts = ThreadSafeOrderedDict()
self._deleted_figures = deque()
self._deleted_analysis_results = deque()
self._deleted_artifacts = set() # for holding unique artifact names to be deleted
# Child related
# Add component data and set parent ID to current container
self._child_data = ThreadSafeOrderedDict()
if child_data is not None:
self._set_child_data(child_data)
# Getters/setters for experiment metadata
@property
def experiment(self):
"""Return the experiment for this data.
Returns:
BaseExperiment: the experiment object.
"""
return self._experiment
@property
def completion_times(self) -> Dict[str, datetime]:
"""Returns the completion times of the jobs."""
job_times = {}
for job_id, job in self._jobs.items():
if job is not None:
if hasattr(job, "time_per_step") and "COMPLETED" in job.time_per_step():
job_times[job_id] = job.time_per_step().get("COMPLETED")
elif (
execution := job.result().metadata.get("execution")
) and "execution_spans" in execution:
job_times[job_id] = execution["execution_spans"].stop
elif (client := getattr(job, "_api_client", None)) and hasattr(
client, "job_metadata"
):
metadata = client.job_metadata(job.job_id())
finished = metadata.get("timestamps", {}).get("finished", {})
if finished:
job_times[job_id] = datetime.fromisoformat(finished)
if job_id not in job_times:
warnings.warn(
"Could not determine job completion time. Using current timestamp.",
UserWarning,
)
job_times[job_id] = datetime.now()
return job_times
@property
def tags(self) -> List[str]:
"""Return tags assigned to this experiment data.
Returns:
A list of tags assigned to this experiment data.
"""
return self._db_data.tags
@tags.setter
def tags(self, new_tags: List[str]) -> None:
"""Set tags for this experiment."""
if not isinstance(new_tags, list):
raise ExperimentDataError(f"The `tags` field of {type(self).__name__} must be a list.")
self._db_data.tags = np.unique(new_tags).tolist()
if self.auto_save:
self.save_metadata()
@property
def metadata(self) -> Dict:
"""Return experiment metadata.
Returns:
Experiment metadata.
"""
return self._db_data.metadata
@property
def creation_datetime(self) -> datetime:
"""Return the creation datetime of this experiment data.
Returns:
The timestamp when this experiment data was saved to the cloud service
in the local timezone.
"""
return self._db_data.creation_datetime
@property
def start_datetime(self) -> datetime:
"""Return the start datetime of this experiment data.
Returns:
The timestamp when this experiment began running in the local timezone.
"""
return self._db_data.start_datetime
@start_datetime.setter
def start_datetime(self, new_start_datetime: datetime) -> None:
self._db_data.start_datetime = new_start_datetime
@property
def updated_datetime(self) -> datetime:
"""Return the update datetime of this experiment data.
Returns:
The timestamp when this experiment data was last updated in the service
in the local timezone.
"""
return self._db_data.updated_datetime
@property
def running_time(self) -> datetime:
"""Return the running time of this experiment data.
The running time is the time the latest successful job started running on
the remote quantum machine. This can change as more jobs finish.
"""
return self._running_time
@property
def end_datetime(self) -> datetime:
"""Return the end datetime of this experiment data.
The end datetime is the time the latest job data was
added without errors; this can change as more jobs finish.
Returns:
The timestamp when the last job of this experiment finished
in the local timezone.
"""
return self._db_data.end_datetime
@end_datetime.setter
def end_datetime(self, new_end_datetime: datetime) -> None:
self._db_data.end_datetime = new_end_datetime
@property
def hub(self) -> str:
"""Return the hub of this experiment data.
Returns:
The hub of this experiment data.
"""
return self._db_data.hub
@property
def group(self) -> str:
"""Return the group of this experiment data.
Returns:
The group of this experiment data.
"""
return self._db_data.group
@property
def project(self) -> str:
"""Return the project of this experiment data.
Returns:
The project of this experiment data.
"""
return self._db_data.project
@property
def experiment_id(self) -> str:
"""Return experiment ID
Returns:
Experiment ID.
"""
return self._db_data.experiment_id
@property
def experiment_type(self) -> str:
"""Return experiment type
Returns:
Experiment type.
"""
return self._db_data.experiment_type
@experiment_type.setter
def experiment_type(self, new_type: str) -> None:
"""Sets the parent id"""
self._db_data.experiment_type = new_type
@property
def parent_id(self) -> str:
"""Return parent experiment ID
Returns:
Parent ID.
"""
return self._db_data.parent_id
@parent_id.setter
def parent_id(self, new_id: str) -> None:
"""Sets the parent id"""
self._db_data.parent_id = new_id
@property
def job_ids(self) -> List[str]:
"""Return experiment job IDs.
Returns: IDs of jobs submitted for this experiment.
"""
return self._db_data.job_ids
@property
def figure_names(self) -> List[str]:
"""Return names of the figures associated with this experiment.
Returns:
Names of figures associated with this experiment.
"""
return self._db_data.figure_names
@property
def share_level(self) -> str:
"""Return the share level for this experiment
Returns:
Experiment share level.
"""
return self._db_data.share_level
@share_level.setter
def share_level(self, new_level: str) -> None:
"""Set the experiment share level,
to this experiment itself and its descendants.
Args:
new_level: New experiment share level. Valid share levels are provider-
specified. For example, IBM Quantum experiment service allows
"public", "hub", "group", "project", and "private".
"""
self._db_data.share_level = new_level
for data in self._child_data.values():
original_auto_save = data.auto_save
data.auto_save = False
data.share_level = new_level
data.auto_save = original_auto_save
if self.auto_save:
self.save_metadata()
@property
def notes(self) -> str:
"""Return experiment notes.
Returns:
Experiment notes.
"""
return self._db_data.notes
@notes.setter
def notes(self, new_notes: str) -> None:
"""Update experiment notes.
Args:
new_notes: New experiment notes.
"""
self._db_data.notes = new_notes
if self.auto_save:
self.save_metadata()
@property
def backend_name(self) -> str:
"""Return the backend's name"""
return self._db_data.backend
@property
def backend(self) -> Backend:
"""Return backend.
Returns:
Backend.
"""
return self._backend
@backend.setter
def backend(self, new_backend: Backend) -> None:
"""Update backend.
Args:
new_backend: New backend.
"""
self._set_backend(new_backend)
if self.auto_save:
self.save_metadata()
def _set_backend(self, new_backend: Backend, recursive: bool = True) -> None:
"""Set backend.
Args:
new_backend: New backend.
recursive: should set the backend for children as well
"""
# defined independently from the setter to enable setting without autosave
self._backend = new_backend
self._backend_data = BackendData(new_backend)
self._db_data.backend = self._backend_data.name
if self._db_data.backend is None:
self._db_data.backend = str(new_backend)
provider = self._backend_data.provider
if provider is not None:
self._set_hgp_from_provider(provider)
# qiskit-ibm-runtime style
elif hasattr(self._backend, "_instance") and self._backend._instance:
self.hgp = self._backend._instance
if recursive:
for data in self.child_data():
data._set_backend(new_backend)
def _set_hgp_from_provider(self, provider):
try:
# qiskit-ibm-provider style
if hasattr(provider, "_hgps"):
for hgp_string, hgp in provider._hgps.items():
if self.backend.name in hgp.backends:
self.hgp = hgp_string
break
except (AttributeError, IndexError, QiskitError):
pass
@property
def hgp(self) -> str:
"""Returns Hub/Group/Project data as a formatted string"""
return f"{self.hub}/{self.group}/{self.project}"
@hgp.setter
def hgp(self, new_hgp: str) -> None:
"""Sets the Hub/Group/Project data from a formatted string"""
if re.match(r"[^/]*/[^/]*/[^/]*$", new_hgp) is None:
raise QiskitError("hgp can be only given in a <hub>/<group>/<project> format")
self._db_data.hub, self._db_data.group, self._db_data.project = new_hgp.split("/")
def _clear_results(self):
"""Delete all currently stored analysis results and figures"""
# Schedule existing analysis results for deletion next save call
self._deleted_analysis_results.extend(list(self._analysis_results.result_ids))
self._analysis_results.clear()
# Schedule existing figures for deletion next save call
# TODO: Fully delete artifacts from the service
# Current implementation uploads empty files instead
for artifact in self._artifacts.values():
self._deleted_artifacts.add(artifact.name)
for key in self._figures.keys():
self._deleted_figures.append(key)
self._figures = ThreadSafeOrderedDict()
self._artifacts = ThreadSafeOrderedDict()
self._db_data.figure_names.clear()
@property
def service(self) -> Optional[IBMExperimentService]:
"""Return the database service.
Returns:
Service that can be used to access this experiment in a database.
"""
return self._service
@service.setter
def service(self, service: IBMExperimentService) -> None:
"""Set the service to be used for storing experiment data
Args:
service: Service to be used.
Raises:
ExperimentDataError: If an experiment service is already being used.
"""
self._set_service(service)
@property
def provider(self) -> Optional[Provider]:
"""Return the backend provider.
Returns:
Provider that is used to obtain backends and job data.
"""
return self._provider
@provider.setter
def provider(self, provider: Provider) -> None:
"""Set the provider to be used for obtaining job data
Args:
provider: Provider to be used.
"""
self._provider = provider
@property
def auto_save(self) -> bool:
"""Return current auto-save option.
Returns:
Whether changes will be automatically saved.
"""
return self._auto_save
@auto_save.setter
def auto_save(self, save_val: bool) -> None:
"""Set auto save preference.
Args:
save_val: Whether to do auto-save.
"""
# children will be saved once we set auto_save for them
if save_val is True:
self.save(save_children=False)
self._auto_save = save_val
for data in self.child_data():
data.auto_save = save_val
@property
def source(self) -> Dict:
"""Return the class name and version."""
return self._db_data.metadata["_source"]
# Data addition and deletion
def add_data(
self,
data: Union[Result, List[Result], Dict, List[Dict]],
) -> None:
"""Add experiment data.
Args:
data: Experiment data to add. Several types are accepted for convenience:
* Result: Add data from this ``Result`` object.
* List[Result]: Add data from the ``Result`` objects.
* Dict: Add this data.
* List[Dict]: Add this list of data.
Raises:
TypeError: If the input data type is invalid.
"""
if any(not future.done() for future in self._analysis_futures.values()):
LOG.warning(
"Not all analysis has finished running. Adding new data may "
"create unexpected analysis results."
)
if not isinstance(data, list):
data = [data]
# Directly add non-job data
with self._result_data.lock:
for datum in data:
if isinstance(datum, dict):
self._result_data.append(datum)
elif isinstance(datum, Result):
self._add_result_data(datum)
else:
raise TypeError(f"Invalid data type {type(datum)}.")
def add_jobs(
self,
jobs: Union[Job, List[Job], BasePrimitiveJob, List[BasePrimitiveJob]],
timeout: Optional[float] = None,
) -> None:
"""Add experiment data.
Args:
jobs: The Job or list of Jobs to add result data from.
timeout: Optional, time in seconds to wait for all jobs to finish
before cancelling them.
Raises:
TypeError: If the input data type is invalid.
.. note::
If a timeout is specified the :meth:`cancel_jobs` method will be
called after timing out to attempt to cancel any unfinished jobs.
If you want to wait for jobs without cancelling, use the timeout
kwarg of :meth:`block_for_results` instead.
"""
if any(not future.done() for future in self._analysis_futures.values()):
LOG.warning(
"Not all analysis has finished running. Adding new jobs may "
"create unexpected analysis results."
)
if isinstance(jobs, Job):
jobs = [jobs]
# Add futures for extracting finished job data
timeout_ids = []
for job in jobs:
if hasattr(job, "backend"):
if self.backend is not None:
backend_name = BackendData(self.backend).name
job_backend_name = BackendData(job.backend()).name
if self.backend and backend_name != job_backend_name:
LOG.warning(
"Adding a job from a backend (%s) that is different "
"than the current backend (%s). "
"The new backend will be used, but "
"service is not changed if one already exists.",
job.backend(),
self.backend,
)
self.backend = job.backend()
jid = job.job_id()
if jid in self._jobs:
LOG.warning(
"Skipping duplicate job, a job with this ID already exists [Job ID: %s]", jid
)
else:
self.job_ids.append(jid)
self._jobs[jid] = job
if jid in self._job_futures:
LOG.warning("Job future has already been submitted [Job ID: %s]", jid)
else:
self._add_job_future(job)
if timeout is not None:
timeout_ids.append(jid)
# Add future for cancelling jobs that timeout
if timeout_ids:
self._job_executor.submit(self._timeout_running_jobs, timeout_ids, timeout)
if self.auto_save:
self.save_metadata()
def _timeout_running_jobs(self, job_ids, timeout):
"""Function for cancelling jobs after timeout length.
This function should be submitted to an executor to run as a future.
Args:
job_ids: the IDs of jobs to wait for.
timeout: The total time to wait for all jobs before cancelling.
"""
futs = [self._job_futures[jid] for jid in job_ids]
waited = futures.wait(futs, timeout=timeout)
# Try to cancel timed-out jobs
if waited.not_done:
LOG.debug("Cancelling running jobs that exceeded add_jobs timeout.")
done_ids = {fut.result()[0] for fut in waited.done}
notdone_ids = [jid for jid in job_ids if jid not in done_ids]
self.cancel_jobs(notdone_ids)
def _add_job_future(self, job):
"""Submit new _add_job_data job to executor"""
jid = job.job_id()
if jid in self._job_futures:
LOG.warning("Job future has already been submitted [Job ID: %s]", jid)
else:
self._job_futures[jid] = self._job_executor.submit(self._add_job_data, job)
def _add_job_data(
self,
job: Job,
) -> Tuple[str, bool]:
"""Wait for a job to finish and add job result data.
Args:
job: the Job to wait for and add data from.
Returns:
A tuple (str, bool) of the job id and bool of if the job data was added.
Raises:
Exception: If an error occurred when adding job data.
"""
jid = job.job_id()
try:
job_result = job.result()
try:
self._running_time = job.time_per_step().get("running", None)
except AttributeError:
pass
self._add_result_data(job_result, jid)
LOG.debug("Job data added [Job ID: %s]", jid)
# sets the endtime to be the time the last successful job was added
self.end_datetime = datetime.now()
return jid, True
except Exception as ex: # pylint: disable=broad-except
# Handle cancelled jobs
status = job.status()
if status == JobStatus.CANCELLED:
LOG.warning("Job was cancelled before completion [Job ID: %s]", jid)
return jid, False
if status == JobStatus.ERROR:
LOG.error(
"Job data not added for errored job [Job ID: %s]\nError message: %s",
jid,
job.error_message() if hasattr(job, "error_message") else "n/a",
)
return jid, False
LOG.warning("Adding data from job failed [Job ID: %s]", job.job_id())
raise ex
def add_analysis_callback(self, callback: Callable, **kwargs: Any):
"""Add analysis callback for running after experiment data jobs are finished.
This method adds the `callback` function to a queue to be run
asynchronously after completion of any running jobs, or immediately
if no running jobs. If this method is called multiple times the
callback functions will be executed in the order they were
added.
Args:
callback: Callback function invoked when job finishes successfully.
The callback function will be called as
``callback(expdata, **kwargs)`` where `expdata` is this
``DbExperimentData`` object, and `kwargs` are any additional
keyword arguments passed to this method.
**kwargs: Keyword arguments to be passed to the callback function.
"""
with self._job_futures.lock and self._analysis_futures.lock:
# Create callback dataclass
cid = uuid.uuid4().hex
self._analysis_callbacks[cid] = AnalysisCallback(
name=callback.__name__,
callback_id=cid,
)
# Futures to wait for
futs = self._job_futures.values() + self._analysis_futures.values()
wait_future = self._monitor_executor.submit(
self._wait_for_futures, futs, name="jobs and analysis"
)
# Create a future to monitor event for calls to cancel_analysis
def _monitor_cancel():
self._analysis_callbacks[cid].event.wait()
return False
cancel_future = self._monitor_executor.submit(_monitor_cancel)
# Add run analysis future
self._analysis_futures[cid] = self._analysis_executor.submit(
self._run_analysis_callback, cid, wait_future, cancel_future, callback, **kwargs
)
def _run_analysis_callback(
self,
callback_id: str,
wait_future: futures.Future,
cancel_future: futures.Future,
callback: Callable,
**kwargs,
):
"""Run an analysis callback after specified futures have finished."""
if callback_id not in self._analysis_callbacks:
raise ValueError(f"No analysis callback with id {callback_id}")
# Monitor jobs and cancellation event to see if callback should be run
# or cancelled
# Future which returns if either all jobs finish, or cancel event is set
waited = futures.wait([wait_future, cancel_future], return_when="FIRST_COMPLETED")
cancel = not all(fut.result() for fut in waited.done)
# Ensure monitor event is set so monitor future can terminate
self._analysis_callbacks[callback_id].event.set()
# If not ready cancel the callback before running
if cancel:
self._analysis_callbacks[callback_id].status = AnalysisStatus.CANCELLED
LOG.info(
"Cancelled analysis callback [Experiment ID: %s][Analysis Callback ID: %s]",
self.experiment_id,
callback_id,
)
return callback_id, False
# Run callback function
self._analysis_callbacks[callback_id].status = AnalysisStatus.RUNNING
try:
LOG.debug(
"Running analysis callback '%s' [Experiment ID: %s][Analysis Callback ID: %s]",
self._analysis_callbacks[callback_id].name,
self.experiment_id,
callback_id,
)
callback(self, **kwargs)
self._analysis_callbacks[callback_id].status = AnalysisStatus.DONE
LOG.debug(
"Analysis callback finished [Experiment ID: %s][Analysis Callback ID: %s]",
self.experiment_id,
callback_id,
)
return callback_id, True
except Exception as ex: # pylint: disable=broad-except
self._analysis_callbacks[callback_id].status = AnalysisStatus.ERROR
tb_text = "".join(traceback.format_exception(type(ex), ex, ex.__traceback__))
error_msg = (
f"Analysis callback failed [Experiment ID: {self.experiment_id}]"
f"[Analysis Callback ID: {callback_id}]:\n{tb_text}"
)
self._analysis_callbacks[callback_id].error_msg = error_msg
LOG.warning(error_msg)
return callback_id, False