"""Some helpers to convert between different formats."""frompathlibimportPathfromtypingimportUnionfromaiida.ormimportBool,Dict,Str,StructureData,TrajectoryData,load_codefromase.ioimportreadimportnumpyasnpfromaiida_mlip.helpers.help_loadimportload_model,load_structure
[docs]defconvert_numpy(dictionary:dict)->dict:""" Convert numpy ndarrays in dictionary into lists. Parameters ---------- dictionary : dict A dictionary with numpy array values to be converted into lists. Returns ------- dict Converted dictionary. """new_dict=dictionary.copy()forkey,valueinnew_dict.items():ifisinstance(value,np.ndarray):new_dict[key]=value.tolist()returnnew_dict
[docs]defxyz_to_aiida_traj(traj_file:Union[str,Path],)->tuple[StructureData,TrajectoryData]:""" Convert xyz trajectory file to `TrajectoryData` data type. Parameters ---------- traj_file : Union[str, Path] The path to the XYZ file. Returns ------- Tuple[StructureData, TrajectoryData] A tuple containing the last structure in the trajectory and a `TrajectoryData` object containing all structures from the trajectory. """# Read the XYZ file using ASEstruct_list=read(traj_file,index=":")# Create a TrajectoryData objecttraj=[StructureData(ase=struct)forstructinstruct_list]returntraj[-1],TrajectoryData(traj)
[docs]defconvert_to_nodes(dictionary:dict,convert_all:bool=False)->dict:""" Convert each key of the config file to a aiida node. Parameters ---------- dictionary : dict The dictionary obtained from the config file. convert_all : bool Define if you want to convert all the parameters or only the main ones. Returns ------- dict Returns the converted dictionary. """new_dict=dictionary.copy()arch=new_dict["arch"]conv={"code":load_code,"struct":load_structure,"model":lambdav:load_model(v,arch),"arch":Str,"ensemble":Str,"opt_cell_fully":Bool,}forkey,valueinnew_dict.items():ifkeyinconv:value=conv[key](value)# This is only in the case in which we use the run_from_config function, in that# case the config file would be made for aiida specifically not for januselifconvert_all:ifkey.endswith("_kwargs")orkey.endswith("-kwargs"):key=key.replace("-kwargs","_kwargs")value=Dict(value)else:value=Str(value)else:continuenew_dict[key]=valuereturnnew_dict