K i?8dZddlmZmZmZddlZgdZddZejddZ ejdddd Z dd Z ejdddd Z ejd dd ZejddddZy)aFunctions to convert NetworkX graphs to and from other formats. The preferred way of converting data to a NetworkX graph is through the graph constructor. The constructor calls the to_networkx_graph() function which attempts to guess the input type and convert it automatically. Examples -------- Create a graph with a single edge from a dictionary of dictionaries >>> d = {0: {1: 1}} # dict-of-dicts single edge (0,1) >>> G = nx.Graph(d) See Also -------- nx_agraph, nx_pydot ) Collection GeneratorIteratorN)to_networkx_graphfrom_dict_of_dictsto_dict_of_dictsfrom_dict_of_liststo_dict_of_lists from_edgelist to_edgelistct|dr t|j||j}|jj |j|j jD]#\}}|j|j |%|St|tr t|||St|t"t$ztj&j(zt*zr t-||St|d r" tj.j1||S d dl} t|| j4rP|j6d |j6d k(r tj8||S tj:|d|S d dl} t|| j@r tjB||S d dl"} t|dr tjF||S t|tHtJzt*zr t-||Stjd#t$r}tjd|d}~wwxYw#t$r]}|dur$tjdt|d| t||cYd}~S#t$r}t!d |d}~wwxYwd}~wwxYw#YxYw#t$r}tjd |d}~wwxYw#t$r}d} tj| |d}~wwxYw#t$r}d} tj| |d}~wwxYw#t<$rYwxYw#t$r}tjd|d}~wwxYw#t<$rYwxYw#t$r}tjd|d}~wwxYw#t<$rYwxYw#t$r}tjd|d}~wwxYw)aMake a NetworkX graph from a known data structure. The preferred way to call this is automatically from the class constructor >>> d = {0: {1: {"weight": 1}}} # dict-of-dicts single edge (0,1) >>> G = nx.Graph(d) instead of the equivalent >>> G = nx.from_dict_of_dicts(d) Parameters ---------- data : object to be converted Current known types are: any NetworkX graph dict-of-dicts dict-of-lists container (e.g. set, list, tuple) of edges iterator (e.g. itertools.chain) that produces edges generator of edges Pandas DataFrame (row per edge) 2D numpy array scipy sparse array pygraphviz agraph create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. multigraph_input : bool (default False) If True and data is a dict_of_dicts, try to create a multigraph assuming dict_of_dict_of_lists. If data and create_using are both multigraphs then create a multigraph from a multigraph. adj) create_usingmultigraph_inputz&Input is not a correct NetworkX graph.NTz$converting multigraph_input raised: z: )rzInput is not known type. is_strictz(Input is not a correct pygraphviz graph.rz9Input is not a correct Pandas DataFrame adjacency matrix.) edge_attrrz2Input is not a correct Pandas DataFrame edge-list.z1Failed to interpret array as an adjacency matrix.formatz/Input is not a correct scipy sparse array type.zInput is not a valid edge listz.Input is not a known data type for conversion.)&hasattrrr is_multigraphgraphupdatenodesitems_node Exceptionnx NetworkXError isinstancedicttyper TypeErrorlisttuple reportviews EdgeViewABCrr nx_agraph from_agraphpandas DataFrameshapefrom_pandas_adjacencyfrom_pandas_edgelist ImportErrornumpyndarrayfrom_numpy_arrayscipyfrom_scipy_sparse_arrayrr) datarrresultndderrerr1err2pdmsgnpsps V/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/networkx/convert.pyrr"sPtU V')!%!3!3!5F LL   + ))+ +2 Q&&r* +M $ F%B H:, I!4 K  K09M *K9L"N7MN9!N O : III! K*(K J%K% J?. J::J??KK K K6K11K69 LLLM " M+MMM MM M?$M::M??N NN N6N11N66N99 OO O-O((O-cx||}i}|D])}|j|Dcgc] }||vs| c}||<+|Scc}w)a&Returns adjacency representation of graph as a dictionary of lists. Parameters ---------- G : graph A NetworkX graph nodelist : list Use only nodes specified in nodelist Notes ----- Completely ignores edge data for MultiGraph and MultiDiGraph. ) neighbors)Gnodelistdr6nbrs r?r r sR" A B {{1~AA!B HBs 77T)graphs returns_graphc^tjd|}|j||jrO|j s?i}|j D](\}}|D]}||vs|j ||d||<*|S|jd|j D|S)aReturns a graph from a dictionary of lists. Parameters ---------- d : dictionary of lists A dictionary of lists adjacency representation. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Examples -------- >>> dol = {0: [1]} # single edge (0,1) >>> G = nx.from_dict_of_lists(dol) or >>> G = nx.Graph(dol) # use Graph constructor rrc38K|]\}}|D]}||f ywN).0nodenbrlistrEs r? z%from_dict_of_lists..s$ K]T77 KCdC[ K[ Ks)r empty_graphadd_nodes_fromr is_directedradd_edgeadd_edges_from)rDrrBseenrMrNrEs r?r r s, q,'AQWWY MD' *d?JJtS) *DJ   H  Kaggi K  Hci}^|-|jD]\}}|j||<|S|jD]\}}|j||||<|S|:D]3}i||<fd||jDD] \}}||||<5|SD]"}i||<fd||DD] }||||< $|S)a Returns adjacency representation of graph as a dictionary of dictionaries. Parameters ---------- G : graph A NetworkX graph nodelist : list Use only nodes specified in nodelist. If None, all nodes in G. edge_data : scalar, optional (default: the G edgedatadict for each edge) If provided, the value of the dictionary will be set to `edge_data` for all edges. Usual values could be `1` or `True`. If `edge_data` is `None` (the default), the edgedata in `G` is used, resulting in a dict-of-dict-of-dicts. If `G` is a MultiGraph, the result will be a dict-of-dict-of-dict-of-dicts. See Notes for an approach to customize handling edge data. `edge_data` should *not* be a container as it will be the same container for all the edges. Returns ------- dod : dict A nested dictionary representation of `G`. Note that the level of nesting depends on the type of `G` and the value of `edge_data` (see Examples). See Also -------- from_dict_of_dicts, to_dict_of_lists Notes ----- For a more custom approach to handling edge data, try:: dod = { n: {nbr: custom(n, nbr, dd) for nbr, dd in nbrdict.items()} for n, nbrdict in G.adj.items() } where `custom` returns the desired edge data for each edge between `n` and `nbr`, given existing edge data `dd`. Examples -------- >>> G = nx.path_graph(3) >>> nx.to_dict_of_dicts(G) {0: {1: {}}, 1: {0: {}, 2: {}}, 2: {1: {}}} Edge data is preserved by default (``edge_data=None``), resulting in dict-of-dict-of-dicts where the innermost dictionary contains the edge data: >>> G = nx.Graph() >>> G.add_edges_from( ... [ ... (0, 1, {"weight": 1.0}), ... (1, 2, {"weight": 2.0}), ... (2, 0, {"weight": 1.0}), ... ] ... ) >>> d = nx.to_dict_of_dicts(G) >>> d # doctest: +SKIP {0: {1: {'weight': 1.0}, 2: {'weight': 1.0}}, 1: {0: {'weight': 1.0}, 2: {'weight': 2.0}}, 2: {1: {'weight': 2.0}, 0: {'weight': 1.0}}} >>> d[1][2]["weight"] 2.0 If `edge_data` is not `None`, edge data in the original graph (if any) is replaced: >>> d = nx.to_dict_of_dicts(G, edge_data=1) >>> d {0: {1: 1, 2: 1}, 1: {0: 1, 2: 1}, 2: {1: 1, 0: 1}} >>> d[1][2] 1 This also applies to MultiGraphs: edge data is preserved by default: >>> G = nx.MultiGraph() >>> G.add_edge(0, 1, key="a", weight=1.0) 'a' >>> G.add_edge(0, 1, key="b", weight=5.0) 'b' >>> d = nx.to_dict_of_dicts(G) >>> d # doctest: +SKIP {0: {1: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}}, 1: {0: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}}} >>> d[0][1]["b"]["weight"] 5.0 But multi edge data is lost if `edge_data` is not `None`: >>> d = nx.to_dict_of_dicts(G, edge_data=10) >>> d {0: {1: 10}, 1: {0: 10}} c36K|]\}}|vs ||fywrJrK)rLvr4rCs r?rOz#to_dict_of_dicts..ksWgahD Ws  c3,K|] }|vs| ywrJrK)rLrYrCs r?rOz#to_dict_of_dicts..ps;Q(]!;s ) adjacencycopyfromkeysr)rBrC edge_datadodunbrdictrYr4s ` r?rrsD C  kkm ( 7 A ( J kkm : 7gy9A : J   %AW1W%GAt $CF1I% % J  *A;QqT;*A )CF1I* * JrVc tjd|}|j||r~|jr`|j r(|j d|j D|S|j d|j D|S|j rt}|j D]`\}|j D]H\ } f|vs |j  fd|j D|j fJb|St}|j D]`\}|j D]H\ } f|vs |j  fd|j D|j fJb|S|j r|jst}|j D]d\}|j D]L\ } f|vr.|j d| dj||j fNf|S|j d|j D|S)aOReturns a graph from a dictionary of dictionaries. Parameters ---------- d : dictionary of dictionaries A dictionary of dictionaries adjacency representation. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. multigraph_input : bool (default False) When True, the dict `d` is assumed to be a dict-of-dict-of-dict-of-dict structure keyed by node to neighbor to edge keys to edge data for multi-edges. Otherwise this routine assumes dict-of-dict-of-dict keyed by node to neighbor to edge data. Examples -------- >>> dod = {0: {1: {"weight": 1}}} # single edge (0,1) >>> G = nx.from_dict_of_dicts(dod) or >>> G = nx.Graph(dod) # use Graph constructor rc3K|]=\}}|jD]%\}}|jD] \}}||||f'?ywrJrrLr`nbrsrYdatadictkeyr4s r?rOz%from_dict_of_dicts..sd!4'+zz|!$8%-^^%5 !"T3%!%!%!sAAc3K|]<\}}|jD]$\}}|jD] \}}|||f&>ywrJrdres r?rOz%from_dict_of_dicts..sa!4'+zz|!$8%-^^%5 !"T4L! ! !sAAc30K|] \}}||fywrJrKrLrhr4r`rYs r?rOz%from_dict_of_dicts..s#-6?c4AsD 1-sc3.K|] \}}|fywrJrKrks r?rOz%from_dict_of_dicts..s -1:dAt -s)rhc3\K|]$\}}|jD] \}}|||f&ywrJrd)rLr`rfrYr4s r?rOz%from_dict_of_dicts..s0S'!TdjjlS71d!QSSs*,) rrPrQrRrrTrsetaddrSr) rDrrrBrUrfrgr4r`rYs @@r?rrusa: q,'AQ ==?   !#$779!b HU  !#$779!T HG u wwy-GAt'+zz|- 8q6-,,-CK>>CS-!HHaV, --B H3u wwy-GAt'+zz|- 8q6-,,->Fnn>N-!HHaV, --0 H ?? Q]]_5D779 %4#zz|%GAt1vT) 1aQ /!Q ))$/HHaV$ % % H   SQWWYS  HrV)preserve_edge_attrscP||jdS|j|dS)zReturns a list of edges in the graph. Parameters ---------- G : graph A NetworkX graph nodelist : list Use only nodes specified in nodelist T)r4)edges)rBrCs r?r r s.wwDw!! 778$7 ''rVcTtjd|}|j||S)aReturns a graph from a list of edges. Parameters ---------- edgelist : list or iterator Edge tuples create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Examples -------- >>> edgelist = [(0, 1)] # single edge (0,1) >>> G = nx.from_edgelist(edgelist) or >>> G = nx.Graph(edgelist) # use Graph constructor r)rrPrT)edgelistrrBs r?r r s', q,'AX HrV)NFrJ)NN)__doc__collections.abcrrrnetworkxr__all__r _dispatchabler r rrr r rKrVr?rzs$<; UMp  2T2% 3% PupT2S 3S ld+(,("T2 3 rV