"""Opacities loaded from pickle."""importpathlibimportpickle# noqaimporttypingastimportnumpyasnpimportnumpy.typingasnptfromtaurex.cacheimportGlobalCachefromtaurex.mpiimportallocate_as_sharedfromtaurex.mpiimporthas_mpifromtaurex.mpiimportshared_rankfromtaurex.typesimportPathLikefromtaurex.utilimportsanitize_molecule_stringfrom.interpolateopacityimportInterpModeTypefrom.interpolateopacityimportInterpolatingOpacity
[docs]classPickleOpacity(InterpolatingOpacity):"""Class for loading opacities from pickle files. This was the original format for TauREx 1/2 opacities. It is now deprecated in favour of HDF5 files. """
[docs]@classmethoddefdiscover(cls)->t.List[t.Tuple[str,t.Tuple[pathlib.Path,str]]]:"""Discover opacities from pickle files in path."""fromtaurex.utilimportsanitize_molecule_stringpath=GlobalCache()["xsec_path"]ifpathisNone:return[]path=pathlib.Path(path)files=path.glob("*.pickle")discovery=[]interp=GlobalCache()["xsec_interpolation"]or"linear"forfinfiles:splits=f.stem.split(".")mol_name=sanitize_molecule_string(splits[0])discovery.append((mol_name,[f,interp]))returndiscovery
def__init__(self,filename:PathLike,interpolation_mode:t.Optional[InterpModeType]="linear",)->None:"""Initialize and load pickle file. Parameters ---------- filename: PathLike Path to pickle file interpolation_mode: Interpolation mode, by default "linear" Raises ------ FileNotFoundError If file is not found """filename=pathlib.Path(filename)super().__init__(f"PickleOpacity:{filename.stem[0:10]}",interpolation_mode=interpolation_mode,)importwarningswarnings.warn("PickleOpacity is deprecated and will be removed"" in a future major version. ""Please use HDF5Opacity instead.",DeprecationWarning,stacklevel=2,)ifnotfilename.exists():raiseFileNotFoundError(f"File {filename} does not exist")self._filename=filenameself._molecule_name=Noneself._spec_dict=Noneself._resolution=Noneself._load_pickle_file(filename)@propertydefmoleculeName(self)->str:# noqa: N802"""Molecule name."""returnself._molecule_name@propertydefxsecGrid(self)->npt.NDArray[np.float64]:# noqa: N802"""Opacity grid."""returnself._xsec_griddef_load_pickle_file(self,filename:pathlib.Path)->None:"""Load pickle file into memory."""use_shared=bool(GlobalCache()["mpi_use_shared"])sh_root=(nothas_mpi())orshared_rank()==0ifuse_sharedandnotsh_root:# Non-root ranks in a shared-memory group avoid loading# the large pickle payload and attach directly to the# shared allocations created by rank 0.xsec_arr=Nonewn_arr=Nonetemp_arr=Nonepress_arr=Noneelse:# Load the pickle fileself.info(f"Loading opacity from {filename}")try:withopen(filename,"rb")asf:self._spec_dict=pickle.load(f)# noqaexceptUnicodeDecodeError:withopen(filename,"rb")asf:self._spec_dict=pickle.load(f,encoding="latin1")# noqaself._wavenumber_grid=self._spec_dict["wno"]self._temperature_grid=self._spec_dict["t"]self._pressure_grid=self._spec_dict["p"]*1e5# Extract arrays and free the raw pickle dict immediately.# This avoids holding two copies during the shared-memory copy.xsec_arr=self._spec_dict["xsecarr"]wn_arr=self._wavenumber_gridtemp_arr=self._temperature_gridpress_arr=self._pressure_gridself._spec_dict=Noneself._xsec_grid=allocate_as_shared(xsec_arr,logger=self)# Also share the auxiliary grid arrays when using MPI shared memory.ifuse_shared:self._wavenumber_grid=allocate_as_shared(wn_arr,logger=self)self._temperature_grid=allocate_as_shared(temp_arr,logger=self)self._pressure_grid=allocate_as_shared(press_arr,logger=self)else:self._wavenumber_grid=wn_arrself._temperature_grid=temp_arrself._pressure_grid=press_arrself._resolution=np.average(np.diff(self._wavenumber_grid))splits=filename.stem.split(".")mol_name=sanitize_molecule_string(splits[0])self._molecule_name=mol_nameself._min_pressure=self._pressure_grid.min()self._max_pressure=self._pressure_grid.max()self._min_temperature=self._temperature_grid.min()self._max_temperature=self._temperature_grid.max()self.clean_molecule_name()
[docs]defclean_molecule_name(self)->None:"""Clean molecule name from underscores used."""splits=self.moleculeName.split("_")self._molecule_name=splits[0]