importimportlib.utilimportosfrompathlibimportPathfromtypingimportOptional,Unionfromqibo.configimportraise_errorfrom..parametersimportHardwarefrom.platformimportPlatform__all__=["create_platform","locate_platform"]PLATFORM="platform.py"PLATFORMS="QIBOLAB_PLATFORMS"def_platforms_paths()->list[Path]:"""Get path to repository containing the platforms. Path is specified using the environment variable QIBOLAB_PLATFORMS. """paths=os.environ.get(PLATFORMS)ifpathsisNone:raise_error(RuntimeError,f"Platforms path ${PLATFORMS} unset.")return[Path(p)forpinpaths.split(os.pathsep)]def_search(name:str,paths:list[Path])->Path:"""Search paths for given platform name."""forpathinpaths:platform=path/nameifplatform.exists():returnplatformraise_error(ValueError,f"Platform {name} not found. Check ${PLATFORMS} environment variable.",)def_load(platform:Path)->Union[Platform,Hardware]:"""Load the platform module."""module_name="platform"spec=importlib.util.spec_from_file_location(module_name,platform/PLATFORM)module=importlib.util.module_from_spec(spec)spec.loader.exec_module(module)returnmodule.create()
[docs]deflocate_platform(name:str,paths:Optional[list[Path]]=None)->Path:"""Locate platform's path. The ``name`` corresponds to the name of the folder in which the platform is defined, i.e. the one containing the ``platform.py`` file. If ``paths`` are specified, the environment is ignored, and the folder search happens only in the specified paths. """ifpathsisNone:paths=_platforms_paths()return_search(name,paths)
[docs]defcreate_platform(name:str)->Platform:"""A platform for executing quantum algorithms. It consists of a quantum processor QPU and a set of controlling instruments. Args: name (str): name of the platform. Returns: The plaform class. """ifname=="dummy":fromqibolab._core.dummyimportcreate_dummyreturncreate_dummy()path=_search(name,_platforms_paths())hardware=_load(path)ifisinstance(hardware,Platform):returnhardwarereturnPlatform.load(path,**vars(hardware))
defavailable_platforms()->list[str]:"""Returns the platforms found in the $QIBOLAB_PLATFORMS directory."""return[d.nameforplatformsin_platforms_paths()fordinplatforms.iterdir()ifd.is_dir()andPath(f"{os.environ.get(PLATFORMS)}/{d.name}/platform.py")ind.iterdir()]