"""Some helpers to convert between different formats."""from__future__importannotationsfrompathlibimportPathfromtypingimportAnyfromaiida.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:str|Path,)->tuple[StructureData,TrajectoryData]:""" Convert xyz trajectory file to `TrajectoryData` data type. Parameters ---------- traj_file : 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
[docs]defkwarg_to_param(params:dict[str,Any])->list[str]:""" Convert a dictionary of kwargs to a set of commandline flags. Bools are converted as though ``store_true`` flag keys. Parameters ---------- params : dict[str, Any] Dictionary of arguments to convert. Returns ------- list[str] Commandline arguments as flags. Examples -------- >>> kwarg_to_param({"name": "Geoff", "key": True}) ['--name', 'Geoff', '--key'] >>> kwarg_to_param({"value": 6, "falsey": False}) ['--value', '6', '--no-falsey'] """cmdline_params=[]forkey,valinparams.items():key=key.replace("_","-")matchval:casebool()ifval:cmdline_params.append(f"--{key}")casebool():cmdline_params.append(f"--no-{key}")case_:cmdline_params.extend((f"--{key}",str(val)))returncmdline_params