Source code for qiskit_experiments.framework.experiment_data
# 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__importannotationsimportloggingimportrefromtypingimportDict,Optional,List,Union,Any,Callable,Tuple,TYPE_CHECKINGfromdatetimeimportdatetime,timezonefromconcurrentimportfuturesfromfunctoolsimportwrapsfromcollectionsimportdeque,defaultdictfromcollections.abcimportIterableimportcontextlibimportcopyimportuuidimporttimeimportsysimportjsonimporttracebackimportwarningsimportnumpyasnpimportpandasaspdfrommatplotlibimportpyplotfromqiskit.resultimportResultfromqiskit.primitivesimportPrimitiveResultfromqiskit.providers.jobstatusimportJobStatus,JOB_FINAL_STATESfromqiskit.exceptionsimportQiskitErrorfromqiskit.providersimportBackendfromqiskit.utils.deprecationimportdeprecate_argfromqiskit.primitivesimportBitArray,SamplerPubResultfromqiskit_ibm_experimentimport(IBMExperimentService,ExperimentDataasExperimentDataclass,AnalysisResultDataasAnalysisResultDataclass,ResultQuality,)fromqiskit_experiments.framework.jsonimportExperimentEncoder,ExperimentDecoderfromqiskit_experiments.database_service.utilsimport(plot_to_svg_bytes,ThreadSafeOrderedDict,ThreadSafeList,)fromqiskit_experiments.database_service.device_componentimportto_component,DeviceComponentfromqiskit_experiments.framework.analysis_resultimportAnalysisResultfromqiskit_experiments.framework.analysis_result_dataimportAnalysisResultDatafromqiskit_experiments.framework.analysis_result_tableimportAnalysisResultTablefromqiskit_experiments.frameworkimportBackendDatafromqiskit_experiments.framework.containersimportArtifactDatafromqiskit_experiments.frameworkimportExperimentStatus,AnalysisStatus,AnalysisCallbackfromqiskit_experiments.framework.package_depsimportqiskit_versionfromqiskit_experiments.database_service.exceptionsimport(ExperimentDataError,ExperimentEntryNotFound,ExperimentDataSaveFailed,)fromqiskit_experiments.database_service.utilsimportobjs_to_zip,zip_to_objsfrom.containers.figure_dataimportFigureData,FigureTypefrom.provider_interfacesimportJob,ProviderifTYPE_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.importBaseExperimentLOG=logging.getLogger(__name__)defdo_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)ifself.auto_save:self.save_metadata()returnreturn_valreturn_wrappeddefparse_utc_datetime(dt_str:str)->datetime:"""Parses UTC datetime from a string"""ifdt_strisNone:returnNonedb_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)returndt_utcdefget_job_status(job:Job)->JobStatus:"""Get job status in JobStatus format defined in: `from qiskit.providers.jobstatus import JobStatus`"""status=job.status()ifisinstance(status,str):qe_job_status=getattr(JobStatus,status,None)ifqe_job_statusisNone:raiseQiskitError(f"The status of job {job.job_id()} is {status} ""which is not supported by qiskit-experiments.")status=qe_job_statusreturnstatus
[docs]classExperimentData:"""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=10def__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. """ifexperimentisnotNone:backend=backendorexperiment.backendexperiment_type=experiment.experiment_typeelse:# Don't use None since the resultDB won't accept thatexperiment_type=""ifjob_idsisNone:job_ids=[]self._experiment=experiment# data stored in the databasemetadata={}ifexperimentisnotNone: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"]=sourceexperiment_id=kwargs.get("experiment_id",str(uuid.uuid4()))ifdb_dataisNone: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_dataifself.start_datetimeisNone:ifstart_datetimeisNone:start_datetime=datetime.now()self.start_datetime=start_datetimeforkey,valueinkwargs.items():ifhasattr(self._db_data,key):setattr(self._db_data,key,value)else:LOG.warning("Key '%s' not stored in the database",key)# general data relatedself._backend=NoneifbackendisnotNone:self._set_backend(backend,recursive=False)self._provider=providerifproviderisNoneandbackendisnotNone:# BackendV2 has a provider attribute but BackendV3 probably will notself._provider=getattr(backend,"provider",None)ifself.providerisNoneandhasattr(backend,"service"):# qiskit_ibm_runtime.IBMBackend stores its Provider-like object in# the "service" attributeself._provider=backend.service# Experiment service like qiskit_ibm_experiment.IBMExperimentService,# not to be confused with qiskit_ibm_runtime.QiskitRuntimeServiceself._service=serviceself._auto_save=Falseself._created_in_db=Falseself._extra_data=kwargsself.verbose=verbose# job handling relatedself._jobs=ThreadSafeOrderedDict(job_ids)self._job_futures=ThreadSafeOrderedDict()self._running_time=Noneself._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 storageself._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 containerself._child_data=ThreadSafeOrderedDict()ifchild_dataisnotNone:self._set_child_data(child_data)# Getters/setters for experiment metadata@propertydefexperiment(self):"""Return the experiment for this data. Returns: BaseExperiment: the experiment object. """returnself._experiment@propertydefcompletion_times(self)->Dict[str,datetime]:"""Returns the completion times of the jobs."""job_times={}forjob_id,jobinself._jobs.items():ifjobisnotNone:ifhasattr(job,"time_per_step")and"COMPLETED"injob.time_per_step():job_times[job_id]=job.time_per_step().get("COMPLETED")elif(execution:=getattr(job.result(),"metadata",{}).get("execution"))and"execution_spans"inexecution:job_times[job_id]=execution["execution_spans"].stopelif(client:=getattr(job,"_api_client",None))andhasattr(client,"job_metadata"):metadata=client.job_metadata(job.job_id())finished=metadata.get("timestamps",{}).get("finished",{})iffinished:job_times[job_id]=datetime.fromisoformat(finished)ifjob_idnotinjob_times:warnings.warn("Could not determine job completion time. Using current timestamp.",UserWarning,)job_times[job_id]=datetime.now()returnjob_times@propertydeftags(self)->List[str]:"""Return tags assigned to this experiment data. Returns: A list of tags assigned to this experiment data. """returnself._db_data.tags@tags.setterdeftags(self,new_tags:List[str])->None:"""Set tags for this experiment."""ifnotisinstance(new_tags,list):raiseExperimentDataError(f"The `tags` field of {type(self).__name__} must be a list.")self._db_data.tags=np.unique(new_tags).tolist()ifself.auto_save:self.save_metadata()@propertydefmetadata(self)->Dict:"""Return experiment metadata. Returns: Experiment metadata. """returnself._db_data.metadata@propertydefcreation_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. """returnself._db_data.creation_datetime@propertydefstart_datetime(self)->datetime:"""Return the start datetime of this experiment data. Returns: The timestamp when this experiment began running in the local timezone. """returnself._db_data.start_datetime@start_datetime.setterdefstart_datetime(self,new_start_datetime:datetime)->None:self._db_data.start_datetime=new_start_datetime@propertydefupdated_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. """returnself._db_data.updated_datetime@propertydefrunning_time(self)->datetime|None:"""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. .. note:: In practice, this property is not currently set automatically by Qiskit Experiments. """returnself._running_time@propertydefend_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. """returnself._db_data.end_datetime@end_datetime.setterdefend_datetime(self,new_end_datetime:datetime)->None:self._db_data.end_datetime=new_end_datetime@propertydefhub(self)->str:"""Return the hub of this experiment data. Returns: The hub of this experiment data. """returnself._db_data.hub@propertydefgroup(self)->str:"""Return the group of this experiment data. Returns: The group of this experiment data. """returnself._db_data.group@propertydefproject(self)->str:"""Return the project of this experiment data. Returns: The project of this experiment data. """returnself._db_data.project@propertydefexperiment_id(self)->str:"""Return experiment ID Returns: Experiment ID. """returnself._db_data.experiment_id@propertydefexperiment_type(self)->str:"""Return experiment type Returns: Experiment type. """returnself._db_data.experiment_type@experiment_type.setterdefexperiment_type(self,new_type:str)->None:"""Sets the parent id"""self._db_data.experiment_type=new_type@propertydefparent_id(self)->str:"""Return parent experiment ID Returns: Parent ID. """returnself._db_data.parent_id@parent_id.setterdefparent_id(self,new_id:str)->None:"""Sets the parent id"""self._db_data.parent_id=new_id@propertydefjob_ids(self)->List[str]:"""Return experiment job IDs. Returns: IDs of jobs submitted for this experiment. """returnself._db_data.job_ids@propertydeffigure_names(self)->List[str]:"""Return names of the figures associated with this experiment. Returns: Names of figures associated with this experiment. """returnself._db_data.figure_names@propertydefshare_level(self)->str:"""Return the share level for this experiment Returns: Experiment share level. """returnself._db_data.share_level@share_level.setterdefshare_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_levelfordatainself._child_data.values():original_auto_save=data.auto_savedata.auto_save=Falsedata.share_level=new_leveldata.auto_save=original_auto_saveifself.auto_save:self.save_metadata()@propertydefnotes(self)->str:"""Return experiment notes. Returns: Experiment notes. """returnself._db_data.notes@notes.setterdefnotes(self,new_notes:str)->None:"""Update experiment notes. Args: new_notes: New experiment notes. """self._db_data.notes=new_notesifself.auto_save:self.save_metadata()@propertydefbackend_name(self)->str:"""Return the backend's name"""returnself._db_data.backend@propertydefbackend(self)->Backend:"""Return backend. Returns: Backend. """returnself._backend@backend.setterdefbackend(self,new_backend:Backend)->None:"""Update backend. Args: new_backend: New backend. """self._set_backend(new_backend)ifself.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 autosaveself._backend=new_backendself._backend_data=BackendData(new_backend)self._db_data.backend=self._backend_data.nameifself._db_data.backendisNone:self._db_data.backend=str(new_backend)ifhasattr(self._backend,"_instance")andself._backend._instance:self.hgp=self._backend._instanceifrecursive:fordatainself.child_data():data._set_backend(new_backend)@propertydefhgp(self)->str:"""Returns Hub/Group/Project data as a formatted string"""returnf"{self.hub}/{self.group}/{self.project}"@hgp.setterdefhgp(self,new_hgp:str)->None:"""Sets the Hub/Group/Project data from a formatted string"""ifre.match(r"[^/]*/[^/]*/[^/]*$",new_hgp)isNone:raiseQiskitError("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 callself._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 insteadforartifactinself._artifacts.values():self._deleted_artifacts.add(artifact.name)forkeyinself._figures.keys():self._deleted_figures.append(key)self._figures=ThreadSafeOrderedDict()self._artifacts=ThreadSafeOrderedDict()self._db_data.figure_names.clear()@propertydefservice(self)->Optional[IBMExperimentService]:"""Return the database service. Returns: Service that can be used to access this experiment in a database. """returnself._service@service.setterdefservice(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)def_infer_service(self,warn:bool):"""Try to configure service if it has not been configured This method should be called before any method that needs to work with the experiment service. Args: warn: Warn if the service could not be set up from the backend or provider attributes. Returns: True if a service instance has been set up """ifself.serviceisNone:self.service=self.get_service_from_backend(self.backend)ifself.serviceisNone:self.service=self.get_service_from_provider(self.provider)ifwarnandself.serviceisNone:LOG.warning("Experiment service has not been configured. Can not save!")returnself.serviceisnotNonedef_set_service(self,service:IBMExperimentService)->None:"""Set the service to be used for storing experiment data, to this experiment itself and its descendants. Args: service: Service to be used. Raises: ExperimentDataError: If an experiment service is already being used and `replace==False`. """ifself._serviceisnotNone:raiseExperimentDataError("An experiment service is already being used.")self._service=servicewithcontextlib.suppress(Exception):self.auto_save=self.service.options.get("auto_save",False)fordatainself.child_data():data._set_service(service)
[docs]@staticmethoddefget_service_from_backend(backend)->IBMExperimentService|None:"""Initializes the service from the backend data"""# backend.provider is not checked since currently the only viable way# to set up the experiment service is using the credentials from# QiskitRuntimeService on a qiskit_ibm_runtime.IBMBackend.provider=getattr(backend,"service",None)returnExperimentData.get_service_from_provider(provider)
[docs]@staticmethoddefget_service_from_provider(provider)->IBMExperimentService|None:"""Initializes the service from the provider data"""ifnothasattr(provider,"active_account"):returnNoneaccount=provider.active_account()url=account.get("url")token=account.get("token")try:ifurlisnotNoneandtokenisnotNone:returnIBMExperimentService(token=token,url=url)exceptException:# pylint: disable=broad-exceptLOG.warning("Failed to connect to experiment service",exc_info=True)returnNone
@propertydefprovider(self)->Optional[Provider]:"""Return the backend provider. Returns: Provider that is used to obtain backends and job data. """returnself._provider@provider.setterdefprovider(self,provider:Provider)->None:"""Set the provider to be used for obtaining job data Args: provider: Provider to be used. """self._provider=provider@propertydefauto_save(self)->bool:"""Return current auto-save option. Returns: Whether changes will be automatically saved. """returnself._auto_save@auto_save.setterdefauto_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 themifsave_valisTrue:self.save(save_children=False)self._auto_save=save_valfordatainself.child_data():data.auto_save=save_val@propertydefsource(self)->Dict:"""Return the class name and version."""returnself._db_data.metadata["_source"]# Data addition and deletion
[docs]defadd_data(self,data:Union[Result,PrimitiveResult,List[Result|PrimitiveResult],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. """ifany(notfuture.done()forfutureinself._analysis_futures.values()):LOG.warning("Not all analysis has finished running. Adding new data may ""create unexpected analysis results.")ifnotisinstance(data,list):data=[data]# Directly add non-job datawithself._result_data.lock:fordatumindata:ifisinstance(datum,dict):self._result_data.append(datum)elifisinstance(datum,(Result,PrimitiveResult)):self._add_result_data(datum)else:raiseTypeError(f"Invalid data type {type(datum)}.")
[docs]defadd_jobs(self,jobs:Union[Job,List[Job]],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. """ifany(notfuture.done()forfutureinself._analysis_futures.values()):LOG.warning("Not all analysis has finished running. Adding new jobs may ""create unexpected analysis results.")ifnotisinstance(jobs,Iterable):jobs=[jobs]# Add futures for extracting finished job datatimeout_ids=[]forjobinjobs:ifhasattr(job,"backend"):ifself.backendisnotNone:backend_name=BackendData(self.backend).namejob_backend_name=BackendData(job.backend()).nameifself.backendandbackend_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()ifjidinself._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]=jobifjidinself._job_futures:LOG.warning("Job future has already been submitted [Job ID: %s]",jid)else:self._add_job_future(job)iftimeoutisnotNone:timeout_ids.append(jid)# Add future for cancelling jobs that timeoutiftimeout_ids:self._job_executor.submit(self._timeout_running_jobs,timeout_ids,timeout)ifself.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]forjidinjob_ids]waited=futures.wait(futs,timeout=timeout)# Try to cancel timed-out jobsifwaited.not_done:LOG.debug("Cancelling running jobs that exceeded add_jobs timeout.")done_ids={fut.result()[0]forfutinwaited.done}notdone_ids=[jidforjidinjob_idsifjidnotindone_ids]self.cancel_jobs(notdone_ids)def_add_job_future(self,job):"""Submit new _add_job_data job to executor"""jid=job.job_id()ifjidinself._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()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 addedself.end_datetime=datetime.now()returnjid,TrueexceptExceptionasex:# pylint: disable=broad-except# Handle cancelled jobsstatus=get_job_status(job)ifstatus==JobStatus.CANCELLED:LOG.warning("Job was cancelled before completion [Job ID: %s]",jid)returnjid,Falseifstatus==JobStatus.ERROR:LOG.error("Job data not added for errored job [Job ID: %s]\nError message: %s",jid,job.error_message()ifhasattr(job,"error_message")else"n/a",)returnjid,FalseLOG.warning("Adding data from job failed [Job ID: %s]",job.job_id())raiseex
[docs]defadd_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. """withself._job_futures.lockandself._analysis_futures.lock:# Create callback dataclasscid=uuid.uuid4().hexself._analysis_callbacks[cid]=AnalysisCallback(name=callback.__name__,callback_id=cid,)# Futures to wait forfuts=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_analysisdef_monitor_cancel():self._analysis_callbacks[cid].event.wait()returnFalsecancel_future=self._monitor_executor.submit(_monitor_cancel)# Add run analysis futureself._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."""ifcallback_idnotinself._analysis_callbacks:raiseValueError(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 setwaited=futures.wait([wait_future,cancel_future],return_when="FIRST_COMPLETED")cancel=notall(fut.result()forfutinwaited.done)# Ensure monitor event is set so monitor future can terminateself._analysis_callbacks[callback_id].event.set()# If not ready cancel the callback before runningifcancel:self._analysis_callbacks[callback_id].status=AnalysisStatus.CANCELLEDLOG.info("Cancelled analysis callback [Experiment ID: %s][Analysis Callback ID: %s]",self.experiment_id,callback_id,)returncallback_id,False# Run callback functionself._analysis_callbacks[callback_id].status=AnalysisStatus.RUNNINGtry: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.DONELOG.debug("Analysis callback finished [Experiment ID: %s][Analysis Callback ID: %s]",self.experiment_id,callback_id,)returncallback_id,TrueexceptExceptionasex:# pylint: disable=broad-exceptself._analysis_callbacks[callback_id].status=AnalysisStatus.ERRORtb_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_msgLOG.warning(error_msg)returncallback_id,Falsedef_add_result_data(self,result:Result|PrimitiveResult,job_id:Optional[str]=None,)->None:"""Add data from a Result object Args: result: Result object containing data to be added. job_id: The id of the job the result came from. If `None`, the job id in `result` is used. """ifhasattr(result,"results"):# backend run resultsifjob_idisNone:job_id=result.job_idifjob_idnotinself._jobs:self._jobs[job_id]=Noneself.job_ids.append(job_id)withself._result_data.lock:# Lock data while adding all result datafori,_inenumerate(result.results):data=result.data(i)data["job_id"]=job_idif"counts"indata:# Format to Counts object rather than hex dictdata["counts"]=result.get_counts(i)expr_result=result.results[i]ifhasattr(expr_result,"header")andhasattr(expr_result.header,"metadata"):data["metadata"]=expr_result.header.metadatadata["shots"]=expr_result.shotsdata["meas_level"]=expr_result.meas_levelifhasattr(expr_result,"meas_return"):data["meas_return"]=expr_result.meas_returnself._result_data.append(data)else:# sampler resultsifjob_idisNone:raiseQiskitError("job_id must be provided, not available in the sampler result")ifjob_idnotinself._jobs:self._jobs[job_id]=Noneself.job_ids.append(job_id)withself._result_data.lock:# Lock data while adding all result data# Sampler results are a listfori,_inenumerate(result):data={}# convert to a Sampler Pub Result (can remove this later when the bug is fixed)testres=SamplerPubResult(result[i].data,result[i].metadata)data["job_id"]=job_idiftestres.data:joined_data=testres.join_data()outer_shape=testres.data.shapeifouter_shape:raiseQiskitError(f"Outer PUB dimensions {outer_shape} found in result. ""Only unparameterized PUBs are currently supported by ""qiskit-experiments.")else:joined_data=Noneifjoined_dataisNone:# No data, usually this only happens in testspasselifisinstance(joined_data,BitArray):# bit results so has countsdata["meas_level"]=2# The sampler result always contains bitstrings. At# this point, we have lost track of whether the job# requested memory/meas_return=single. Here we just# hope that nothing breaks if we always return single# shot results since the counts dict is also returned# any way.data["meas_return"]="single"# join the datadata["counts"]=testres.join_data(testres.data.keys()).get_counts()data["memory"]=testres.join_data(testres.data.keys()).get_bitstrings()# number of shotsdata["shots"]=joined_data.num_shotselifisinstance(joined_data,np.ndarray):data["meas_level"]=1ifjoined_data.ndim==1:data["meas_return"]="avg"# TODO: we either need to track shots in the# circuit metadata and pull it out here or get# upstream to report the number of shots in the# sampler result for level 1 avg data.data["shots"]=1data["memory"]=np.zeros((len(joined_data),2),dtype=float)data["memory"][:,0]=np.real(joined_data)data["memory"][:,1]=np.imag(joined_data)else:data["meas_return"]="single"data["shots"]=joined_data.shape[0]data["memory"]=np.zeros((*joined_data.shape,2),dtype=float)data["memory"][:,:,0]=np.real(joined_data)data["memory"][:,:,1]=np.imag(joined_data)else:raiseQiskitError(f"Unexpected result format: {type(joined_data)}")# Some Sampler implementations remove the circuit metadata# which some experiment Analysis classes need. Here we try# to put it back from the circuits themselves.if"circuit_metadata"intestres.metadata:data["metadata"]=testres.metadata["circuit_metadata"]elifself._jobs[job_id]isnotNone:corresponding_pub=self._jobs[job_id].inputs["pubs"][i]circuit=corresponding_pub[0]data["metadata"]=circuit.metadataself._result_data.append(data)def_retrieve_data(self):"""Retrieve job data if missing experiment data."""# Get job results if missing in experiment data.ifself.providerisNone:# 'self._result_data' could be locked, so I check a copy of it.ifnotself._result_data.copy():# Adding warning so the user will have indication why the analysis may fail.LOG.warning("Provider for ExperimentData object doesn't exist, resulting in a failed attempt to"" retrieve data from the server; no stored result data exists")returnretrieved_jobs={}jobs_to_retrieve=[]# the list of all jobs to retrieve from the server# first find which jobs are listed in the `job_ids` field of the experiment dataifself.job_idsisnotNone:forjidinself.job_ids:ifjidnotinself._jobsorself._jobs[jid]isNone:jobs_to_retrieve.append(jid)forjidinjobs_to_retrieve:LOG.debug("Retrieving job [Job ID: %s]",jid)try:# qiskit-ibm-runtime syntaxjob=self.provider.job(jid)retrieved_jobs[jid]=jobexceptException:# pylint: disable=broad-exceptLOG.warning("Unable to retrieve data from job [Job ID: %s]: %s",jid,traceback.format_exc())# Add retrieved job objects to stored jobs and extract dataforjid,jobinretrieved_jobs.items():self._jobs[jid]=jobifget_job_status(job)inJOB_FINAL_STATES:# Add job results synchronouslyself._add_job_data(job)else:# Add job results asynchronouslyself._add_job_future(job)
[docs]defdata(self,index:Optional[Union[int,slice,str]]=None,)->Union[Dict,List[Dict]]:"""Return the experiment data at the specified index. Args: index: Index of the data to be returned. Several types are accepted for convenience: * None: Return all experiment data. * int: Specific index of the data. * slice: A list slice of data indexes. * str: ID of the job that produced the data. Returns: Experiment data. Raises: TypeError: If the input `index` has an invalid type. """self._retrieve_data()ifindexisNone:returnself._result_data.copy()ifisinstance(index,(int,slice)):returnself._result_data[index]ifisinstance(index,str):return[datafordatainself._result_dataifdata.get("job_id")==index]raiseTypeError(f"Invalid index type {type(index)}.")
[docs]@do_auto_savedefadd_figures(self,figures:Union[FigureType,List[FigureType]],figure_names:Optional[Union[str,List[str]]]=None,overwrite:bool=False,save_figure:Optional[bool]=None,)->Union[str,List[str]]:"""Add the experiment figure. Args: figures: Paths of the figure files or figure data. figure_names: Names of the figures. If ``None``, use the figure file names, if given, or a generated name of the format ``experiment_type``, figure index, first 5 elements of ``device_components``, and first 8 digits of the experiment ID connected by underscores, such as ``T1_Q0_0123abcd.svg``. If `figures` is a list, then `figure_names` must also be a list of the same length or ``None``. overwrite: Whether to overwrite the figure if one already exists with the same name. By default, overwrite is ``False`` and the figure will be renamed with an incrementing numerical suffix. For example, trying to save ``figure.svg`` when ``figure.svg`` already exists will save it as ``figure-1.svg``, and trying to save ``figure-1.svg`` when ``figure-1.svg`` already exists will save it as ``figure-2.svg``. save_figure: Whether to save the figure in the database. If ``None``, the ``auto-save`` attribute is used. Returns: Figure names in SVG format. Raises: ValueError: If an input parameter has an invalid value. """iffigure_namesisnotNoneandnotisinstance(figure_names,list):figure_names=[figure_names]ifnotisinstance(figures,list):figures=[figures]iffigure_namesisnotNoneandlen(figures)!=len(figure_names):raiseValueError("The parameter figure_names must be None or a list of ""the same size as the parameter figures.")added_figs=[]foridx,figureinenumerate(figures):iffigure_namesisNone:ifisinstance(figure,str):# figure is a filename, so we use it as the namefig_name=figureelifnotisinstance(figure,FigureData):# Generate a name in the form StandardRB_Q0_Q1_Q2_b4f1d8ad-1.svgfig_name=(f"{self.experiment_type}_"f'{"_".join(str(i)foriinself.metadata.get("device_components",[])[:5])}_'f"{self.experiment_id[:8]}.svg")else:# Keep the existing figure name if there is onefig_name=figure.nameelse:fig_name=figure_names[idx]ifnotfig_name.endswith(".svg"):LOG.info("File name %s does not have an SVG extension. A '.svg' is added.")fig_name+=".svg"existing_figure=fig_nameinself._figuresifexisting_figureandnotoverwrite:# Remove any existing suffixes then generate new figure name# StandardRB_Q0_Q1_Q2_b4f1d8ad.svg becomes StandardRB_Q0_Q1_Q2_b4f1d8adfig_name_chunked=fig_name.rsplit("-",1)iflen(fig_name_chunked)!=1:# Figure name already has a suffix# This extracts StandardRB_Q0_Q1_Q2_b4f1d8ad as the prefix from# StandardRB_Q0_Q1_Q2_b4f1d8ad-1.svgfig_name_prefix=fig_name_chunked[0]try:fig_name_suffix=int(fig_name_chunked[1].rsplit(".",1)[0])exceptValueError:# the suffix is not an int, add our own suffix# my-custom-figure-name will be the prefix of my-custom-figure-name.svgfig_name_prefix=fig_name.rsplit(".",1)[0]fig_name_suffix=0else:# StandardRB_Q0_Q1_Q2_b4f1d8ad.svg has no hyphens so# StandardRB_Q0_Q1_Q2_b4f1d8ad would be its prefixfig_name_prefix=fig_name.rsplit(".",1)[0]fig_name_suffix=0fig_name=f"{fig_name_prefix}-{fig_name_suffix+1}.svg"whilefig_nameinself._figures:# Increment suffix until the name isn't taken# If StandardRB_Q0_Q1_Q2_b4f1d8ad-1.svg already exists,# StandardRB_Q0_Q1_Q2_b4f1d8ad-2.svg will be the name of this figurefig_name_suffix+=1fig_name=f"{fig_name_prefix}-{fig_name_suffix+1}.svg"# figure_data = Noneifisinstance(figure,str):withopen(figure,"rb")asfile:figure=file.read()# check whether the figure is already wrapped, meaning it came from a sub-experimentifisinstance(figure,FigureData):figure_data=figure.copy(new_name=fig_name)figure=figure_data.figureelse:figure_metadata={"qubits":self.metadata.get("physical_qubits"),"device_components":self.metadata.get("device_components"),"experiment_type":self.experiment_type,}figure_data=FigureData(figure=figure,name=fig_name,metadata=figure_metadata)self._figures[fig_name]=figure_dataself._db_data.figure_names.append(fig_name)save=save_figureifsave_figureisnotNoneelseself.auto_saveifsaveandself._infer_service(warn=True):ifisinstance(figure,pyplot.Figure):figure=plot_to_svg_bytes(figure)self.service.create_or_update_figure(experiment_id=self.experiment_id,figure=figure,figure_name=fig_name,create=notexisting_figure,)added_figs.append(fig_name)returnadded_figsiflen(added_figs)!=1elseadded_figs[0]
[docs]@do_auto_savedefdelete_figure(self,figure_key:Union[str,int],)->str:"""Add the experiment figure. Args: figure_key: Name or index of the figure. Returns: Figure name. Raises: ExperimentEntryNotFound: If the figure is not found. """figure_key=self._find_figure_key(figure_key)delself._figures[figure_key]self._deleted_figures.append(figure_key)ifself.auto_saveandself._infer_service(warn=True):withservice_exception_to_warning():self.service.delete_figure(experiment_id=self.experiment_id,figure_name=figure_key)self._deleted_figures.remove(figure_key)returnfigure_key
def_find_figure_key(self,figure_key:int|str,)->str:"""A helper method to find figure key."""ifisinstance(figure_key,int):iffigure_key<0orfigure_key>=len(self._figures):raiseExperimentEntryNotFound(f"Figure index {figure_key} out of range.")returnself._figures.keys()[figure_key]# All figures must have '.svg' in their names when added, as the extension is added to the key# name in the `add_figures()` method of this class.ifisinstance(figure_key,str):ifnotfigure_key.endswith(".svg"):figure_key+=".svg"iffigure_keynotinself._figures:raiseExperimentEntryNotFound(f"Figure key {figure_key} not found.")returnfigure_key
[docs]deffigure(self,figure_key:Union[str,int],file_name:Optional[str]=None,)->Union[int,FigureData]:"""Retrieve the specified experiment figure. Args: figure_key: Name or index of the figure. file_name: Name of the local file to save the figure to. If ``None``, the content of the figure is returned instead. Returns: The size of the figure if `file_name` is specified. Otherwise the content of the figure as a `FigureData` object. Raises: ExperimentEntryNotFound: If the figure cannot be found. """figure_key=self._find_figure_key(figure_key)figure_data=self._figures.get(figure_key,None)iffigure_dataisNoneandself._infer_service(warn=False):figure=self.service.figure(experiment_id=self.experiment_id,figure_name=figure_key)figure_data=FigureData(figure=figure,name=figure_key)self._figures[figure_key]=figure_dataiffigure_dataisNone:raiseExperimentEntryNotFound(f"Figure {figure_key} not found.")iffile_name:withopen(file_name,"wb")asoutput:num_bytes=output.write(figure_data.figure)returnnum_bytesreturnfigure_data
[docs]@deprecate_arg(name="results",since="0.6",additional_msg="Use keyword arguments rather than creating an AnalysisResult object.",package_name="qiskit-experiments",pending=True,)@do_auto_savedefadd_analysis_results(self,results:Optional[Union[AnalysisResult,List[AnalysisResult]]]=None,*,name:Optional[str]=None,value:Optional[Any]=None,quality:Optional[str]=None,components:Optional[List[DeviceComponent]]=None,experiment:Optional[str]=None,experiment_id:Optional[str]=None,result_id:Optional[str]=None,tags:Optional[List[str]]=None,backend:Optional[str]=None,run_time:Optional[datetime]=None,created_time:Optional[datetime]=None,**extra_values,)->None:"""Save the analysis result. Args: results: Analysis results to be saved. name: Name of the result entry. value: Analyzed quantity. quality: Quality of the data. components: Associated device components. experiment: String identifier of the associated experiment. experiment_id: ID of the associated experiment. result_id: ID of this analysis entry. If not set a random UUID is generated. tags: List of arbitrary tags. backend: Name of associated backend. run_time: The date time when the experiment started to run on the device. created_time: The date time when this analysis is performed. extra_values: Arbitrary keyword arguments for supplementary information. New dataframe columns are created in the analysis result table with added keys. """ifresultsisnotNone:# TODO deprecate this pathifnotisinstance(results,list):results=[results]forresultinresults:extra_values=result.extra.copy()ifresult.chisqisnotNone:# Move chisq to extra.# This is not global outcome, e.g. QPT doesn't provide chisq.extra_values["chisq"]=result.chisqexperiment=extra_values.pop("experiment",self.experiment_type)backend=extra_values.pop("backend",self.backend_name)run_time=extra_values.pop("run_time",self.running_time)created_time=extra_values.pop("created_time",None)self._analysis_results.add_data(name=result.name,value=result.value,quality=result.quality,components=result.device_components,experiment=experiment,experiment_id=result.experiment_id,result_id=result.result_id,tags=result.tags,backend=backend,run_time=run_time,created_time=created_time,**extra_values,)ifself.auto_save:result.save()else:experiment=experimentorself.experiment_typeexperiment_id=experiment_idorself.experiment_idtags=tagsor[]backend=backendorself.backend_nameuid=self._analysis_results.add_data(result_id=result_id,name=name,value=value,quality=quality,components=components,experiment=experiment,experiment_id=experiment_id,tags=tagsor[],backend=backend,run_time=run_time,created_time=created_time,**extra_values,)ifself.auto_saveandself._infer_service(warn=True):service_result=_series_to_service_result(series=self._analysis_results.get_data(uid,columns="all").iloc[0],service=self.service,auto_save=False,)service_result.save()
[docs]@do_auto_savedefdelete_analysis_result(self,result_key:Union[int,str],)->list[str]:"""Delete the analysis result. Args: result_key: ID or index of the analysis result to be deleted. Returns: Deleted analysis result IDs. Raises: ExperimentEntryNotFound: If analysis result not found or multiple entries are found. """uids=self._analysis_results.del_data(result_key)ifself.auto_saveandself._infer_service(warn=True):withservice_exception_to_warning():foruidinuids:self.service.delete_analysis_result(result_id=uid)else:self._deleted_analysis_results.extend(uids)returnuids
def_retrieve_analysis_results(self,refresh:bool=False):"""Retrieve service analysis results. Args: refresh: Retrieve the latest analysis results from the server, if an experiment service is available. """# Get job results if missing experiment data.ifself.serviceand(len(self._analysis_results)==0orrefresh):retrieved_results=self.service.analysis_results(experiment_id=self.experiment_id,limit=None,json_decoder=self._json_decoder)forresultinretrieved_results:# Canonicalize IBM specific data structure.# TODO define proper data schema on frontend and delegate this to service.cano_quality=AnalysisResult.RESULT_QUALITY_TO_TEXT.get(result.quality,"unknown")cano_components=[to_component(c)forcinresult.device_components]extra=result.result_data["_extra"]ifresult.chisqisnotNone:extra["chisq"]=result.chisqself._analysis_results.add_data(name=result.result_type,value=result.result_data["_value"],quality=cano_quality,components=cano_components,experiment_id=result.experiment_id,result_id=result.result_id,tags=result.tags,backend=result.backend_name,created_time=result.creation_datetime,**extra,)
[docs]@deprecate_arg(name="dataframe",deprecation_description="Setting ``dataframe`` to False in analysis_results",since="0.6",package_name="qiskit-experiments",pending=True,predicate=lambdadataframe:notdataframe,)defanalysis_results(self,index:int|slice|str|None=None,refresh:bool=False,block:bool=True,timeout:float|None=None,columns:str|list[str]="default",dataframe:bool=False,)->AnalysisResult|list[AnalysisResult]|pd.DataFrame:"""Return analysis results associated with this experiment. .. caution:: Retrieving analysis results by a numerical index, whether an integer or a slice, is deprecated as of 0.6 and will be removed in a future release. Use the name or ID of the result instead. When this method is called with ``dataframe=True`` you will receive matched result entries with the ``index`` condition in the dataframe format. You can access a certain entry value by specifying its row index by either row number or short index string. For example, .. jupyter-input:: results = exp_data.analysis_results("res1", dataframe=True) print(results) .. jupyter-output:: name experiment components value quality backend run_time 7dd286f4 res1 MyExp [Q0, Q1] 1 good test1 2024-02-06 13:46 f62042a7 res1 MyExp [Q2, Q3] 2 good test1 2024-02-06 13:46 Getting the first result value with a row number (``iloc``). .. code-block:: python value = results.iloc[0].value Getting the first result value with a short index (``loc``). .. code-block:: python value = results.loc["7dd286f4"] See the pandas `DataFrame`_ documentation for the tips about data handling. .. _DataFrame: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html Args: index: Index of the analysis result to be returned. Several types are accepted for convenience: * None: Return all analysis results. * int: Specific index of the analysis results. * slice: A list slice of indexes. * str: ID or name of the analysis result. refresh: Retrieve the latest analysis results from the server, if an experiment service is available. block: If ``True``, block for any analysis callbacks to finish running. timeout: max time in seconds to wait for analysis callbacks to finish running. columns: Specifying a set of columns to return. You can pass a list of each column name to return, otherwise builtin column groups are available: * ``all``: Return all columns, including metadata to communicate with the experiment service, such as entry IDs. * ``default``: Return columns including analysis result with supplementary information about experiment. * ``minimal``: Return only analysis subroutine returns. dataframe: Set to ``True`` to return analysis results in the dataframe format. Returns: A copy of analysis results data. Updating the returned object doesn't mutate the original dataset. Raises: ExperimentEntryNotFound: If the entry cannot be found. """ifblock:self._wait_for_futures(self._analysis_futures.values(),name="analysis",timeout=timeout)self._retrieve_analysis_results(refresh=refresh)ifdataframe:returnself._analysis_results.get_data(index,columns=columns)# Convert back into List[AnalysisResult] which is payload for IBM experiment service.# This will be removed in future version.tmp_df=self._analysis_results.get_data(index,columns="all")service_results=[]for_,seriesintmp_df.iterrows():service_results.append(_series_to_service_result(series=series,service=self.service,auto_save=self._auto_save,))ifindex==0andtmp_df.iloc[0]["name"].startswith("@"):warnings.warn("Curve fit results have moved to experiment artifacts and will be removed ""from analysis results in a future release. Use "'expdata.artifacts("fit_summary").data to access curve fit results.',DeprecationWarning,)elifisinstance(index,(int,slice)):warnings.warn("Accessing analysis results via a numerical index is deprecated and will be ""removed in a future release. Use the ID or name of the analysis result ""instead.",DeprecationWarning,)iflen(service_results)==1andindexisnotNone:returnservice_results[0]returnservice_results
# Save and load from the database
[docs]defsave_metadata(self)->None:"""Save this experiments metadata to a database service. .. note:: This method does not save analysis results, figures, or artifacts. Use :meth:`save` for general saving of all experiment data. See :meth:`qiskit.providers.experiment.IBMExperimentService.create_experiment` for fields that are saved. """self._infer_service(warn=False)self._save_experiment_metadata()fordatainself.child_data():data.save_metadata()
def_save_experiment_metadata(self,suppress_errors:bool=True)->None:"""Save this experiments metadata to a database service. Args: suppress_errors: should the method catch exceptions (true) or pass them on, potentially aborting the experiment (false) Raises: QiskitError: If the save to the database failed .. note:: This method does not save analysis results nor figures. Use :meth:`save` for general saving of all experiment data. See :meth:`qiskit.providers.experiment.IBMExperimentService.create_experiment` for fields that are saved. """ifnotself.service:LOG.warning("Experiment cannot be saved because no experiment service is available. ""An experiment service is available, for example, ""when using an IBM Quantum backend.")returntry:handle_metadata_separately=self._metadata_too_large()ifhandle_metadata_separately:metadata=self._db_data.metadataself._db_data.metadata={}result=self.service.create_or_update_experiment(self._db_data,json_encoder=self._json_encoder,create=notself._created_in_db)ifisinstance(result,dict):created_datetime=result.get("created_at",None)updated_datetime=result.get("updated_at",None)self._db_data.creation_datetime=parse_utc_datetime(created_datetime)self._db_data.updated_datetime=parse_utc_datetime(updated_datetime)self._created_in_db=Trueifhandle_metadata_separately:self.service.file_upload(self._db_data.experiment_id,self._metadata_filename,metadata,json_encoder=self._json_encoder,)self._db_data.metadata=metadataexceptExceptionasex:# pylint: disable=broad-except# Don't automatically fail the experiment just because its data cannot be saved.LOG.error("Unable to save the experiment data: %s",traceback.format_exc())ifnotsuppress_errors:raiseQiskitError(f"Experiment data save failed\nError Message:\n{str(ex)}")fromexdef_metadata_too_large(self):"""Determines whether the metadata should be stored in a separate file"""# currently the entire POST JSON request body is limited by default to 100kbtotal_metadata_size=sys.getsizeof(json.dumps(self.metadata,cls=self._json_encoder))returntotal_metadata_size>10000# Save and load from the database
[docs]defsave(self,suppress_errors:bool=True,max_workers:int=3,save_figures:bool=True,save_artifacts:bool=True,save_children:bool=True,)->None:"""Save the experiment data to a database service. Args: suppress_errors: should the method catch exceptions (true) or pass them on, potentially aborting the experiment (false) max_workers: Maximum number of concurrent worker threads (default 3, maximum 10) save_figures: Whether to save figures in the database or not save_artifacts: Whether to save artifacts in the database save_children: For composite experiments, whether to save children as well Raises: ExperimentDataSaveFailed: If no experiment database service was found, or the experiment service failed to save .. note:: This saves the experiment metadata, all analysis results, and all figures. Depending on the number of figures and analysis results this operation could take a while. To only update a previously saved experiments metadata (eg for additional tags or notes) use :meth:`save_metadata`. """# TODO - track changesself._infer_service(warn=False)ifnotself.service:LOG.warning("Experiment cannot be saved because no experiment service is available. ""An experiment service is available, for example, ""when using an IBM Quantum backend.")ifsuppress_errors:returnelse:raiseExperimentDataSaveFailed("No service found")ifmax_workers>self._max_workers_cap:LOG.warning("max_workers cannot be larger than %s. Setting max_workers = %s now.",self._max_workers_cap,self._max_workers_cap,)max_workers=self._max_workers_capifsave_artifacts:# populate the metadata entry for artifact file namesself.metadata["artifact_files"]={f"{artifact.name}.zip"forartifactinself._artifacts.values()}self._save_experiment_metadata(suppress_errors=suppress_errors)ifnotself._created_in_db:LOG.warning("Could not save experiment metadata to DB, aborting experiment save")returnanalysis_results_to_create=[]for_,seriesinself._analysis_results.dataframe.iterrows():# TODO We should support saving entire dataframe# Calling API per entry takes huge amount of time.legacy_result=_series_to_service_result(series=series,service=self.service,auto_save=False,)analysis_results_to_create.append(legacy_result._db_data)try:self.service.create_analysis_results(data=analysis_results_to_create,blocking=True,json_encoder=self._json_encoder,max_workers=max_workers,)exceptExceptionasex:# pylint: disable=broad-except# Don't automatically fail the experiment just because its data cannot be saved.LOG.error("Unable to save the experiment data: %s",traceback.format_exc())ifnotsuppress_errors:raiseExperimentDataSaveFailed(f"Analysis result save failed\nError Message:\n{str(ex)}")fromexforresultinself._deleted_analysis_results.copy():withservice_exception_to_warning():self.service.delete_analysis_result(result_id=result)self._deleted_analysis_results.remove(result)ifsave_figures:withself._figures.lock:figures_to_create=[]forname,figureinself._figures.items():iffigureisNone:continue# currently only the figure and its name are stored in the databaseifisinstance(figure,FigureData):figure=figure.figureLOG.debug("Figure metadata is currently not saved to the database")ifisinstance(figure,pyplot.Figure):figure=plot_to_svg_bytes(figure)figures_to_create.append((figure,name))self.service.create_figures(experiment_id=self.experiment_id,figure_list=figures_to_create,blocking=True,max_workers=max_workers,)fornameinself._deleted_figures.copy():withservice_exception_to_warning():self.service.delete_figure(experiment_id=self.experiment_id,figure_name=name)self._deleted_figures.remove(name)# save artifactsifsave_artifacts:withself._artifacts.lock:# make dictionary {artifact name: [artifact ids]}artifact_list=defaultdict(list)forartifactinself._artifacts.values():artifact_list[artifact.name].append(artifact.artifact_id)try:forartifact_name,artifact_idsinartifact_list.items():file_zipped=objs_to_zip(artifact_ids,[self._artifacts[artifact_id]forartifact_idinartifact_ids],json_encoder=self._json_encoder,)self.service.file_upload(experiment_id=self.experiment_id,file_name=f"{artifact_name}.zip",file_data=file_zipped,)exceptException:# pylint: disable=broad-except:LOG.error("Unable to save artifacts: %s",traceback.format_exc())# Upload a blank file if the whole file should be deleted# TODO: replace with direct artifact deletion when availableforartifact_nameinself._deleted_artifacts.copy():try:# Don't overwrite with a blank file if there's still artifacts with this nameself.artifacts(artifact_name)exceptException:# pylint: disable=broad-except:withservice_exception_to_warning():self.service.file_upload(experiment_id=self.experiment_id,file_name=f"{artifact_name}.zip",file_data=None,)# Even if we didn't overwrite an artifact file, we don't need to keep this because# an existing artifact(s) needs to be deleted to delete the artifact file in the futureself._deleted_artifacts.remove(artifact_name)ifnotself.service.localandself.verbose:print("You can view the experiment online at "f"https://quantum.ibm.com/experiments/{self.experiment_id}")# handle children, but without additional printsifsave_children:fordatainself._child_data.values():original_verbose=data.verbosedata.verbose=Falsedata.save(suppress_errors=suppress_errors,max_workers=max_workers,save_figures=save_figures,save_artifacts=save_artifacts,)data.verbose=original_verbose
[docs]defjobs(self)->List[Job]:"""Return a list of jobs for the experiment"""returnself._jobs.values()
[docs]defcancel_jobs(self,ids:str|list[str]|None=None,)->bool:"""Cancel any running jobs. Args: ids: Job(s) to cancel. If None all non-finished jobs will be cancelled. Returns: True if the specified jobs were successfully cancelled otherwise false. """ifisinstance(ids,str):ids=[ids]withself._jobs.lock:all_cancelled=Trueforjid,jobinreversed(self._jobs.items()):ifidsandjidnotinids:# Skip cancelling this callbackcontinueifjobandget_job_status(job)notinJOB_FINAL_STATES:try:job.cancel()LOG.warning("Cancelled job [Job ID: %s]",jid)exceptExceptionaserr:# pylint: disable=broad-exceptall_cancelled=FalseLOG.warning("Unable to cancel job [Job ID: %s]:\n%s",jid,err)continue# Remove done or cancelled job futuresifjidinself._job_futures:delself._job_futures[jid]returnall_cancelled
[docs]defcancel_analysis(self,ids:str|list[str]|None=None,)->bool:"""Cancel any queued analysis callbacks. .. note:: A currently running analysis callback cannot be cancelled. Args: ids: Analysis callback(s) to cancel. If None all non-finished analysis will be cancelled. Returns: True if the specified analysis callbacks were successfully cancelled otherwise false. """ifisinstance(ids,str):ids=[ids]# Lock analysis futures so we can't add more while trying to cancelwithself._analysis_futures.lock:all_cancelled=Truenot_running=[]forcid,callbackinreversed(self._analysis_callbacks.items()):ifidsandcidnotinids:# Skip cancelling this callbackcontinue# Set event to cancel callbackcallback.event.set()# Check for running callback that can't be cancelledifcallback.status==AnalysisStatus.RUNNING:all_cancelled=FalseLOG.warning("Unable to cancel running analysis callback [Experiment ID: %s]""[Analysis Callback ID: %s]",self.experiment_id,cid,)else:not_running.append(cid)# Wait for completion of other futures cancelled via event.setwaited=futures.wait([self._analysis_futures[cid]forcidinnot_running],timeout=1)# Get futures that didn't raise exceptionforfutinwaited.done:iffut.done()andnotfut.exception():cid=fut.result()[0]ifcidinself._analysis_futures:delself._analysis_futures[cid]returnall_cancelled
[docs]defcancel(self)->bool:"""Attempt to cancel any running jobs and queued analysis callbacks. .. note:: A running analysis callback cannot be cancelled. Returns: True if all jobs and analysis are successfully cancelled, otherwise false. """# Cancel analysis first since it is queued on jobs, then cancel jobs# otherwise there can be a race issue when analysis starts running# as soon as jobs are cancelledanalysis_cancelled=self.cancel_analysis()jobs_cancelled=self.cancel_jobs()returnanalysis_cancelledandjobs_cancelled
[docs]defblock_for_results(self,timeout:Optional[float]=None)->"ExperimentData":"""Block until all pending jobs and analysis callbacks finish. Args: timeout: Timeout in seconds for waiting for results. Returns: The experiment data with finished jobs and post-processing. """start_time=time.time()withself._job_futures.lockandself._analysis_futures.lock:# Lock threads to get all current job and analysis futures# at the time of function call and then release the lockjob_ids=self._job_futures.keys()job_futs=self._job_futures.values()analysis_ids=self._analysis_futures.keys()analysis_futs=self._analysis_futures.values()# Wait for futuresself._wait_for_futures(job_futs+analysis_futs,name="jobs and analysis",timeout=timeout)# Clean up done job futuresnum_jobs=len(job_ids)forjid,futinzip(job_ids,job_futs):if(fut.done()andnotfut.exception())orfut.cancelled():ifjidinself._job_futures:delself._job_futures[jid]num_jobs-=1# Clean up done analysis futuresnum_analysis=len(analysis_ids)forcid,futinzip(analysis_ids,analysis_futs):if(fut.done()andnotfut.exception())orfut.cancelled():ifcidinself._analysis_futures:delself._analysis_futures[cid]num_analysis-=1# Check if more futures got added while this function was running# and block recursively. This could happen if an analysis callback# spawns another callback or creates more jobsiflen(self._job_futures)>num_jobsorlen(self._analysis_futures)>num_analysis:time_taken=time.time()-start_timeiftimeoutisnotNone:timeout=max(0,timeout-time_taken)returnself.block_for_results(timeout=timeout)returnself
def_wait_for_futures(self,futs:List[futures.Future],name:str="futures",timeout:Optional[float]=None)->bool:"""Wait for jobs to finish running. Args: futs: Job or analysis futures to wait for. name: type name for future for logger messages. timeout: The length of time to wait for all jobs before returning False. Returns: True if all jobs finished. False if timeout time was reached or any jobs were cancelled or had an exception. """waited=futures.wait(futs,timeout=timeout)value=True# Log futures still running after timeoutifwaited.not_done:LOG.info("Waiting for %s timed out before completion [Experiment ID: %s].",name,self.experiment_id,)value=False# Check for futures that were cancelled or erroredexcepts=""forfutinwaited.done:ex=fut.exception()ifex:excepts+="\n".join(traceback.format_exception(type(ex),ex,ex.__traceback__))value=Falseeliffut.cancelled():LOG.debug("%s was cancelled before completion [Experiment ID: %s]",name,self.experiment_id,)value=Falseelifnotfut.result()[1]:# The job/analysis did not succeed, and the failure reflects in the second# returned value of _add_job_data/_run_analysis_callback. See details in Issue #866.value=Falseifexcepts:LOG.error("%s raised exceptions [Experiment ID: %s]:%s",name,self.experiment_id,excepts)returnvalue
[docs]defstatus(self)->ExperimentStatus:"""Return the experiment status. Possible return values for :class:`.ExperimentStatus` are * :attr:`~.ExperimentStatus.EMPTY` - experiment data is empty * :attr:`~.ExperimentStatus.INITIALIZING` - experiment jobs are being initialized * :attr:`~.ExperimentStatus.QUEUED` - experiment jobs are queued * :attr:`~.ExperimentStatus.RUNNING` - experiment jobs is actively running * :attr:`~.ExperimentStatus.CANCELLED` - experiment jobs or analysis has been cancelled * :attr:`~.ExperimentStatus.POST_PROCESSING` - experiment analysis is actively running * :attr:`~.ExperimentStatus.DONE` - experiment jobs and analysis have successfully run * :attr:`~.ExperimentStatus.ERROR` - experiment jobs or analysis incurred an error .. note:: If an experiment has status :attr:`~.ExperimentStatus.ERROR` there may still be pending or running jobs. In these cases it may be beneficial to call :meth:`cancel_jobs` to terminate these remaining jobs. Returns: The experiment status. """ifall(len(container)==0forcontainerin[self._result_data,self._jobs,self._job_futures,self._analysis_callbacks,self._analysis_futures,self._figures,self._analysis_results,]):returnExperimentStatus.EMPTY# Return job status is job is not DONEtry:return{JobStatus.INITIALIZING:ExperimentStatus.INITIALIZING,JobStatus.QUEUED:ExperimentStatus.QUEUED,JobStatus.VALIDATING:ExperimentStatus.VALIDATING,JobStatus.RUNNING:ExperimentStatus.RUNNING,JobStatus.CANCELLED:ExperimentStatus.CANCELLED,JobStatus.ERROR:ExperimentStatus.ERROR,}[self.job_status()]exceptKeyError:pass# Return analysis status if Done, cancelled or errortry:return{AnalysisStatus.DONE:ExperimentStatus.DONE,AnalysisStatus.CANCELLED:ExperimentStatus.CANCELLED,AnalysisStatus.ERROR:ExperimentStatus.ERROR,}[self.analysis_status()]exceptKeyError:returnExperimentStatus.POST_PROCESSING
[docs]defjob_status(self)->JobStatus:"""Return the experiment job execution status. Possible return values for :class:`qiskit.providers.jobstatus.JobStatus` are * ``ERROR`` - if any job incurred an error * ``CANCELLED`` - if any job is cancelled. * ``RUNNING`` - if any job is still running. * ``QUEUED`` - if any job is queued. * ``VALIDATING`` - if any job is being validated. * ``INITIALIZING`` - if any job is being initialized. * ``DONE`` - if all jobs are finished. .. note:: If an experiment has status ``ERROR`` or ``CANCELLED`` there may still be pending or running jobs. In these cases it may be beneficial to call :meth:`cancel_jobs` to terminate these remaining jobs. Returns: The job execution status. """statuses=set()withself._jobs.lock:# No jobs presentifnotself._jobs:returnJobStatus.DONEstatuses=set()forjobinself._jobs.values():ifjob:statuses.add(get_job_status(job))# If any jobs are in non-DONE state return that stateforstatin[JobStatus.ERROR,JobStatus.CANCELLED,JobStatus.RUNNING,JobStatus.QUEUED,JobStatus.VALIDATING,JobStatus.INITIALIZING,]:ifstatinstatuses:returnstatreturnJobStatus.DONE
[docs]defanalysis_status(self)->AnalysisStatus:"""Return the data analysis post-processing status. Possible return values for :class:`.AnalysisStatus` are * :attr:`~.AnalysisStatus.ERROR` - if any analysis callback incurred an error * :attr:`~.AnalysisStatus.CANCELLED` - if any analysis callback is cancelled. * :attr:`~.AnalysisStatus.RUNNING` - if any analysis callback is actively running. * :attr:`~.AnalysisStatus.QUEUED` - if any analysis callback is queued. * :attr:`~.AnalysisStatus.DONE` - if all analysis callbacks have successfully run. Returns: Then analysis status. """statuses=set()forstatusinself._analysis_callbacks.values():statuses.add(status.status)forstatin[AnalysisStatus.ERROR,AnalysisStatus.CANCELLED,AnalysisStatus.RUNNING,AnalysisStatus.QUEUED,]:ifstatinstatuses:returnstatreturnAnalysisStatus.DONE
[docs]defjob_errors(self)->str:"""Return any errors encountered in job execution."""errors=[]# Get any job errorsforjobinself._jobs.values():ifjobandget_job_status(job)==JobStatus.ERROR:ifhasattr(job,"error_message"):error_msg=job.error_message()else:error_msg=""errors.append(f"\n[Job ID: {job.job_id()}]: {error_msg}")# Get any job futures errors:forjid,futinself._job_futures.items():iffutandfut.done()andfut.exception():ex=fut.exception()errors.append(f"[Job ID: {jid}]""\n".join(traceback.format_exception(type(ex),ex,ex.__traceback__)))return"".join(errors)
[docs]defanalysis_errors(self)->str:"""Return any errors encountered during analysis callbacks."""errors=[]# Get any callback errorsforcid,callbackinself._analysis_callbacks.items():ifcallback.status==AnalysisStatus.ERROR:errors.append(f"\n[Analysis Callback ID: {cid}]: {callback.error_msg}")return"".join(errors)
[docs]deferrors(self)->str:"""Return errors encountered during job and analysis execution. .. note:: To display only job or analysis errors use the :meth:`job_errors` or :meth:`analysis_errors` methods. Returns: Experiment errors. """returnself.job_errors()+self.analysis_errors()
# Children handling
[docs]defadd_child_data(self,experiment_data:ExperimentData):"""Add child experiment data to the current experiment data"""experiment_data.parent_id=self.experiment_idself._child_data[experiment_data.experiment_id]=experiment_dataself.metadata["child_data_ids"]=self._child_data.keys()
[docs]defchild_data(self,index:Optional[Union[int,slice,str]]=None)->Union[ExperimentData,List[ExperimentData]]:"""Return child experiment data. Args: index: Index of the child experiment data to be returned. Several types are accepted for convenience: * None: Return all child data. * int: Specific index of the child data. * slice: A list slice of indexes. * str: experiment ID of the child data. Returns: The requested single or list of child experiment data. Raises: QiskitError: If the index or ID of the child experiment data cannot be found. """ifindexisNone:returnself._child_data.values()ifisinstance(index,(int,slice)):returnself._child_data.values()[index]ifisinstance(index,str):returnself._child_data[index]raiseQiskitError(f"Invalid index type {type(index)}.")
[docs]@classmethoddefload(cls,experiment_id:str,service:Optional[IBMExperimentService]=None,provider:Optional[Provider]=None,)->"ExperimentData":"""Load a saved experiment data from a database service. Args: experiment_id: Experiment ID. service: the database service. provider: an IBMProvider required for loading job data and can be used to initialize the service. When using :external+qiskit_ibm_runtime:doc:`qiskit-ibm-runtime <index>`, this is the :class:`~qiskit_ibm_runtime.QiskitRuntimeService` and should not be confused with the experiment database service :meth:`qiskit_ibm_experiment.IBMExperimentService`. Returns: The loaded experiment data. Raises: ExperimentDataError: If not service nor provider were given. """ifserviceisNone:ifproviderisNone:raiseExperimentDataError("Loading an experiment requires a valid Qiskit provider or experiment service.")service=cls.get_service_from_provider(provider)data=service.experiment(experiment_id,json_decoder=cls._json_decoder)ifservice.experiment_has_file(experiment_id,cls._metadata_filename):metadata=service.file_download(experiment_id,cls._metadata_filename,json_decoder=cls._json_decoder)data.metadata.update(metadata)expdata=cls(service=service,db_data=data,provider=provider)# Retrieve data and analysis results# Maybe this isn't necessary but the repr of the class should# be updated to show correct number of results including remote onesexpdata._retrieve_data()expdata._retrieve_analysis_results()# Recreate artifactstry:if"artifact_files"inexpdata.metadata:forfilenameinexpdata.metadata["artifact_files"]:ifservice.experiment_has_file(experiment_id,filename):artifact_file=service.file_download(experiment_id,filename)forartifactinzip_to_objs(artifact_file,json_decoder=cls._json_decoder):expdata.add_artifacts(artifact)exceptException:# pylint: disable=broad-except:LOG.error("Unable to load artifacts: %s",traceback.format_exc())# mark it as existing in the DBexpdata._created_in_db=Truechild_data_ids=expdata.metadata.pop("child_data_ids",[])child_data=[ExperimentData.load(child_id,service,provider)forchild_idinchild_data_ids]expdata._set_child_data(child_data)returnexpdata
[docs]defcopy(self,copy_results:bool=True)->"ExperimentData":"""Make a copy of the experiment data with a new experiment ID. Args: copy_results: If True copy the analysis results, figures, and artifacts into the returned container, along with the experiment data and metadata. If False only copy the experiment data and metadata. Returns: A copy of the experiment data object with the same data but different IDs. .. note: If analysis results and figures are copied they will also have new result IDs and figure names generated for the copies. This method can not be called from an analysis callback. It waits for analysis callbacks to complete before copying analysis results. """new_instance=ExperimentData(backend=self.backend,service=self.service,provider=self.provider,parent_id=self.parent_id,job_ids=self.job_ids,child_data=list(self._child_data.values()),verbose=self.verbose,)new_instance._db_data=self._db_data.copy()# Figure names shouldn't be copied overnew_instance._db_data.figure_names=[]new_instance._db_data.experiment_id=str(uuid.uuid4())# different id for copied experimentifself.experimentisNone:new_instance._experiment=Noneelse:new_instance._experiment=self.experiment.copy()LOG.debug("Copying experiment data [Experiment ID: %s]: %s",self.experiment_id,new_instance.experiment_id,)# Copy basic properties and metadatanew_instance._jobs=self._jobs.copy_object()new_instance._auto_save=self._auto_savenew_instance._extra_data=self._extra_data# Copy circuit result data and jobswithself._result_data.lock:# Hold the lock so no new data can be added.new_instance._result_data=self._result_data.copy_object()forjid,futinself._job_futures.items():ifnotfut.done():new_instance._add_job_future(new_instance._jobs[jid])# If not copying results return the objectifnotcopy_results:returnnew_instance# Copy results and figures.# This requires analysis callbacks to finishself._wait_for_futures(self._analysis_futures.values(),name="analysis")new_instance._analysis_results=self._analysis_results.copy()withself._figures.lock:new_instance._figures=ThreadSafeOrderedDict()new_instance.add_figures(self._figures.values())withself._artifacts.lock:new_instance._artifacts=ThreadSafeOrderedDict()new_instance.add_artifacts(self._artifacts.values())# Recursively copy child datachild_data=[data.copy(copy_results=copy_results)fordatainself.child_data()]new_instance._set_child_data(child_data)returnnew_instance
def_set_child_data(self,child_data:List[ExperimentData]):"""Set child experiment data for the current experiment."""self._child_data=ThreadSafeOrderedDict()fordatainchild_data:self.add_child_data(data)self._db_data.metadata["child_data_ids"]=self._child_data.keys()
[docs]defadd_tags_recursive(self,tags2add:List[str])->None:"""Add tags to this experiment itself and its descendants Args: tags2add - the tags that will be added to the existing tags """self.tags+=tags2addfordatainself._child_data.values():data.add_tags_recursive(tags2add)
[docs]defremove_tags_recursive(self,tags2remove:List[str])->None:"""Remove tags from this experiment itself and its descendants Args: tags2remove - the tags that will be removed from the existing tags """self.tags=[xforxinself.tagsifxnotintags2remove]fordatainself._child_data.values():data.remove_tags_recursive(tags2remove)
# representation and serializationdef__repr__(self):out=f"{type(self).__name__}({self.experiment_type}"out+=f", {self.experiment_id}"ifself.parent_id:out+=f", parent_id={self.parent_id}"ifself.tags:out+=f", tags={self.tags}"ifself.job_ids:out+=f", job_ids={self.job_ids}"ifself.share_level:out+=f", share_level={self.share_level}"ifself.metadata:out+=f", metadata=<{len(self.metadata)} items>"ifself.figure_names:out+=f", figure_names={self.figure_names}"ifself.notes:out+=f", notes={self.notes}"ifself._extra_data:forkey,valinself._extra_data.items():out+=f", {key}={repr(val)}"out+=")"returnoutdef__getattr__(self,name:str)->Any:try:returnself._extra_data[name]exceptKeyError:# pylint: disable=raise-missing-fromraiseAttributeError(f"Attribute {name} is not defined")def_safe_serialize_jobs(self):"""Return serializable object for stored jobs"""# Since Job objects are not serializable this removes# them from the jobs dict and returns {job_id: None}# that can be used to retrieve jobs from a service after loadingjobs=ThreadSafeOrderedDict()withself._jobs.lock:forjidinself._jobs.keys():jobs[jid]=Nonereturnjobsdef_safe_serialize_figures(self):"""Return serializable object for stored figures"""# Convert any MPL figures into SVG images before serializingfigures=ThreadSafeOrderedDict()withself._figures.lock:forname,figureinself._figures.items():ifisinstance(figure,pyplot.Figure):figures[name]=plot_to_svg_bytes(figure)else:figures[name]=figurereturnfiguresdef__json_encode__(self):ifany(notfut.done()forfutinself._job_futures.values()):raiseQiskitError("Not all experiment jobs have finished. Jobs must be ""cancelled or done to serialize experiment data.")ifany(notfut.done()forfutinself._analysis_futures.values()):raiseQiskitError("Not all experiment analysis has finished. Analysis must be ""cancelled or done to serialize experiment data.")json_value={"_db_data":self._db_data,"_analysis_results":self._analysis_results,"_analysis_callbacks":self._analysis_callbacks,"_deleted_figures":self._deleted_figures,"_deleted_analysis_results":self._deleted_analysis_results,"_result_data":self._result_data,"_extra_data":self._extra_data,"_created_in_db":self._created_in_db,"_figures":self._safe_serialize_figures(),# Convert figures to SVG"_jobs":self._safe_serialize_jobs(),# Handle non-serializable objects"_artifacts":self._artifacts,"_experiment":self._experiment,"_child_data":self._child_data,"_running_time":self._running_time,}# the attribute self._service in charge of the connection and communication with the# experiment db. It doesn't have meaning in the json format so there is no need to serialize# it.forattin["_service","_backend"]:json_value[att]=Nonevalue=getattr(self,att)ifvalueisnotNone:LOG.info("%s cannot be JSON serialized",str(type(value)))returnjson_value@classmethoddef__json_decode__(cls,value):ret=cls()foratt,att_valinvalue.items():setattr(ret,att,att_val)returnretdef__getstate__(self):ifany(notfut.done()forfutinself._job_futures.values()):LOG.warning("Not all job futures have finished."" Data from running futures will not be serialized.")ifany(notfut.done()forfutinself._analysis_futures.values()):LOG.warning("Not all analysis callbacks have finished."" Results from running callbacks will not be serialized.")state=self.__dict__.copy()# Remove non-pickleable attributesforkeyin["_job_futures","_analysis_futures","_analysis_executor","_monitor_executor"]:delstate[key]# Convert figures to SVGstate["_figures"]=self._safe_serialize_figures()# Handle partially pickleable attributesstate["_jobs"]=self._safe_serialize_jobs()returnstatedef__setstate__(self,state):self.__dict__.update(state)# Initialize non-pickled attributesself._job_futures=ThreadSafeOrderedDict()self._analysis_futures=ThreadSafeOrderedDict()self._analysis_executor=futures.ThreadPoolExecutor(max_workers=1)self._monitor_executor=futures.ThreadPoolExecutor()def__str__(self):line=51*"-"n_res=len(self._analysis_results)status=self.status()ret=lineret+=f"\nExperiment: {self.experiment_type}"ret+=f"\nExperiment ID: {self.experiment_id}"ifself._db_data.parent_id:ret+=f"\nParent ID: {self._db_data.parent_id}"ifself._child_data:ret+=f"\nChild Experiment Data: {len(self._child_data)}"ret+=f"\nStatus: {status}"ifstatus=="ERROR":ret+="\n "ret+="\n ".join(self._errors)ifself.backend:ret+=f"\nBackend: {self.backend}"ifself.tags:ret+=f"\nTags: {self.tags}"ret+=f"\nData: {len(self._result_data)}"ret+=f"\nAnalysis Results: {n_res}"ret+=f"\nFigures: {len(self._figures)}"ret+=f"\nArtifacts: {len(self._artifacts)}"returnret
[docs]defadd_artifacts(self,artifacts:ArtifactData|list[ArtifactData],overwrite:bool=False):"""Add artifacts to experiment. The artifact ID must be unique. Args: artifacts: Artifact or list of artifacts to be added. overwrite: Whether to overwrite the existing artifact. """ifisinstance(artifacts,ArtifactData):artifacts=[artifacts]forartifactinartifacts:ifartifact.artifact_idinself._artifactsandnotoverwrite:raiseValueError("An artifact with id {artifact.id} already exists.""Set overwrite to True if you want to overwrite the existing""artifact.")self._artifacts[artifact.artifact_id]=artifact
[docs]defdelete_artifact(self,artifact_key:int|str,)->str|list[str]:"""Delete specified artifact data. Args: artifact_key: UID or name of the artifact. Deleting by index is deprecated. Returns: Deleted artifact ids. """ifisinstance(artifact_key,int):warnings.warn("Accessing artifacts via a numerical index is deprecated and will be ""removed in a future release. Use the ID or name of the artifact ""instead.",DeprecationWarning,)artifact_keys=self._find_artifact_keys(artifact_key)forkeyinartifact_keys:self._deleted_artifacts.add(self._artifacts[key].name)delself._artifacts[key]iflen(artifact_keys)==1:returnartifact_keys[0]returnartifact_keys
[docs]defartifacts(self,artifact_key:int|str=None,)->ArtifactData|list[ArtifactData]:"""Return specified artifact data. Args: artifact_key: UID or name of the artifact. Supplying a numerical index is deprecated. Returns: A list of specified artifact data. """ifartifact_keyisNone:returnself._artifacts.values()elifisinstance(artifact_key,int):warnings.warn("Accessing artifacts via a numerical index is deprecated and will be ""removed in a future release. Use the ID or name of the artifact ""instead.",DeprecationWarning,)artifact_keys=self._find_artifact_keys(artifact_key)out=[]forkeyinartifact_keys:artifact_data=self._artifacts[key]out.append(artifact_data)iflen(out)==1:returnout[0]returnout
def_find_artifact_keys(self,artifact_key:int|str,)->list[str]:"""A helper method to find artifact key."""ifisinstance(artifact_key,int):ifartifact_key<0orartifact_key>=len(self._artifacts):raiseExperimentEntryNotFound(f"Artifact index {artifact_key} out of range.")return[self._artifacts.keys()[artifact_key]]ifartifact_keynotinself._artifacts:name_matched=[kfork,dinself._artifacts.items()ifd.name==artifact_key]iflen(name_matched)==0:raiseExperimentEntryNotFound(f"Artifact key {artifact_key} not found.")returnname_matchedreturn[artifact_key]
@contextlib.contextmanagerdefservice_exception_to_warning():"""Convert an exception raised by experiment service to a warning."""try:yieldexceptException:# pylint: disable=broad-exceptLOG.warning("Experiment service operation failed: %s",traceback.format_exc())def_series_to_service_result(series:pd.Series,service:IBMExperimentService,auto_save:bool,source:Optional[Dict[str,Any]]=None,)->AnalysisResult:"""Helper function to convert dataframe to AnalysisResult payload for IBM experiment service. .. note:: Now :class:`.AnalysisResult` is only used to save data in the experiment service. All local operations must be done with :class:`.AnalysisResultTable` dataframe. ExperimentData._analysis_results are totally decoupled from the model of IBM experiment service until this function is implicitly called. Args: series: Pandas dataframe Series (a row of dataframe). service: Experiment service. auto_save: Do auto save when entry value changes. Returns: Legacy AnalysisResult payload. """# TODO This must be done on experiment service rather than by client.qe_result=AnalysisResultData.from_table_element(**series.replace({np.nan:None}).to_dict())result_data=AnalysisResult.format_result_data(value=qe_result.value,extra=qe_result.extra,chisq=qe_result.chisq,source=source,)# Overwrite formatted result data dictionary with original objects.# The format_result_data method implicitly deep copies input value and extra field,# but it means the dictionary stores input objects with different object id.# This affects computation of error propagation with ufloats, because it# recognizes the value correlation with object id.# See test.curve_analysis.test_baseclass.TestCurveAnalysis.test_end_to_end_compute_new_entry.result_data["_value"]=qe_result.valueresult_data["_extra"]=qe_result.extra# IBM Experiment Service doesn't have data field for experiment and run time.# These are added to extra field so that these data can be saved.result_data["_extra"]["experiment"]=qe_result.experimentresult_data["_extra"]["run_time"]=qe_result.run_timetry:quality=ResultQuality(str(qe_result.quality).upper())exceptValueError:quality="unknown"experiment_service_payload=AnalysisResultDataclass(result_id=qe_result.result_id,experiment_id=qe_result.experiment_id,result_type=qe_result.name,result_data=result_data,device_components=list(map(to_component,qe_result.device_components)),quality=quality,tags=qe_result.tags,backend_name=qe_result.backend,creation_datetime=qe_result.created_time,chisq=qe_result.chisq,)service_result=AnalysisResult()service_result.set_data(experiment_service_payload)withcontextlib.suppress(ExperimentDataError):service_result.service=serviceservice_result.auto_save=auto_savereturnservice_result