"""Methods to create graphs from molecules and crystals."""# Standard library importsfromtypingimportList# Third party library importsimportnetworkxasnx# Internal library importsfromaim2dat.ext_interfacesimport_return_ext_interface_modulesfromaim2dat.strct.strctimportStructurefromaim2dat.strct.ext_analysis.decoratorimportexternal_analysis_method
[docs]@external_analysis_methoddefcreate_graph(structure:Structure,get_graphviz_graph:bool=False,graphviz_engine:str="circo",graphviz_edge_rank_colors:List[str]=["blue","red","green","orange","darkblue"],**cn_kwargs,):""" Create graph based on the coordination. Parameters ---------- structure : aim2dat.strct.Structure Structure object. get_graphviz_graph : bool Whether to also output a graphviz.Digraph object. graphviz_engine : str Graphviz engine used to create the graph. The default value is ``'circo'``. graphviz_edge_rank_colors : list List of colors of the different edge ranks. cn_kwargs : Optional keyword arguments passed on to the ``calculate_coordination`` function. Returns ------- nx_graph : nx.MultiDiGraph networkx graph of the structure. graphviz_graph : graphviz.Digraph graphviz graph of the structure (if ``get_graphviz_graph`` is set to ``True``). """coord=structure.calculate_coordination(**cn_kwargs)nx_graph=nx.MultiDiGraph()forsite_idx,siteinenumerate(coord["sites"]):nx_graph.add_node(site_idx,element=site["element"])forsite_idx,siteinenumerate(coord["sites"]):iflen(site["neighbours"])==0:continuedistances=[neigh["distance"]forneighinsite["neighbours"]]zipped=list(zip(distances,range(len(site["neighbours"]))))zipped.sort(key=lambdapoint:point[0])_,neigh_indices=zip(*zipped)last_dist=0.0last_dist_idx=0fordist_idx,neigh_idxinenumerate(neigh_indices):ifabs(last_dist-distances[neigh_idx])<1e-5:dist_idx=last_dist_idxnx_graph.add_edge(site_idx,site["neighbours"][neigh_idx]["site_index"],rank=dist_idx)last_dist_idx=dist_idxlast_dist=distances[neigh_idx]ifget_graphviz_graph:backend_module=_return_ext_interface_modules("graphviz")returnNone,(nx_graph,backend_module._networkx2graphviz(nx_graph,graphviz_engine,graphviz_edge_rank_colors),)else:returnNone,nx_graph