ZTWHHH commited on
Commit
6cd1b09
·
verified ·
1 Parent(s): 79b9a7a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. evalkit_tf437/lib/python3.10/site-packages/triton/compiler/__pycache__/__init__.cpython-310.pyc +0 -0
  2. evalkit_tf437/lib/python3.10/site-packages/triton/compiler/__pycache__/compiler.cpython-310.pyc +0 -0
  3. evalkit_tf437/lib/python3.10/site-packages/triton/language/extra/__init__.py +3 -0
  4. evalkit_tf437/lib/python3.10/site-packages/triton/language/extra/__pycache__/cuda.cpython-310.pyc +0 -0
  5. evalkit_tf437/lib/python3.10/site-packages/triton/language/semantic.py +1565 -0
  6. evalkit_tf437/lib/python3.10/site-packages/triton/tools/__init__.py +0 -0
  7. evalkit_tf437/lib/python3.10/site-packages/triton/tools/__pycache__/build_extern.cpython-310.pyc +0 -0
  8. evalkit_tf437/lib/python3.10/site-packages/triton/tools/__pycache__/disasm.cpython-310.pyc +0 -0
  9. evalkit_tf437/lib/python3.10/site-packages/triton/tools/build_extern.py +376 -0
  10. evalkit_tf437/lib/python3.10/site-packages/triton/tools/compile.h +14 -0
  11. evalkit_tf437/lib/python3.10/site-packages/triton/tools/compile.py +145 -0
  12. falcon/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/__init__.cpython-310.pyc +0 -0
  13. falcon/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/all.cpython-310.pyc +0 -0
  14. falcon/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/product.cpython-310.pyc +0 -0
  15. falcon/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/unary.cpython-310.pyc +0 -0
  16. falcon/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  17. falcon/lib/python3.10/site-packages/networkx/drawing/__init__.py +7 -0
  18. falcon/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc +0 -0
  19. falcon/lib/python3.10/site-packages/networkx/drawing/__pycache__/layout.cpython-310.pyc +0 -0
  20. falcon/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc +0 -0
  21. falcon/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc +0 -0
  22. falcon/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc +0 -0
  23. falcon/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-310.pyc +0 -0
  24. falcon/lib/python3.10/site-packages/networkx/drawing/layout.py +1630 -0
  25. falcon/lib/python3.10/site-packages/networkx/drawing/nx_agraph.py +464 -0
  26. falcon/lib/python3.10/site-packages/networkx/drawing/nx_latex.py +572 -0
  27. falcon/lib/python3.10/site-packages/networkx/drawing/nx_pydot.py +352 -0
  28. falcon/lib/python3.10/site-packages/networkx/drawing/nx_pylab.py +1979 -0
  29. falcon/lib/python3.10/site-packages/networkx/drawing/tests/__init__.py +0 -0
  30. falcon/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  31. falcon/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_agraph.cpython-310.pyc +0 -0
  32. falcon/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_latex.cpython-310.pyc +0 -0
  33. falcon/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_layout.cpython-310.pyc +0 -0
  34. falcon/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pydot.cpython-310.pyc +0 -0
  35. falcon/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pylab.cpython-310.pyc +0 -0
  36. falcon/lib/python3.10/site-packages/networkx/drawing/tests/test_agraph.py +241 -0
  37. falcon/lib/python3.10/site-packages/networkx/drawing/tests/test_latex.py +292 -0
  38. falcon/lib/python3.10/site-packages/networkx/drawing/tests/test_layout.py +538 -0
  39. falcon/lib/python3.10/site-packages/networkx/drawing/tests/test_pydot.py +146 -0
  40. falcon/lib/python3.10/site-packages/networkx/drawing/tests/test_pylab.py +1029 -0
  41. falcon/lib/python3.10/site-packages/networkx/tests/__init__.py +0 -0
  42. falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  43. falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_all_random_functions.cpython-310.pyc +0 -0
  44. falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert.cpython-310.pyc +0 -0
  45. falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert_numpy.cpython-310.pyc +0 -0
  46. falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert_pandas.cpython-310.pyc +0 -0
  47. falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert_scipy.cpython-310.pyc +0 -0
  48. falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_exceptions.cpython-310.pyc +0 -0
  49. falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_import.cpython-310.pyc +0 -0
  50. falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_lazy_imports.cpython-310.pyc +0 -0
evalkit_tf437/lib/python3.10/site-packages/triton/compiler/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (442 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/triton/compiler/__pycache__/compiler.cpython-310.pyc ADDED
Binary file (20.7 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/triton/language/extra/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from . import cuda
2
+
3
+ __all__ = ['cuda']
evalkit_tf437/lib/python3.10/site-packages/triton/language/extra/__pycache__/cuda.cpython-310.pyc ADDED
Binary file (792 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/triton/language/semantic.py ADDED
@@ -0,0 +1,1565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations # remove after python 3.11
2
+
3
+ from functools import wraps
4
+ from typing import List, Optional, Sequence, Tuple, TypeVar
5
+
6
+ from .._C.libtriton.triton import ir
7
+ from ..common.build import is_hip
8
+ from . import core as tl
9
+
10
+ T = TypeVar('T')
11
+
12
+ # TODO: redundant code -- remove after 3P backend refactor
13
+
14
+
15
+ def _is_cuda(target):
16
+ from ..compiler.compiler import CudaTargetDescriptor
17
+ return isinstance(target, CudaTargetDescriptor)
18
+
19
+
20
+ # Create custom exception that prints message "hello"
21
+
22
+
23
+ class IncompatibleTypeErrorImpl(Exception):
24
+
25
+ def __init__(self, type_a, type_b):
26
+ self.type_a = type_a
27
+ self.type_b = type_b
28
+ self.message = "invalid operands of type " + self.type_a.__repr__() + " and " + self.type_b.__repr__()
29
+ super(IncompatibleTypeErrorImpl, self).__init__(self.message)
30
+
31
+
32
+ # ===----------------------------------------------------------------------===##
33
+ # Programming Model
34
+ # ===----------------------------------------------------------------------===##
35
+
36
+
37
+ def program_id(axis: int, builder: ir.builder) -> tl.tensor:
38
+ if axis not in (0, 1, 2):
39
+ raise ValueError(f"program_id axis must be 0, 1, or 2 but got {axis}")
40
+ return tl.tensor(builder.create_get_program_id(axis), tl.int32)
41
+
42
+
43
+ def num_programs(axis: int, builder: ir.builder) -> tl.tensor:
44
+ if axis not in (0, 1, 2):
45
+ raise ValueError(f"num_programs axis must be 0, 1, or 2 but got {axis}")
46
+ return tl.tensor(builder.create_get_num_programs(axis), tl.int32)
47
+
48
+
49
+ # ===----------------------------------------------------------------------===//
50
+ # Implicit Casting Utilities
51
+ # ===----------------------------------------------------------------------===//
52
+
53
+
54
+ def integer_promote_impl(a_ty: tl.dtype, b_ty: tl.dtype) -> tl.dtype:
55
+ a_rank = a_ty.int_bitwidth
56
+ b_rank = b_ty.int_bitwidth
57
+ a_sn = a_ty.int_signedness
58
+ b_sn = b_ty.int_signedness
59
+ # Rules for signedness taken from "Usual arithmetic conversions" on
60
+ # https://en.cppreference.com/w/c/language/conversion.
61
+ if a_sn == b_sn:
62
+ return a_ty if a_rank > b_rank else b_ty
63
+ elif a_sn == tl.dtype.SIGNEDNESS.UNSIGNED:
64
+ return a_ty if a_rank >= b_rank else b_ty
65
+ elif b_sn == tl.dtype.SIGNEDNESS.UNSIGNED:
66
+ return b_ty if b_rank >= a_rank else a_ty
67
+ assert False
68
+
69
+
70
+ def computation_type_impl(a_ty: tl.dtype, b_ty: tl.dtype, div_or_mod: bool) -> tl.dtype:
71
+ # 1) if one operand is double, the other is implicitly
72
+ # converted to double
73
+ if a_ty.is_fp64() or b_ty.is_fp64():
74
+ return tl.float64
75
+ # 2) if one operand is float, the other is implicitly
76
+ # converted to float
77
+ if a_ty.is_fp32() or b_ty.is_fp32():
78
+ return tl.float32
79
+ # 3 ) if one operand is half, the other is implicitly converted to half
80
+ # unless we're doing / or %, which do not exist natively in PTX for fp16.
81
+ # Supported PTX op: add, sub, mul, fma, neg, abs, min, max, tanh, ex2, setp
82
+ if a_ty.is_fp16() or b_ty.is_fp16():
83
+ if div_or_mod:
84
+ return tl.float32
85
+ else:
86
+ return tl.float16
87
+ # 4) return bf16 only if both operands are of bf16
88
+ if a_ty.is_bf16() or b_ty.is_bf16():
89
+ if div_or_mod:
90
+ return tl.float32
91
+ if a_ty.is_bf16() and b_ty.is_bf16():
92
+ return tl.bfloat16
93
+ return tl.float32
94
+ if not a_ty.is_int() or not b_ty.is_int():
95
+ assert False
96
+ # 5 ) both operands are integer and undergo
97
+ # integer promotion
98
+ if div_or_mod and a_ty.int_signedness != b_ty.int_signedness:
99
+ raise ValueError("Cannot use /, #, or % with " + a_ty.__repr__() + " and " + b_ty.__repr__() +
100
+ " because they have different signedness;"
101
+ "this is unlikely to result in a useful answer. Cast them to the same signedness.")
102
+ return integer_promote_impl(a_ty, b_ty)
103
+
104
+
105
+ # ===----------------------------------------------------------------------===//
106
+ # Binary Operators
107
+ # ===----------------------------------------------------------------------===//
108
+
109
+
110
+ def check_ptr_type_impl(type_a: tl.dtype, type_b: tl.dtype, allow_ptr_a: bool) -> None:
111
+ if type_a.is_ptr():
112
+ if not allow_ptr_a:
113
+ raise IncompatibleTypeErrorImpl(type_a, type_b)
114
+ # T* + U* with T != U
115
+ if type_b.is_ptr() and (type_a != type_b):
116
+ raise IncompatibleTypeErrorImpl(type_a, type_b)
117
+ # T* + float
118
+ if type_b.is_floating():
119
+ raise IncompatibleTypeErrorImpl(type_a, type_b)
120
+
121
+
122
+ def binary_op_type_checking_impl(lhs: tl.tensor, rhs: tl.tensor, builder: ir.builder, allow_lhs_ptr=False,
123
+ allow_rhs_ptr=False, arithmetic_check=True,
124
+ div_or_mod=False) -> Tuple[tl.tensor, tl.tensor]:
125
+ # implicit broadcasting
126
+ lhs, rhs = broadcast_impl_value(lhs, rhs, builder)
127
+ # implicit typecasting
128
+ lhs_sca_ty = lhs.type.scalar
129
+ rhs_sca_ty = rhs.type.scalar
130
+ check_ptr_type_impl(lhs_sca_ty, rhs_sca_ty, allow_lhs_ptr)
131
+ check_ptr_type_impl(rhs_sca_ty, lhs_sca_ty, allow_rhs_ptr)
132
+ if arithmetic_check and not lhs_sca_ty.is_ptr() and not rhs_sca_ty.is_ptr():
133
+ ret_sca_ty = computation_type_impl(lhs_sca_ty, rhs_sca_ty, div_or_mod)
134
+ lhs = cast(lhs, ret_sca_ty, builder)
135
+ rhs = cast(rhs, ret_sca_ty, builder)
136
+ return lhs, rhs
137
+
138
+
139
+ def add(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
140
+ input, other = binary_op_type_checking_impl(input, other, builder, True, True)
141
+ input_scalar_ty = input.type.scalar
142
+ other_scalar_ty = other.type.scalar
143
+ if input_scalar_ty.is_ptr() and other_scalar_ty.is_ptr():
144
+ raise ValueError("cannot add pointers together")
145
+
146
+ # offset + ptr
147
+ # ptr + offset
148
+ if other_scalar_ty.is_ptr() and not input_scalar_ty.is_ptr():
149
+ input, other = other, input
150
+ input_scalar_ty = input.type.scalar
151
+ other_scalar_ty = other.type.scalar
152
+ if input_scalar_ty.is_ptr():
153
+ return tl.tensor(builder.create_addptr(input.handle, other.handle), input.type)
154
+ # float + float
155
+ elif input_scalar_ty.is_floating():
156
+ return tl.tensor(builder.create_fadd(input.handle, other.handle), input.type)
157
+ # int + int
158
+ elif input_scalar_ty.is_int():
159
+ return tl.tensor(builder.create_add(input.handle, other.handle), input.type)
160
+ assert False
161
+
162
+
163
+ def sub(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
164
+ input, other = binary_op_type_checking_impl(input, other, builder, True, False)
165
+ scalar_ty = input.type.scalar
166
+ # ptr - offset
167
+ if scalar_ty.is_ptr():
168
+ return tl.tensor(builder.create_addptr(input.handle, minus(other, builder).handle), input.type)
169
+ # float - float
170
+ if scalar_ty.is_floating():
171
+ return tl.tensor(builder.create_fsub(input.handle, other.handle), input.type)
172
+ # int - int
173
+ elif scalar_ty.is_int():
174
+ return tl.tensor(builder.create_sub(input.handle, other.handle), input.type)
175
+ assert False
176
+
177
+
178
+ def mul(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
179
+ input, other = binary_op_type_checking_impl(input, other, builder)
180
+ scalar_ty = input.type.scalar
181
+ # float * float
182
+ if scalar_ty.is_floating():
183
+ return tl.tensor(builder.create_fmul(input.handle, other.handle), input.type)
184
+ # * int
185
+ elif scalar_ty.is_int():
186
+ return tl.tensor(builder.create_mul(input.handle, other.handle), input.type)
187
+ assert False
188
+
189
+
190
+ def truediv(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
191
+ input, other = binary_op_type_checking_impl(input, other, builder, False, False, True, True)
192
+ input_scalar_ty = input.type.scalar
193
+ other_scalar_ty = other.type.scalar
194
+ # float / int
195
+ if input_scalar_ty.is_floating() and other_scalar_ty.is_int():
196
+ other = cast(other, input_scalar_ty, builder)
197
+ # int / float
198
+ elif input_scalar_ty.is_int() and other_scalar_ty.is_floating():
199
+ input = cast(input, other_scalar_ty, builder)
200
+ # int / int (cast to tl.float32)
201
+ elif input_scalar_ty.is_int() and other_scalar_ty.is_int():
202
+ input = cast(input, tl.float32, builder)
203
+ other = cast(other, tl.float32, builder)
204
+ # float / float (cast to the highest exponent type)
205
+ elif input_scalar_ty.is_floating() and other_scalar_ty.is_floating():
206
+ if input_scalar_ty.fp_mantissa_width > other_scalar_ty.fp_mantissa_width:
207
+ other = cast(other, input_scalar_ty, builder)
208
+ else:
209
+ input = cast(input, other_scalar_ty, builder)
210
+ # unreachable
211
+ else:
212
+ assert False
213
+ return tl.tensor(builder.create_fdiv(input.handle, other.handle), input.type)
214
+
215
+
216
+ def floordiv(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
217
+ input, other = binary_op_type_checking_impl(input, other, builder, False, False, True, True)
218
+ input_scalar_ty = input.type.scalar
219
+ other_scalar_ty = other.type.scalar
220
+ if input_scalar_ty.is_int() and other_scalar_ty.is_int():
221
+ ret_ty = integer_promote_impl(input_scalar_ty, other_scalar_ty)
222
+ input = cast(input, ret_ty, builder)
223
+ other = cast(other, ret_ty, builder)
224
+ if ret_ty.is_int_signed():
225
+ return tl.tensor(builder.create_sdiv(input.handle, other.handle), input.type)
226
+ else:
227
+ return tl.tensor(builder.create_udiv(input.handle, other.handle), input.type)
228
+ assert False
229
+
230
+
231
+ def fdiv(input: tl.tensor, other: tl.tensor, ieee_rounding: bool, builder: ir.builder) -> tl.tensor:
232
+ input_scalar_ty = input.type.scalar
233
+ other_scalar_ty = other.type.scalar
234
+ if not input_scalar_ty.is_floating() or not other_scalar_ty.is_floating():
235
+ raise ValueError("both operands of fdiv must have floating scalar type")
236
+ input, other = binary_op_type_checking_impl(input, other, builder, False, False, False, True)
237
+ ret = builder.create_fdiv(input.handle, other.handle)
238
+ return tl.tensor(ret, input.type)
239
+
240
+
241
+ def mod(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
242
+ input, other = binary_op_type_checking_impl(input, other, builder, False, False, True, True)
243
+ scalar_ty = input.type.scalar
244
+ other_scalar_ty = other.type.scalar
245
+ # float % float
246
+ if scalar_ty.is_floating():
247
+ # input - input.div(other, rounding_mode="floor") * other
248
+ ret = sub(input, mul(floor(fdiv(input, other, False, builder), builder), other, builder), builder)
249
+ return ret
250
+ # % int
251
+ elif scalar_ty.is_int():
252
+ if scalar_ty.int_signedness != other_scalar_ty.int_signedness:
253
+ raise ValueError("Cannot mod " + scalar_ty.__repr__() + " by " + other_scalar_ty.__repr__() + " "
254
+ "because they have different signedness;"
255
+ "this is unlikely to result in a useful answer. Cast them to the same signedness.")
256
+ if scalar_ty.is_int_signed():
257
+ return tl.tensor(builder.create_srem(input.handle, other.handle), input.type)
258
+ else:
259
+ return tl.tensor(builder.create_urem(input.handle, other.handle), input.type)
260
+ assert False
261
+
262
+
263
+ ##############
264
+ # bitwise ops
265
+ ##############
266
+
267
+
268
+ def bitwise_op_type_checking_impl(input: tl.tensor, other: tl.tensor,
269
+ builder: ir.builder) -> Tuple[tl.tensor, tl.tensor]:
270
+ input, other = binary_op_type_checking_impl(input, other, builder, False, False, False)
271
+ input_sca_ty = input.type.scalar
272
+ other_sca_ty = other.type.scalar
273
+ if not input_sca_ty.is_int() or not other_sca_ty.is_int():
274
+ raise IncompatibleTypeErrorImpl(input_sca_ty, other_sca_ty)
275
+ ret_sca_ty = integer_promote_impl(input_sca_ty, other_sca_ty)
276
+ if ret_sca_ty != input_sca_ty:
277
+ input = cast(input, ret_sca_ty, builder)
278
+ if ret_sca_ty != other_sca_ty:
279
+ other = cast(other, ret_sca_ty, builder)
280
+ return input, other
281
+
282
+
283
+ def and_(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
284
+ input, other = bitwise_op_type_checking_impl(input, other, builder)
285
+ return tl.tensor(builder.create_and(input.handle, other.handle), input.type)
286
+
287
+
288
+ def or_(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
289
+ input, other = bitwise_op_type_checking_impl(input, other, builder)
290
+ return tl.tensor(builder.create_or(input.handle, other.handle), input.type)
291
+
292
+
293
+ def xor_(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
294
+ input, other = bitwise_op_type_checking_impl(input, other, builder)
295
+ return tl.tensor(builder.create_xor(input.handle, other.handle), input.type)
296
+
297
+
298
+ def logical_and(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
299
+ if not input.type.is_int1():
300
+ input = bitcast(input, tl.dtype("int1"), builder)
301
+ if not other.type.is_int1():
302
+ other = bitcast(other, tl.dtype("int1"), builder)
303
+ return and_(input, other, builder)
304
+
305
+
306
+ def logical_or(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
307
+ if not input.type.is_int1():
308
+ input = bitcast(input, tl.dtype("int1"), builder)
309
+ if not other.type.is_int1():
310
+ other = bitcast(other, tl.dtype("int1"), builder)
311
+ return or_(input, other, builder)
312
+
313
+
314
+ def not_(input: tl.tensor, builder: ir.builder):
315
+ if not input.type.is_int1():
316
+ input = bitcast(input, tl.dtype("int1"), builder)
317
+ return invert(input, builder)
318
+
319
+
320
+ def lshr(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
321
+ input, other = bitwise_op_type_checking_impl(input, other, builder)
322
+ return tl.tensor(builder.create_lshr(input.handle, other.handle), input.type)
323
+
324
+
325
+ def ashr(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
326
+ input, other = bitwise_op_type_checking_impl(input, other, builder)
327
+ return tl.tensor(builder.create_ashr(input.handle, other.handle), input.type)
328
+
329
+
330
+ def shl(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
331
+ input, other = bitwise_op_type_checking_impl(input, other, builder)
332
+ return tl.tensor(builder.create_shl(input.handle, other.handle), input.type)
333
+
334
+
335
+ # ===----------------------------------------------------------------------===//
336
+ # Unary Operators
337
+ # ===----------------------------------------------------------------------===//
338
+
339
+
340
+ def plus(input: tl.tensor) -> tl.tensor:
341
+ return input
342
+
343
+
344
+ def minus(input: tl.tensor, builder: ir.builder) -> tl.tensor:
345
+ input_sca_ty = input.type.scalar
346
+ if input_sca_ty.is_ptr():
347
+ raise ValueError("wrong type argument to unary minus (" + input_sca_ty.__repr__() + ")")
348
+ _0 = tl.tensor(builder.get_null_value(input_sca_ty.to_ir(builder)), input_sca_ty)
349
+ return sub(_0, input, builder)
350
+
351
+
352
+ def invert(input: tl.tensor, builder: tl.tensor) -> tl.tensor:
353
+ input_sca_ty = input.type.scalar
354
+ if input_sca_ty.is_ptr() or input_sca_ty.is_floating():
355
+ raise ValueError("wrong type argument to unary invert (" + input_sca_ty.__repr__() + ")")
356
+ _1 = tl.tensor(builder.get_all_ones_value(input_sca_ty.to_ir(builder)), input_sca_ty)
357
+ return xor_(input, _1, builder)
358
+
359
+
360
+ # ===----------------------------------------------------------------------===//
361
+ # Comparison Operators
362
+ # ===----------------------------------------------------------------------===//
363
+ def _bool_like(v: tl.tensor) -> tl.block_type:
364
+ if not v.type.is_block():
365
+ return tl.int1
366
+ shape = v.type.shape
367
+ return tl.block_type(tl.int1, shape)
368
+
369
+
370
+ def greater_than(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
371
+ input, other = binary_op_type_checking_impl(input, other, builder)
372
+ scalar_ty = input.type.scalar
373
+ # float > float
374
+ if scalar_ty.is_floating():
375
+ return tl.tensor(builder.create_fcmpOGT(input.handle, other.handle), _bool_like(input))
376
+ # > int
377
+ elif scalar_ty.is_int():
378
+ if scalar_ty.is_int_signed():
379
+ return tl.tensor(builder.create_icmpSGT(input.handle, other.handle), _bool_like(input))
380
+ else:
381
+ return tl.tensor(builder.create_icmpUGT(input.handle, other.handle), _bool_like(input))
382
+ assert False
383
+
384
+
385
+ def greater_equal(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
386
+ input, other = binary_op_type_checking_impl(input, other, builder)
387
+ scalar_ty = input.type.scalar
388
+ # float >= float
389
+ if scalar_ty.is_floating():
390
+ return tl.tensor(builder.create_fcmpOGE(input.handle, other.handle), _bool_like(input))
391
+ # >= int
392
+ elif scalar_ty.is_int():
393
+ if scalar_ty.is_int_signed():
394
+ return tl.tensor(builder.create_icmpSGE(input.handle, other.handle), _bool_like(input))
395
+ else:
396
+ return tl.tensor(builder.create_icmpUGE(input.handle, other.handle), _bool_like(input))
397
+ assert False
398
+
399
+
400
+ def less_than(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
401
+ input, other = binary_op_type_checking_impl(input, other, builder)
402
+ scalar_ty = input.type.scalar
403
+ # float < float
404
+ if scalar_ty.is_floating():
405
+ return tl.tensor(builder.create_fcmpOLT(input.handle, other.handle), _bool_like(input))
406
+ # < int
407
+ elif scalar_ty.is_int():
408
+ if scalar_ty.is_int_signed():
409
+ return tl.tensor(builder.create_icmpSLT(input.handle, other.handle), _bool_like(input))
410
+ else:
411
+ return tl.tensor(builder.create_icmpULT(input.handle, other.handle), _bool_like(input))
412
+ assert False
413
+
414
+
415
+ def less_equal(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
416
+ input, other = binary_op_type_checking_impl(input, other, builder)
417
+ scalar_ty = input.type.scalar
418
+ # float < float
419
+ if scalar_ty.is_floating():
420
+ return tl.tensor(builder.create_fcmpOLE(input.handle, other.handle), _bool_like(input))
421
+ # < int
422
+ elif scalar_ty.is_int():
423
+ if scalar_ty.is_int_signed():
424
+ return tl.tensor(builder.create_icmpSLE(input.handle, other.handle), _bool_like(input))
425
+ else:
426
+ return tl.tensor(builder.create_icmpULE(input.handle, other.handle), _bool_like(input))
427
+ assert False
428
+
429
+
430
+ def equal(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
431
+ input, other = binary_op_type_checking_impl(input, other, builder)
432
+ scalar_ty = input.type.scalar
433
+ # float == float
434
+ if scalar_ty.is_floating():
435
+ return tl.tensor(builder.create_fcmpOEQ(input.handle, other.handle), _bool_like(input))
436
+ # == int
437
+ elif scalar_ty.is_int():
438
+ return tl.tensor(builder.create_icmpEQ(input.handle, other.handle), _bool_like(input))
439
+ assert False
440
+
441
+
442
+ def not_equal(input: tl.tensor, other: tl.tensor, builder: ir.builder) -> tl.tensor:
443
+ input, other = binary_op_type_checking_impl(input, other, builder)
444
+ scalar_ty = input.type.scalar
445
+ # float == float
446
+ if scalar_ty.is_floating():
447
+ return tl.tensor(builder.create_fcmpUNE(input.handle, other.handle), _bool_like(input))
448
+ # == int
449
+ elif scalar_ty.is_int():
450
+ return tl.tensor(builder.create_icmpNE(input.handle, other.handle), _bool_like(input))
451
+ assert False
452
+
453
+
454
+ # ===----------------------------------------------------------------------===//
455
+ # Block Creation
456
+ # ===----------------------------------------------------------------------===//
457
+
458
+
459
+ def arange(start: int, end: int, builder: ir.builder) -> tl.tensor:
460
+ if not isinstance(start, int) or not isinstance(end, int):
461
+ raise ValueError("arange's arguments must be of type tl.constexpr")
462
+ is_start_int64 = bool(start >> 32)
463
+ is_end_int64 = bool(end >> 32)
464
+ if is_start_int64 or is_end_int64:
465
+ raise ValueError("arange must fit in int32")
466
+ if end <= start:
467
+ raise ValueError("arange's end argument must be greater than the start argument")
468
+
469
+ shape = [end - start]
470
+ ret_ty = tl.block_type(tl.int32, shape)
471
+ return tl.tensor(builder.create_make_range(start, end), ret_ty)
472
+
473
+
474
+ def full(shape: List[int], value, dtype: tl.dtype, builder: ir.builder) -> tl.tensor:
475
+ if isinstance(value, tl.tensor):
476
+ assert value.numel.value == 1, "only accepts size-1 tensor"
477
+ value = cast(value, dtype, builder)
478
+ else:
479
+ # scalar
480
+ if dtype is None:
481
+ raise ValueError("dtype must be specified when value is not a tensor")
482
+ if value == 0:
483
+ value = builder.get_null_value(dtype.to_ir(builder))
484
+ else:
485
+ get_value_fn = getattr(builder, f"get_{dtype.name}")
486
+ value = get_value_fn(value)
487
+ value = tl.tensor(value, dtype)
488
+
489
+ return splat(value, shape, builder)
490
+
491
+
492
+ # ===----------------------------------------------------------------------===//
493
+ # Shape Manipulation
494
+ # ===----------------------------------------------------------------------===//
495
+
496
+
497
+ def splat(value: tl.tensor, shape: List[int], builder: ir.builder) -> tl.tensor:
498
+ assert not value.type.is_block(), "Cannot splat a block tensor"
499
+ if len(shape) == 0:
500
+ return value
501
+ ret_ty = tl.block_type(value.dtype, shape)
502
+ return tl.tensor(builder.create_splat(value.handle, shape), ret_ty)
503
+
504
+
505
+ def view(input: tl.tensor, dst_shape: List[int], builder: ir.builder) -> tl.tensor:
506
+ numel = 1
507
+ for s in dst_shape:
508
+ numel *= s
509
+ if input.type.numel != numel:
510
+ raise ValueError("cannot view block of different shape")
511
+ ret_ty = tl.block_type(input.type.scalar, dst_shape)
512
+ return tl.tensor(builder.create_reshape(input.handle, dst_shape, True), ret_ty)
513
+
514
+
515
+ def reshape(input: tl.tensor, dst_shape: List[int], builder: ir.builder) -> tl.tensor:
516
+ ret_ty = tl.block_type(input.type.scalar, dst_shape)
517
+ return tl.tensor(builder.create_reshape(input.handle, dst_shape, False), ret_ty)
518
+
519
+
520
+ def expand_dims(input: tl.tensor, axis: int, builder: ir.builder) -> tl.tensor:
521
+ dst_shape = [tl._constexpr_to_value(x) for x in input.shape]
522
+ dst_shape.insert(axis, 1)
523
+
524
+ if not input.type.is_block():
525
+ return splat(input, shape=dst_shape, builder=builder)
526
+
527
+ ret_ty = tl.block_type(input.type.scalar, dst_shape)
528
+ return tl.tensor(builder.create_expand_dims(input.handle, axis), ret_ty)
529
+
530
+
531
+ def cat(lhs: tl.tensor, rhs: tl.tensor, can_reorder: bool, builder: ir.builder) -> tl.tensor:
532
+ assert can_reorder, "current implementation of `cat` always may reorder elements"
533
+ assert len(lhs.shape) == 1
534
+ ret_type = tl.block_type(lhs.type.scalar, [lhs.shape[0] + rhs.shape[0]])
535
+ return tl.tensor(builder.create_cat(lhs.handle, rhs.handle), ret_type)
536
+
537
+
538
+ def trans(input: tl.tensor, builder: ir.builder) -> tl.tensor:
539
+ if len(input.shape) != 2:
540
+ raise ValueError("Only 2D tensors can be transposed")
541
+ ret_type = tl.block_type(input.type.scalar, [input.shape[1], input.shape[0]])
542
+ return tl.tensor(builder.create_trans(input.handle), ret_type)
543
+
544
+
545
+ def broadcast_impl_shape(input: tl.tensor, shape: List[int], builder: ir.builder) -> tl.tensor:
546
+ if not input.type.is_block():
547
+ ret_ty = tl.block_type(input.type, shape)
548
+ return tl.tensor(builder.create_splat(input.handle, shape), ret_ty)
549
+ src_shape = input.type.get_block_shapes()
550
+ if len(src_shape) != len(shape):
551
+ raise ValueError(f"Cannot broadcast, rank mismatch: {src_shape}, {shape}")
552
+ if shape == src_shape:
553
+ return input
554
+ for i, item in enumerate(src_shape):
555
+ if shape[i] != item and item != 1:
556
+ raise ValueError(f"Cannot broadcast, the expanded size of the tensor ({shape[i]})"
557
+ f" must match the existing size ({item}) at non-singleton dimension"
558
+ f" {i}: {src_shape}, {shape}")
559
+ ret_ty = tl.block_type(input.type.scalar, shape)
560
+ return tl.tensor(builder.create_broadcast(input.handle, shape), ret_ty)
561
+
562
+
563
+ def broadcast_impl_value(lhs: tl.tensor, rhs: tl.tensor, builder: ir.builder) -> tl.tensor:
564
+ lhs_ty = lhs.type
565
+ rhs_ty = rhs.type
566
+
567
+ # make_shape_compatible(block, scalar)
568
+ if lhs_ty.is_block() and not rhs_ty.is_block():
569
+ rhs_ty = tl.block_type(rhs_ty.scalar, lhs_ty.shape)
570
+ rhs = tl.tensor(builder.create_splat(rhs.handle, lhs_ty.get_block_shapes()), rhs_ty)
571
+ # make_shape_compatible(scalar, block)
572
+ elif not lhs_ty.is_block() and rhs_ty.is_block():
573
+ lhs_ty = tl.block_type(lhs_ty.scalar, rhs_ty.shape)
574
+ lhs = tl.tensor(builder.create_splat(lhs.handle, rhs_ty.get_block_shapes()), lhs_ty)
575
+ # make_shape_compatible(block, block)
576
+ elif lhs_ty.is_block() and rhs_ty.is_block():
577
+ lhs_shape = lhs_ty.get_block_shapes()
578
+ rhs_shape = rhs_ty.get_block_shapes()
579
+
580
+ if len(lhs_shape) < len(rhs_shape):
581
+ # Add new axes to lhs
582
+ for dim in range(len(lhs_shape), len(rhs_shape)):
583
+ lhs = tl.tensor(builder.create_expand_dims(lhs.handle, 0),
584
+ tl.block_type(lhs_ty.scalar, [1] + lhs_shape))
585
+ lhs_ty = lhs.type
586
+ lhs_shape = lhs_ty.get_block_shapes()
587
+ elif len(rhs_shape) < len(lhs_shape):
588
+ # Add new axes to rhs
589
+ for dim in range(len(rhs_shape), len(lhs_shape)):
590
+ rhs = tl.tensor(builder.create_expand_dims(rhs.handle, 0),
591
+ tl.block_type(rhs_ty.scalar, [1] + rhs_shape))
592
+ rhs_ty = rhs.type
593
+ rhs_shape = rhs_ty.get_block_shapes()
594
+ assert len(rhs_shape) == len(lhs_shape)
595
+
596
+ ret_shape = []
597
+ for i, left in enumerate(lhs_shape):
598
+ right = rhs_shape[i]
599
+ if left == 1:
600
+ ret_shape.append(right)
601
+ elif right == 1:
602
+ ret_shape.append(left)
603
+ elif left == right:
604
+ ret_shape.append(left)
605
+ else:
606
+ raise ValueError("Cannot make_shape_compatible: incompatible dimensions "
607
+ "at index " + str(i) + ": " + str(left) + " and " + str(right))
608
+ if lhs_shape != ret_shape:
609
+ ret_ty = tl.block_type(lhs_ty.scalar, ret_shape)
610
+ lhs = tl.tensor(builder.create_broadcast(lhs.handle, ret_shape), ret_ty)
611
+ if rhs_shape != ret_shape:
612
+ ret_ty = tl.block_type(rhs_ty.scalar, ret_shape)
613
+ rhs = tl.tensor(builder.create_broadcast(rhs.handle, ret_shape), ret_ty)
614
+ # (scalar, scalar) => returns original blocks
615
+ return lhs, rhs
616
+
617
+
618
+ #######
619
+ # cast
620
+ #######
621
+
622
+
623
+ def bitcast(input: tl.tensor, dst_ty: tl.dtype, builder: ir.builder) -> tl.tensor:
624
+ src_ty = input.type
625
+ if src_ty.is_block():
626
+ dst_ty = tl.block_type(dst_ty.scalar, input.type.get_block_shapes())
627
+ if src_ty == dst_ty:
628
+ return input
629
+ src_sca_ty = src_ty.scalar
630
+ dst_sca_ty = dst_ty.scalar
631
+ if src_sca_ty.is_ptr() or dst_sca_ty.is_ptr():
632
+ return cast(input, dst_ty, builder)
633
+ # Bitcast
634
+ src_bits = src_sca_ty.primitive_bitwidth
635
+ dst_bits = dst_sca_ty.primitive_bitwidth
636
+ if src_bits != dst_bits:
637
+ raise ValueError("Cannot bitcast data-type of size " + str(src_bits) + " to "
638
+ "data-type of size " + str(dst_bits))
639
+ return tl.tensor(builder.create_bitcast(input.handle, dst_ty.to_ir(builder)), dst_ty)
640
+
641
+
642
+ def cast(input: tl.tensor, dst_ty: tl.dtype, builder: ir.builder) -> tl.tensor:
643
+ src_ty = input.type
644
+ if isinstance(dst_ty, tl.constexpr):
645
+ dst_ty = dst_ty.value
646
+ if src_ty.is_block():
647
+ dst_ty = tl.block_type(dst_ty.scalar, input.type.get_block_shapes())
648
+ if src_ty == dst_ty:
649
+ return input
650
+
651
+ src_sca_ty = src_ty.scalar
652
+ dst_sca_ty = dst_ty.scalar
653
+
654
+ if _is_cuda(builder.target) and builder.target.capability < 89 and \
655
+ (src_sca_ty.is_fp8e4nv() or dst_sca_ty.is_fp8e4nv()):
656
+ assert False, "fp8e4nv data type is not supported on CUDA arch < 89"
657
+
658
+ # Casting with customized floating types involved: fp8 <=> bf16, fp16, fp32, fp64
659
+ if (src_sca_ty.is_fp8() and dst_sca_ty.is_floating()) or \
660
+ (src_sca_ty.is_floating() and dst_sca_ty.is_fp8()):
661
+ return tl.tensor(builder.create_fp_to_fp(input.handle, dst_ty.to_ir(builder)), dst_ty)
662
+
663
+ # bf16 <=> (not fp32)
664
+ if (src_sca_ty.is_fp16() and not dst_sca_ty.is_fp32()) or \
665
+ (src_sca_ty.is_bf16() and not dst_sca_ty.is_fp32()):
666
+ return cast(cast(input, tl.float32, builder), dst_sca_ty, builder)
667
+
668
+ # Standard floating types' casting: truncation
669
+ # fp64 => fp32, fp16, bf16
670
+ # fp32 => fp16, bf16
671
+ truncate_fp = src_sca_ty.is_floating() and \
672
+ dst_sca_ty.is_floating() and \
673
+ src_sca_ty.primitive_bitwidth > dst_sca_ty.primitive_bitwidth
674
+ if truncate_fp:
675
+ return tl.tensor(builder.create_fp_trunc(input.handle, dst_ty.to_ir(builder)), dst_ty)
676
+
677
+ # Standard floating types' casting: extension
678
+ # fp32 => fp64
679
+ # fp16 => fp32, fp64
680
+ # bf16 => fp32, fp64
681
+ ext_fp = src_sca_ty.is_floating() and \
682
+ dst_sca_ty.is_floating() and \
683
+ src_sca_ty.primitive_bitwidth < dst_sca_ty.primitive_bitwidth
684
+ if ext_fp:
685
+ return tl.tensor(builder.create_fp_ext(input.handle, dst_ty.to_ir(builder)), dst_ty)
686
+
687
+ # Casting between integer types
688
+ if src_sca_ty.is_int() and dst_sca_ty.is_int() and \
689
+ (src_sca_ty.int_bitwidth != dst_sca_ty.int_bitwidth or src_sca_ty.int_signedness != dst_sca_ty.int_signedness):
690
+ sign_extend = src_sca_ty.is_int_signed() and not src_sca_ty.is_bool()
691
+ if dst_sca_ty.is_bool():
692
+ ty = input.dtype.to_ir(builder)
693
+ _0 = tl.tensor(builder.get_null_value(ty), input.dtype)
694
+ return not_equal(input, _0, builder)
695
+ else:
696
+ return tl.tensor(builder.create_int_cast(input.handle, dst_ty.to_ir(builder), sign_extend), dst_ty)
697
+
698
+ # Casting standard floating types to integer types
699
+ if src_sca_ty.is_standard_floating() and dst_sca_ty.is_int():
700
+ if dst_sca_ty.is_bool():
701
+ ty = input.dtype.to_ir(builder)
702
+ _0 = tl.tensor(builder.get_null_value(ty), input.dtype)
703
+ return not_equal(input, _0, builder)
704
+ elif dst_sca_ty.is_int_signed():
705
+ return tl.tensor(builder.create_fp_to_si(input.handle, dst_ty.to_ir(builder)), dst_ty)
706
+ else:
707
+ return tl.tensor(builder.create_fp_to_ui(input.handle, dst_ty.to_ir(builder)), dst_ty)
708
+
709
+ # Casting integer types to standard floating types
710
+ if src_sca_ty.is_int() and dst_sca_ty.is_standard_floating():
711
+ if src_sca_ty.is_bool() or not src_sca_ty.is_int_signed():
712
+ return tl.tensor(builder.create_ui_to_fp(input.handle, dst_ty.to_ir(builder)), dst_ty)
713
+ else:
714
+ return tl.tensor(builder.create_si_to_fp(input.handle, dst_ty.to_ir(builder)), dst_ty)
715
+
716
+ # Casting pointer types to integer types
717
+ if src_sca_ty.is_ptr() and dst_sca_ty.is_int():
718
+ bitwidth = dst_sca_ty.int_bitwidth
719
+ if bitwidth == 64:
720
+ return tl.tensor(builder.create_ptr_to_int(input.handle, dst_ty.to_ir(builder)), dst_ty)
721
+ if bitwidth == 1:
722
+ return not_equal(cast(input, tl.int64, builder), tl.tensor(builder.get_int64(0), tl.int64), builder)
723
+
724
+ # Casting integer types to pointer types
725
+ if src_sca_ty.is_int() and dst_sca_ty.is_ptr():
726
+ return tl.tensor(builder.create_int_to_ptr(input.handle, dst_ty.to_ir(builder)), dst_ty)
727
+
728
+ # Casting pointer types to pointer types
729
+ if src_sca_ty.is_ptr() and dst_sca_ty.is_ptr():
730
+ return tl.tensor(builder.create_bitcast(input.handle, dst_ty.to_ir(builder)), dst_ty)
731
+
732
+ assert False, f'cannot cast {input} to {dst_ty}'
733
+
734
+
735
+ # ===----------------------------------------------------------------------===//
736
+ # Memory Operators
737
+ # ===----------------------------------------------------------------------===//
738
+
739
+
740
+ def _str_to_load_cache_modifier(cache_modifier):
741
+ cache = ir.CACHE_MODIFIER.NONE # default
742
+ if cache_modifier:
743
+ if cache_modifier == ".ca":
744
+ cache = ir.CACHE_MODIFIER.CA
745
+ elif cache_modifier == ".cg":
746
+ cache = ir.CACHE_MODIFIER.CG
747
+ else:
748
+ raise ValueError(f"Cache modifier {cache_modifier} not supported")
749
+ return cache
750
+
751
+
752
+ def _str_to_store_cache_modifier(cache_modifier):
753
+ cache = ir.CACHE_MODIFIER.NONE # default
754
+ if cache_modifier:
755
+ if cache_modifier == ".wb":
756
+ cache = ir.CACHE_MODIFIER.WB
757
+ elif cache_modifier == ".cg":
758
+ cache = ir.CACHE_MODIFIER.CG
759
+ elif cache_modifier == ".cs":
760
+ cache = ir.CACHE_MODIFIER.CS
761
+ elif cache_modifier == ".wt":
762
+ cache = ir.CACHE_MODIFIER.WT
763
+ else:
764
+ raise ValueError(f"Cache modifier {cache_modifier} not supported")
765
+ return cache
766
+
767
+
768
+ def _str_to_eviction_policy(eviction_policy):
769
+ eviction = ir.EVICTION_POLICY.NORMAL # default
770
+ if eviction_policy:
771
+ if eviction_policy == "evict_last":
772
+ eviction = ir.EVICTION_POLICY.EVICT_LAST
773
+ elif eviction_policy == "evict_first":
774
+ eviction = ir.EVICTION_POLICY.EVICT_FIRST
775
+ else:
776
+ raise ValueError(f"Eviction policy {eviction_policy} not supported")
777
+ return eviction
778
+
779
+
780
+ def _str_to_padding_option(padding_option):
781
+ padding = None # default
782
+ if padding_option:
783
+ if padding_option == "zero":
784
+ padding = ir.PADDING_OPTION.PAD_ZERO
785
+ elif padding_option == "nan":
786
+ padding = ir.PADDING_OPTION.PAD_NAN
787
+ else:
788
+ raise ValueError(f"Padding option {padding_option} not supported")
789
+ return padding
790
+
791
+
792
+ def _str_to_sem(sem_option):
793
+ sem = ir.MEM_SEMANTIC.ACQUIRE_RELEASE
794
+ if sem_option:
795
+ if sem_option == "acquire":
796
+ sem = ir.MEM_SEMANTIC.ACQUIRE
797
+ elif sem_option == "release":
798
+ sem = ir.MEM_SEMANTIC.RELEASE
799
+ elif sem_option == "acq_rel":
800
+ sem = ir.MEM_SEMANTIC.ACQUIRE_RELEASE
801
+ elif sem_option == "relaxed":
802
+ sem = ir.MEM_SEMANTIC.RELAXED
803
+ else:
804
+ raise ValueError(f"Memory semantic {sem_option} not supported")
805
+ return sem
806
+
807
+
808
+ def _str_to_scope(scope_option):
809
+ scope = ir.MEM_SYNC_SCOPE.GPU
810
+ if scope_option:
811
+ if scope_option == "gpu":
812
+ scope = ir.MEM_SYNC_SCOPE.GPU
813
+ elif scope_option == "cta":
814
+ scope = ir.MEM_SYNC_SCOPE.CTA
815
+ elif scope_option == "sys":
816
+ scope = ir.MEM_SYNC_SCOPE.SYSTEM
817
+ else:
818
+ raise ValueError(f"Memory semantic {scope_option} not supported")
819
+ return scope
820
+
821
+
822
+ def _canonicalize_boundary_check(boundary_check, block_shape):
823
+ if boundary_check:
824
+ if not hasattr(boundary_check, "__iter__"):
825
+ boundary_check = [boundary_check]
826
+ boundary_check = [elem.value if isinstance(elem, tl.constexpr) else elem for elem in boundary_check]
827
+ for dim in boundary_check:
828
+ assert isinstance(dim, int) and 0 <= dim < len(block_shape)
829
+ assert len(boundary_check) > 0
830
+ assert len(boundary_check) == len(set(boundary_check)), "Duplicate dimension in `boundary_check`"
831
+ return sorted(boundary_check)
832
+ return tuple()
833
+
834
+
835
+ def _load_block_pointer(ptr, mask, other, boundary_check, padding, cache, eviction, is_volatile, builder):
836
+ # Load by a block pointer: `pointer_type<block_type<>>`
837
+ # Block pointer can not have `mask` and `other` arguments
838
+ if mask or other:
839
+ raise ValueError("`mask` and `other` arguments cannot be specified for loading block pointers")
840
+
841
+ elt_ty = ptr.type.element_ty.element_ty
842
+ assert elt_ty != tl.int1, "`tl.int1` should be rewrited in `tl.make_block_ptr`"
843
+ if elt_ty.is_int() and padding == ir.PADDING_OPTION.PAD_NAN:
844
+ raise ValueError("Padding option `nan` is not supported for integer block pointers")
845
+
846
+ # `dst_ty` is de-referenced type of the pointer type
847
+ dst_ty = ptr.type.element_ty
848
+
849
+ # Check `boundary_check` argument
850
+ boundary_check = _canonicalize_boundary_check(boundary_check, dst_ty.get_block_shapes())
851
+
852
+ # Build IR
853
+ return tl.tensor(
854
+ builder.create_tensor_pointer_load(ptr.handle, boundary_check, padding, cache, eviction, is_volatile), dst_ty)
855
+
856
+
857
+ def _load_legacy(ptr, mask, other, boundary_check, padding, cache, eviction, is_volatile, builder):
858
+ # Load by a tensor of pointers or a pointer of scalar: `block_type<pointer_type<>>` or `pointer_type<>`
859
+ if not ptr.type.scalar.is_ptr():
860
+ raise ValueError(f"Unsupported ptr type {ptr.type.__repr__()} in `tl.load`")
861
+
862
+ # Check `mask`, `other`, `boundary_check`, and `padding` arguments
863
+ if not mask and other:
864
+ raise ValueError("`other` cannot be provided without `mask`")
865
+ if padding or boundary_check:
866
+ raise ValueError("`padding_option` or `boundary_check` argument is not supported for loading a tensor of"
867
+ "pointers or loading a scalar. Because the compiler does not know the boundary; please "
868
+ "use block pointers (defined by `make_block_ptr`) instead")
869
+
870
+ # For a pointer of scalar, check the type of `mask` and `other`
871
+ if not ptr.type.is_block():
872
+ if mask and mask.type.is_block():
873
+ raise ValueError("Mask argument cannot be block type if pointer argument is not a block")
874
+ if other and other.type.is_block():
875
+ raise ValueError("Other argument cannot be block type if pointer argument is not a block")
876
+
877
+ # Make `mask` and `other` into the same shape as `ptr`
878
+ if ptr.type.is_block():
879
+ if mask:
880
+ mask = broadcast_impl_shape(mask, ptr.type.get_block_shapes(), builder)
881
+ if other:
882
+ other = broadcast_impl_shape(other, ptr.type.get_block_shapes(), builder)
883
+
884
+ # Get `pointer_type<elt_ty>` and `elt_ty`
885
+ ptr_ty = ptr.type.scalar
886
+ elt_ty = ptr_ty.element_ty
887
+
888
+ # Treat `pointer_type<tl.int1>` as `pointer_type<tl.int8>`
889
+ if elt_ty == tl.int1:
890
+ elt_ty = tl.int8
891
+ ptr_ty = tl.pointer_type(elt_ty, ptr_ty.address_space)
892
+ ptr = cast(ptr, ptr_ty, builder)
893
+
894
+ # Cast `other` into `ele_ty` type
895
+ if other:
896
+ other = cast(other, elt_ty, builder)
897
+
898
+ # Create loaded result type `dst_ty`
899
+ if ptr.type.is_block():
900
+ shape = ptr.type.get_block_shapes()
901
+ dst_ty = tl.block_type(elt_ty, shape)
902
+ else:
903
+ # Load by de-referencing the pointer of scalar
904
+ dst_ty = elt_ty
905
+
906
+ # Build IR
907
+ if not mask:
908
+ return tl.tensor(builder.create_load(ptr.handle, cache, eviction, is_volatile), dst_ty)
909
+ else:
910
+ return tl.tensor(
911
+ builder.create_masked_load(ptr.handle, mask.handle, other.handle if other else None, cache, eviction,
912
+ is_volatile), dst_ty)
913
+
914
+
915
+ def load(ptr: tl.tensor, mask: Optional[tl.tensor], other: Optional[tl.tensor], boundary_check, padding_option: str,
916
+ cache_modifier: str, eviction_policy: str, is_volatile: bool, builder: ir.builder) -> tl.tensor:
917
+ # Cache, eviction and padding options
918
+ cache = _str_to_load_cache_modifier(cache_modifier)
919
+ eviction = _str_to_eviction_policy(eviction_policy)
920
+ padding = _str_to_padding_option(padding_option)
921
+
922
+ if ptr.type.is_ptr() and ptr.type.element_ty.is_block():
923
+ # Load by a block pointer: `pointer_type<block_type<>>`
924
+ return _load_block_pointer(ptr, mask, other, boundary_check, padding, cache, eviction, is_volatile, builder)
925
+ else:
926
+ # Load by a tensor of pointers or a pointer of scalar: `block_type<pointer_type<>>` or `pointer_type<>`
927
+ return _load_legacy(ptr, mask, other, boundary_check, padding, cache, eviction, is_volatile, builder)
928
+
929
+
930
+ def _store_block_pointer(ptr, val, mask, boundary_check, cache, eviction, builder):
931
+ # Store by a block pointer: `pointer_type<block_type<>>`
932
+ # Block pointers can not have the `mask` argument
933
+ if mask:
934
+ raise ValueError("`mask` and `other` arguments cannot be specified for loading block pointers")
935
+
936
+ # Check same shape and element type
937
+ block_shape = ptr.type.element_ty.get_block_shapes()
938
+ if not val.type.is_block():
939
+ val = broadcast_impl_shape(val, block_shape, builder)
940
+ assert val.type.is_block(), "Value argument must be block type or a scalar"
941
+ assert block_shape == val.type.get_block_shapes(
942
+ ), f"Block shape({block_shape}) and value shape({val.type.get_block_shapes()}) mismatch"
943
+ assert ptr.type.element_ty.element_ty == val.type.element_ty, f"Block element type({ptr.type.element_ty.element_ty}) and value element type({val.type.element_ty}) mismatch"
944
+
945
+ elt_ty = ptr.type.element_ty.element_ty
946
+ assert elt_ty != tl.int1, "`tl.int1` should be rewrited in `tl.make_block_ptr`"
947
+
948
+ # Check `boundary_check` argument
949
+ boundary_check = _canonicalize_boundary_check(boundary_check, block_shape)
950
+
951
+ # Build IR
952
+ return tl.tensor(builder.create_tensor_pointer_store(ptr.handle, val.handle, boundary_check, cache, eviction),
953
+ tl.void)
954
+
955
+
956
+ def _store_legacy(ptr, val, mask, boundary_check, cache, eviction, builder):
957
+ # Store by a tensor of pointers or a pointer of scalar: `block_type<pointer_type<>>` or `pointer_type<>`
958
+ if not ptr.type.scalar.is_ptr():
959
+ raise ValueError(f"Unsupported ptr type {ptr.type.__repr__()} in `tl.store`")
960
+
961
+ # Check `boundary_check` argument
962
+ if boundary_check:
963
+ raise ValueError("`boundary_check` argument is not supported for storing a tensor of pointers or storing a "
964
+ "scalar. Because the compiler does not know the boundary; please use block pointers "
965
+ "(defined by `make_block_ptr`) instead")
966
+
967
+ # For a pointer of scalar, check the type of `val` and `mask`
968
+ if not ptr.type.is_block():
969
+ if val.type.is_block():
970
+ raise ValueError("Value argument cannot be block type if pointer argument is not a block")
971
+ if mask and mask.type.is_block():
972
+ raise ValueError("Mask argument cannot be block type if pointer argument is not a block")
973
+
974
+ # Make `mask` and `val` into the same shape as `ptr`
975
+ if ptr.type.is_block():
976
+ val = broadcast_impl_shape(val, ptr.type.get_block_shapes(), builder)
977
+ if mask:
978
+ mask = broadcast_impl_shape(mask, ptr.type.get_block_shapes(), builder)
979
+
980
+ ptr_ty = ptr.type.scalar
981
+ elt_ty = ptr_ty.element_ty
982
+
983
+ # Treat `pointer_type<tl.int1>` as `pointer_type<tl.int8>`
984
+ if elt_ty == tl.int1:
985
+ elt_ty = tl.int8
986
+ ptr_ty = tl.pointer_type(elt_ty, ptr_ty.address_space)
987
+ ptr = cast(ptr, ptr_ty, builder)
988
+
989
+ # Cast to target data type
990
+ val = cast(val, elt_ty, builder)
991
+
992
+ # Build IR
993
+ if not mask:
994
+ return tl.tensor(builder.create_store(ptr.handle, val.handle, cache, eviction), tl.void)
995
+ if not mask.type.scalar.is_bool():
996
+ raise ValueError("Mask must have boolean scalar type")
997
+ return tl.tensor(builder.create_masked_store(ptr.handle, val.handle, mask.handle, cache, eviction), tl.void)
998
+
999
+
1000
+ def store(ptr: tl.tensor, val: tl.tensor, mask: Optional[tl.tensor], boundary_check, cache_modifier: str,
1001
+ eviction_policy: str, builder: ir.builder) -> tl.tensor:
1002
+ # Cache and eviction options
1003
+ cache = _str_to_store_cache_modifier(cache_modifier)
1004
+ eviction = _str_to_eviction_policy(eviction_policy)
1005
+
1006
+ if ptr.type.is_ptr() and ptr.type.element_ty.is_block():
1007
+ # Store by a block pointer: `pointer_type<block_type<>>`
1008
+ return _store_block_pointer(ptr, val, mask, boundary_check, cache, eviction, builder)
1009
+ else:
1010
+ # Store by a tensor of pointers or a pointer of scalar: `block_type<pointer_type<>>` or `pointer_type<>`
1011
+ return _store_legacy(ptr, val, mask, boundary_check, cache, eviction, builder)
1012
+
1013
+
1014
+ #########
1015
+ # atomic
1016
+ #########
1017
+
1018
+
1019
+ def atomic_cas(ptr: tl.tensor, cmp: tl.tensor, val: tl.tensor, sem: str, scope: str, builder: ir.builder) -> tl.tensor:
1020
+ sem = _str_to_sem(sem)
1021
+ scope = _str_to_scope(scope)
1022
+ element_ty = ptr.type.scalar.element_ty
1023
+ if element_ty.primitive_bitwidth not in [16, 32, 64]:
1024
+ raise ValueError("atomic_cas only supports elements with width {16, 32, 64}")
1025
+ return tl.tensor(builder.create_atomic_cas(ptr.handle, cmp.handle, val.handle, sem, scope), val.type)
1026
+
1027
+
1028
+ def atom_red_typechecking_impl(ptr: tl.tensor, val: tl.tensor, mask: tl.tensor, op: str,
1029
+ builder: ir.builder) -> Tuple[tl.tensor, tl.tensor, tl.tensor]:
1030
+ if not ptr.type.scalar.is_ptr():
1031
+ raise ValueError("Pointer argument of store instruction is " + ptr.type.__repr__())
1032
+ element_ty = ptr.type.scalar.element_ty
1033
+ if element_ty is tl.float16 and op != 'add':
1034
+ raise ValueError("atomic_" + op + " does not support fp16")
1035
+ if element_ty in [tl.int1, tl.int8, tl.int16, tl.bfloat16]:
1036
+ raise ValueError("atomic_" + op + " does not support " + str(element_ty))
1037
+ if ptr.type.is_block():
1038
+ if mask:
1039
+ mask = broadcast_impl_shape(mask, ptr.type.get_block_shapes(), builder)
1040
+ if val:
1041
+ val = broadcast_impl_shape(val, ptr.type.get_block_shapes(), builder)
1042
+ val = cast(val, ptr.type.scalar.element_ty, builder)
1043
+ if not mask:
1044
+ mask_ir = builder.get_int1(True)
1045
+ mask_ty = tl.int1
1046
+ if ptr.type.is_block():
1047
+ mask_ir = builder.create_splat(mask_ir, ptr.type.get_block_shapes())
1048
+ mask_ty = tl.block_type(tl.int1, ptr.type.get_block_shapes())
1049
+ mask = tl.tensor(mask_ir, mask_ty)
1050
+ return ptr, val, mask
1051
+
1052
+
1053
+ def atomic_max(ptr: tl.tensor, val: tl.tensor, mask: tl.tensor, sem: str, scope: str, builder: ir.builder) -> tl.tensor:
1054
+ ptr, val, mask = atom_red_typechecking_impl(ptr, val, mask, 'max', builder)
1055
+ sem = _str_to_sem(sem)
1056
+ scope = _str_to_scope(scope)
1057
+ sca_ty = val.type.scalar
1058
+ # direct call to atomic_max for integers
1059
+ if sca_ty.is_int():
1060
+ if sca_ty.is_int_signed():
1061
+ return tl.tensor(
1062
+ builder.create_atomic_rmw(ir.ATOMIC_OP.MAX, ptr.handle, val.handle, mask.handle, sem, scope), val.type)
1063
+ else:
1064
+ return tl.tensor(
1065
+ builder.create_atomic_rmw(ir.ATOMIC_OP.UMAX, ptr.handle, val.handle, mask.handle, sem, scope), val.type)
1066
+ # for float
1067
+ # return atomic_smax(i_ptr, i_val) if val >= 0
1068
+ # return atomic_umin(i_ptr, i_val) if val < 0
1069
+ if sca_ty not in {tl.float32, tl.float64}:
1070
+ raise TypeError(f"atomic_max not supported for dtype {sca_ty}")
1071
+
1072
+ itype = tl.int32 if sca_ty == tl.float32 else tl.float64
1073
+ zero = full([], 0.0, sca_ty, builder)
1074
+
1075
+ i_val = bitcast(val, itype, builder)
1076
+ i_ptr = bitcast(ptr, tl.pointer_type(itype, 1), builder)
1077
+ pos = greater_equal(val, zero, builder)
1078
+ neg = less_than(val, zero, builder)
1079
+ pos_ret = tl.tensor(
1080
+ builder.create_atomic_rmw(ir.ATOMIC_OP.MAX, i_ptr.handle, i_val.handle,
1081
+ and_(mask, pos, builder).handle, sem, scope), i_val.type)
1082
+ neg_ret = tl.tensor(
1083
+ builder.create_atomic_rmw(ir.ATOMIC_OP.UMIN, i_ptr.handle, i_val.handle,
1084
+ and_(mask, neg, builder).handle, sem, scope), i_val.type)
1085
+ ret = where(pos, pos_ret, neg_ret, builder)
1086
+ return bitcast(ret, sca_ty, builder)
1087
+
1088
+
1089
+ def atomic_min(ptr: tl.tensor, val: tl.tensor, mask: tl.tensor, sem: str, scope: str, builder: ir.builder) -> tl.tensor:
1090
+ ptr, val, mask = atom_red_typechecking_impl(ptr, val, mask, 'min', builder)
1091
+ sem = _str_to_sem(sem)
1092
+ scope = _str_to_scope(scope)
1093
+ sca_ty = val.type.scalar
1094
+ # direct call to atomic_min for integers
1095
+ if sca_ty.is_int():
1096
+ if sca_ty.is_int_signed():
1097
+ return tl.tensor(
1098
+ builder.create_atomic_rmw(ir.ATOMIC_OP.MIN, ptr.handle, val.handle, mask.handle, sem, scope), val.type)
1099
+ else:
1100
+ return tl.tensor(
1101
+ builder.create_atomic_rmw(ir.ATOMIC_OP.UMIN, ptr.handle, val.handle, mask.handle, sem, scope), val.type)
1102
+ # for float
1103
+ # return atomic_smin(i_ptr, i_val) if val >= 0
1104
+ # return atomic_umax(i_ptr, i_val) if val < 0
1105
+ if sca_ty not in {tl.float32, tl.float64}:
1106
+ raise TypeError(f"atomic_min not supported for dtype {sca_ty}")
1107
+
1108
+ itype = tl.int32 if sca_ty == tl.float32 else tl.float64
1109
+ zero = full([], 0.0, sca_ty, builder)
1110
+
1111
+ i_val = bitcast(val, itype, builder)
1112
+ i_ptr = bitcast(ptr, tl.pointer_type(itype, 1), builder)
1113
+ pos = greater_equal(val, zero, builder)
1114
+ neg = less_than(val, zero, builder)
1115
+ pos_ret = tl.tensor(
1116
+ builder.create_atomic_rmw(ir.ATOMIC_OP.MIN, i_ptr.handle, i_val.handle,
1117
+ and_(mask, pos, builder).handle, sem, scope), i_val.type)
1118
+ neg_ret = tl.tensor(
1119
+ builder.create_atomic_rmw(ir.ATOMIC_OP.UMAX, i_ptr.handle, i_val.handle,
1120
+ and_(mask, neg, builder).handle, sem, scope), i_val.type)
1121
+ ret = where(pos, pos_ret, neg_ret, builder)
1122
+ return bitcast(ret, sca_ty, builder)
1123
+
1124
+
1125
+ def atomic_add(ptr: tl.tensor, val: tl.tensor, mask: tl.tensor, sem: str, scope: str, builder: ir.builder) -> tl.tensor:
1126
+ ptr, val, mask = atom_red_typechecking_impl(ptr, val, mask, 'add', builder)
1127
+ sem = _str_to_sem(sem)
1128
+ scope = _str_to_scope(scope)
1129
+ sca_ty = val.type.scalar
1130
+ op = ir.ATOMIC_OP.FADD if sca_ty.is_floating() else ir.ATOMIC_OP.ADD
1131
+ return tl.tensor(builder.create_atomic_rmw(op, ptr.handle, val.handle, mask.handle, sem, scope), val.type)
1132
+
1133
+
1134
+ def atomic_and(ptr: tl.tensor, val: tl.tensor, mask: tl.tensor, sem: str, scope: str, builder: ir.builder) -> tl.tensor:
1135
+ ptr, val, mask = atom_red_typechecking_impl(ptr, val, mask, 'and', builder)
1136
+ sem = _str_to_sem(sem)
1137
+ scope = _str_to_scope(scope)
1138
+ return tl.tensor(builder.create_atomic_rmw(ir.ATOMIC_OP.AND, ptr.handle, val.handle, mask.handle, sem, scope),
1139
+ val.type)
1140
+
1141
+
1142
+ def atomic_or(ptr: tl.tensor, val: tl.tensor, mask: tl.tensor, sem: str, scope: str, builder: ir.builder) -> tl.tensor:
1143
+ ptr, val, mask = atom_red_typechecking_impl(ptr, val, mask, 'or', builder)
1144
+ sem = _str_to_sem(sem)
1145
+ scope = _str_to_scope(scope)
1146
+ return tl.tensor(builder.create_atomic_rmw(ir.ATOMIC_OP.OR, ptr.handle, val.handle, mask.handle, sem, scope),
1147
+ val.type)
1148
+
1149
+
1150
+ def atomic_xor(ptr: tl.tensor, val: tl.tensor, mask: tl.tensor, sem: str, scope: str, builder: ir.builder) -> tl.tensor:
1151
+ ptr, val, mask = atom_red_typechecking_impl(ptr, val, mask, 'xor', builder)
1152
+ sem = _str_to_sem(sem)
1153
+ scope = _str_to_scope(scope)
1154
+ return tl.tensor(builder.create_atomic_rmw(ir.ATOMIC_OP.XOR, ptr.handle, val.handle, mask.handle, sem, scope),
1155
+ val.type)
1156
+
1157
+
1158
+ def atomic_xchg(ptr: tl.tensor, val: tl.tensor, mask: tl.tensor, sem: str, scope: str,
1159
+ builder: ir.builder) -> tl.tensor:
1160
+ ptr, val, mask = atom_red_typechecking_impl(ptr, val, mask, 'xchg', builder)
1161
+ sem = _str_to_sem(sem)
1162
+ scope = _str_to_scope(scope)
1163
+ return tl.tensor(builder.create_atomic_rmw(ir.ATOMIC_OP.XCHG, ptr.handle, val.handle, mask.handle, sem, scope),
1164
+ val.type)
1165
+
1166
+
1167
+ # ===----------------------------------------------------------------------===//
1168
+ # Linear Algebra
1169
+ # ===----------------------------------------------------------------------===//
1170
+
1171
+
1172
+ def gpu_has_mfma() -> bool:
1173
+ if not is_hip():
1174
+ return False
1175
+ return True # mfma supported in ['gfx908', 'gfx90a']
1176
+
1177
+
1178
+ def mfma_supported(M, N, K, allow_tf32, ret_scalar_ty) -> bool:
1179
+ if not gpu_has_mfma():
1180
+ return False
1181
+ # TODO: Add check for configurations and types.
1182
+ return True
1183
+
1184
+
1185
+ def dot(lhs: tl.tensor, rhs: tl.tensor, acc: tl.tensor, allow_tf32: bool, max_num_imprecise_acc: int,
1186
+ out_dtype: tl.dtype, builder: ir.builder) -> tl.tensor:
1187
+
1188
+ def assert_dtypes_valid(lhs_dtype, rhs_dtype, target):
1189
+ # Checks for non-cuda archs
1190
+ if not _is_cuda(target):
1191
+ assert lhs_dtype == rhs_dtype, f"First input ({lhs_dtype}) and second input ({rhs_dtype}) must have the same dtype!"
1192
+ return
1193
+ # Checks for cuda arch
1194
+ if target.capability < 90:
1195
+ assert not lhs_dtype.is_fp8e4nv() and not rhs_dtype.is_fp8e4nv(
1196
+ ), "Dot op does not support fp8e4nv on CUDA arch < 90"
1197
+ if lhs_dtype.is_fp8() and rhs_dtype.is_fp8():
1198
+ return
1199
+ assert lhs_dtype == rhs_dtype, f"First input ({lhs_dtype}) and second input ({rhs_dtype}) must have the same dtype!"
1200
+ else:
1201
+ assert not lhs_dtype.is_fp8e4b15() and not rhs_dtype.is_fp8e4b15(
1202
+ ), "Dot op does not support fp8e4b15 on CUDA arch >= 90"
1203
+ assert not lhs_dtype.is_fp8e4b15x4() and not rhs_dtype.is_fp8e4b15x4(
1204
+ ), "Dot op does not support fp8e4b15x4 on CUDA arch >= 90"
1205
+ if lhs_dtype.is_int() or rhs_dtype.is_int():
1206
+ assert lhs_dtype == rhs_dtype, f"Both operands must be same type. First operand ({lhs_dtype}) and second operand ({rhs_dtype})"
1207
+ assert lhs_dtype.is_int8() or lhs_dtype.is_uint8(
1208
+ ), f"Both operands must be either int8 or uint8. Operand type ({lhs_dtype})"
1209
+ elif lhs_dtype.is_fp8() or rhs_dtype.is_fp8():
1210
+ assert lhs_dtype.is_fp8e4nv() or lhs_dtype.is_fp8e5(
1211
+ ), f"Only supports fp8e4nv or fp8e5. First operand ({lhs_dtype})"
1212
+ assert rhs_dtype.is_fp8e4nv() or rhs_dtype.is_fp8e5(
1213
+ ), f"Only supports fp8e4nv or fp8e5. Second operand ({rhs_dtype})"
1214
+ else:
1215
+ assert lhs_dtype.is_fp16() or lhs_dtype.is_bf16() or lhs_dtype.is_fp32() or lhs_dtype.is_int1(
1216
+ ), f"Unsupported dtype {lhs_dtype}"
1217
+ assert rhs_dtype.is_fp16() or rhs_dtype.is_bf16() or rhs_dtype.is_fp32() or rhs_dtype.is_int1(
1218
+ ), f"Unsupported dtype {rhs_dtype}"
1219
+ assert lhs_dtype == rhs_dtype, f"First input ({lhs_dtype}) and second input ({rhs_dtype}) must have the same dtype!"
1220
+
1221
+ assert lhs.type.is_block() and rhs.type.is_block()
1222
+
1223
+ assert_dtypes_valid(lhs.dtype, rhs.dtype, builder.target)
1224
+
1225
+ assert len(lhs.shape) == 2, f"First input shape ({lhs.shape}) is not two dimensional!"
1226
+ assert len(rhs.shape) == 2, f"Second input shape ({rhs.shape}) is not two dimensional!"
1227
+ assert lhs.shape[1].value == rhs.shape[
1228
+ 0].value, f"First input shape ({lhs.shape}) and second input shape {rhs.shape} are not compatible for matmul (second index of first shape ({lhs.shape[1].value}) must be equal to first index of second shape ({rhs.shape[0].value})"
1229
+ assert lhs.shape[0].value >= 16 and lhs.shape[1].value >= 16 \
1230
+ and rhs.shape[1].value >= 16, \
1231
+ f"All values in both first input shape ({lhs.shape}) and second input shape ({rhs.shape}) must be >= 16!"
1232
+ if lhs.type.scalar.is_int():
1233
+ assert lhs.type.scalar == tl.int8, "only int8 supported!"
1234
+ # TODO: This is CUDA specific, check if ROCm has the same limitation
1235
+ assert lhs.shape[1].value >= 32, "small blocks not supported!"
1236
+ _0 = builder.get_int32(0)
1237
+ ret_scalar_ty = tl.int32
1238
+ elif out_dtype.is_bf16():
1239
+ raise ValueError(
1240
+ "out_dtype=bfloat16 is unsupported. Please use out_dtype=float32/float16 and cast with `.to(tl.bfloat16)`")
1241
+ elif lhs.type.scalar.is_fp32() or lhs.type.scalar.is_bf16():
1242
+ _0 = builder.get_fp32(0)
1243
+ ret_scalar_ty = tl.float32
1244
+ else:
1245
+ _0 = builder.get_fp16(0) if out_dtype.is_fp16() else builder.get_fp32(0)
1246
+ ret_scalar_ty = out_dtype
1247
+
1248
+ M = lhs.type.shape[0]
1249
+ N = rhs.type.shape[1]
1250
+
1251
+ # Cast operands of types f16 and i8 for configurations where FMA only supported.
1252
+ if is_hip() and not mfma_supported(M, N, lhs.type.shape[1], allow_tf32, ret_scalar_ty):
1253
+ ret_cast_scalar_ty = tl.float32 if lhs.type.scalar.is_int() else ret_scalar_ty
1254
+ lhs = cast(lhs, ret_cast_scalar_ty, builder)
1255
+ rhs = cast(rhs, ret_cast_scalar_ty, builder)
1256
+ if ret_cast_scalar_ty == tl.float16:
1257
+ _0 = builder.create_splat(builder.get_fp16(0), [M, N])
1258
+ else:
1259
+ _0 = builder.create_splat(builder.get_fp32(0), [M, N])
1260
+ ret_ty = tl.block_type(ret_cast_scalar_ty, [M, N])
1261
+ ret = tl.tensor(builder.create_dot(lhs.handle, rhs.handle, _0, allow_tf32), ret_ty)
1262
+ return cast(ret, ret_scalar_ty, builder)
1263
+ if is_hip() and mfma_supported(M, N, lhs.type.shape[1], allow_tf32,
1264
+ ret_scalar_ty) and ret_scalar_ty.primitive_bitwidth < 32:
1265
+ if lhs.type.scalar.is_int():
1266
+ ret_dot_scalar_ty = tl.int32
1267
+ _0 = builder.create_splat(builder.get_int32(0), [M, N])
1268
+ else:
1269
+ ret_dot_scalar_ty = tl.float32
1270
+ _0 = builder.create_splat(builder.get_fp32(0), [M, N])
1271
+ ret_ty = tl.block_type(ret_dot_scalar_ty, [M, N])
1272
+ ret = tl.tensor(builder.create_dot(lhs.handle, rhs.handle, _0, allow_tf32), ret_ty)
1273
+ return cast(ret, ret_scalar_ty, builder)
1274
+ ret_ty = tl.block_type(ret_scalar_ty, [M, N])
1275
+ if acc is None:
1276
+ acc_handle = builder.create_splat(_0, [M, N])
1277
+ else:
1278
+ acc_handle = acc.handle
1279
+ assert acc.type == ret_ty
1280
+
1281
+ # max_num_imprecise_acc only applies to fp8 -> fp32 dot on sm_90
1282
+ if not (_is_cuda(builder.target) and builder.target.capability == 90 and lhs.dtype.is_fp8() and rhs.dtype.is_fp8()
1283
+ and ret_scalar_ty.is_fp32()):
1284
+ max_num_imprecise_acc = 0
1285
+ if max_num_imprecise_acc is None:
1286
+ max_num_imprecise_acc = 2**30
1287
+
1288
+ return tl.tensor(builder.create_dot(lhs.handle, rhs.handle, acc_handle, allow_tf32, max_num_imprecise_acc), ret_ty)
1289
+
1290
+
1291
+ # ===----------------------------------------------------------------------===//
1292
+ # Indexing
1293
+ # ===----------------------------------------------------------------------===//
1294
+
1295
+
1296
+ def where(condition: tl.tensor, x: tl.tensor, y: tl.tensor, builder: ir.builder) -> tl.tensor:
1297
+ condition = cast(condition, tl.int1, builder)
1298
+ if condition.type.is_block():
1299
+ condition, x = broadcast_impl_value(condition, x, builder)
1300
+ x, y = broadcast_impl_value(x, y, builder)
1301
+ condition, x = broadcast_impl_value(condition, x, builder)
1302
+
1303
+ x, y = binary_op_type_checking_impl(x, y, builder, True, True)
1304
+ if not condition.type.is_block():
1305
+ condition, _ = broadcast_impl_value(condition, x, builder)
1306
+ ret_ty = x.type
1307
+ return tl.tensor(builder.create_select(condition.handle, x.handle, y.handle), ret_ty)
1308
+
1309
+
1310
+ # ===----------------------------------------------------------------------===//
1311
+ # Reduction
1312
+ # ===----------------------------------------------------------------------===
1313
+
1314
+
1315
+ def reduction(inputs: Sequence[tl.tensor], axis: int, region_builder_fn, builder: ir.builder) -> Tuple[tl.tensor, ...]:
1316
+ if axis is None:
1317
+ new_inputs = []
1318
+ for i in range(len(inputs)):
1319
+ new_shape = [inputs[i].numel.value]
1320
+ new_inputs.append(view(inputs[i], new_shape, builder))
1321
+ inputs = tuple(new_inputs)
1322
+ axis = 0
1323
+ # get result shape
1324
+ shape = inputs[0].type.shape
1325
+ ret_shape = [s for i, s in enumerate(shape) if i != axis]
1326
+ for t in inputs:
1327
+ assert t.type.shape == shape
1328
+
1329
+ def wrap_tensor(x, scalar_ty):
1330
+ if ret_shape:
1331
+ res_ty = tl.block_type(scalar_ty, ret_shape)
1332
+ else:
1333
+ # 0d-tensor -> scalar
1334
+ res_ty = scalar_ty
1335
+ return tl.tensor(x, res_ty)
1336
+
1337
+ reduce_op = builder.create_reduce([t.handle for t in inputs], axis)
1338
+ region_builder_fn(reduce_op)
1339
+ reduce_op.verify()
1340
+
1341
+ return tuple(wrap_tensor(reduce_op.get_result(i), inputs[i].type.scalar) for i in range(len(inputs)))
1342
+
1343
+
1344
+ # ===----------------------------------------------------------------------===
1345
+ # Associative Scan
1346
+ # ===----------------------------------------------------------------------===
1347
+
1348
+
1349
+ def associative_scan(inputs: Sequence[tl.tensor], axis: int, region_builder_fn,
1350
+ builder: ir.builder) -> Tuple[tl.tensor, ...]:
1351
+ if len(inputs) != 1:
1352
+ raise ValueError("Current implementation only support single tensor input")
1353
+ shape = inputs[0].type.shape
1354
+
1355
+ def wrap_tensor(x, scalar_ty):
1356
+ res_ty = tl.block_type(scalar_ty, shape)
1357
+ return tl.tensor(x, res_ty)
1358
+
1359
+ scan_op = builder.create_scan([t.handle for t in inputs], axis)
1360
+ region_builder_fn(scan_op)
1361
+ scan_op.verify()
1362
+
1363
+ return tuple(wrap_tensor(scan_op.get_result(i), inputs[i].type.scalar) for i in range(len(inputs)))
1364
+
1365
+
1366
+ # ===----------------------------------------------------------------------===
1367
+ # Math
1368
+ # ===----------------------------------------------------------------------===
1369
+
1370
+
1371
+ def _check_dtype(dtypes: List[str]) -> T:
1372
+ """
1373
+ We're following libdevice's convention to check accepted data types for math functions.
1374
+ It is not a good practice to support all data types as accelerators/GPUs don't support
1375
+ many float16 and bfloat16 math operations.
1376
+ We should let the users know that they are using and invoke explicit cast to convert
1377
+ the data type to the supported one.
1378
+ """
1379
+
1380
+ def wrapper(fn):
1381
+
1382
+ @wraps(fn)
1383
+ def check(*args, **kwargs):
1384
+ # concatenate args and kwargs
1385
+ all_args = list(args) + list(kwargs.values())
1386
+ for arg in [a for a in all_args if isinstance(a, tl.tensor)]:
1387
+ if arg.type.scalar.name not in dtypes:
1388
+ raise ValueError(f"Expected dtype {dtypes} but got {arg.type.scalar.name}")
1389
+ return fn(*args, **kwargs)
1390
+
1391
+ return check
1392
+
1393
+ return wrapper
1394
+
1395
+
1396
+ def umulhi(x: tl.tensor, y: tl.tensor, builder: ir.builder) -> tl.tensor:
1397
+ x, y = binary_op_type_checking_impl(x, y, builder)
1398
+ # FIXME(Keren): not portable, should be fixed
1399
+ from . import math
1400
+ return math.mulhi(x, y, _builder=builder)
1401
+
1402
+
1403
+ @_check_dtype(dtypes=["fp32", "fp64"])
1404
+ def floor(x: tl.tensor, builder: ir.builder) -> tl.tensor:
1405
+ # FIXME(Keren): not portable, should be fixed
1406
+ from . import math
1407
+ return math.floor(x, _builder=builder)
1408
+
1409
+
1410
+ @_check_dtype(dtypes=["fp32", "fp64"])
1411
+ def exp(x: tl.tensor, builder: ir.builder) -> tl.tensor:
1412
+ return tl.tensor(builder.create_exp(x.handle), x.type)
1413
+
1414
+
1415
+ @_check_dtype(dtypes=["fp32", "fp64"])
1416
+ def log(x: tl.tensor, builder: ir.builder) -> tl.tensor:
1417
+ return tl.tensor(builder.create_log(x.handle), x.type)
1418
+
1419
+
1420
+ @_check_dtype(dtypes=["fp32", "fp64"])
1421
+ def cos(x: tl.tensor, builder: ir.builder) -> tl.tensor:
1422
+ return tl.tensor(builder.create_cos(x.handle), x.type)
1423
+
1424
+
1425
+ @_check_dtype(dtypes=["fp32", "fp64"])
1426
+ def sin(x: tl.tensor, builder: ir.builder) -> tl.tensor:
1427
+ return tl.tensor(builder.create_sin(x.handle), x.type)
1428
+
1429
+
1430
+ @_check_dtype(dtypes=["fp32", "fp64"])
1431
+ def sqrt(x: tl.tensor, builder: ir.builder) -> tl.tensor:
1432
+ return tl.tensor(builder.create_sqrt(x.handle), x.type)
1433
+
1434
+
1435
+ def abs(x: tl.tensor, builder: ir.builder) -> tl.tensor:
1436
+ dtype = x.dtype
1437
+ if dtype.is_floating():
1438
+ return tl.tensor(builder.create_fabs(x.handle), x.type)
1439
+ elif dtype.is_int_signed():
1440
+ return tl.tensor(builder.create_iabs(x.handle), x.type)
1441
+ elif dtype.is_int_unsigned():
1442
+ return x # no-op
1443
+ else:
1444
+ assert False, f"Unexpected dtype {dtype}"
1445
+
1446
+
1447
+ ##
1448
+
1449
+
1450
+ def multiple_of(x: tl.tensor, values: List[int]) -> tl.tensor:
1451
+ if max(1, len(x.shape)) != len(values):
1452
+ raise ValueError("Shape of input to multiple_of does not match the length of values")
1453
+ x.handle.set_attr("tt.divisibility", ir.make_attr(values, x.handle.get_context()))
1454
+ return x
1455
+
1456
+
1457
+ def max_contiguous(x: tl.tensor, values: List[int]) -> tl.tensor:
1458
+ if len(x.shape) != len(values):
1459
+ raise ValueError("Shape of input to max_contiguous does not match the length of values")
1460
+ x.handle.set_attr("tt.contiguity", ir.make_attr(values, x.handle.get_context()))
1461
+ return x
1462
+
1463
+
1464
+ def max_constancy(x: tl.tensor, values: List[int]) -> tl.tensor:
1465
+ if len(x.shape) != len(values):
1466
+ raise ValueError("Shape of input to max_constancy does not match the length of values")
1467
+ x.handle.set_attr("tt.constancy", ir.make_attr(values, x.handle.get_context()))
1468
+ return x
1469
+
1470
+
1471
+ def debug_barrier(builder: ir.builder) -> tl.tensor:
1472
+ return tl.tensor(builder.create_barrier(), tl.void)
1473
+
1474
+
1475
+ def device_print(prefix: str, args: List[tl.tensor], builder: ir.builder) -> tl.tensor:
1476
+ # It makes sense visually for prefix to end in ": "; make it so. Also,
1477
+ # non-empty prefixes should start with " ".
1478
+ if not prefix.endswith(" ") and args:
1479
+ prefix += " "
1480
+ if not prefix.endswith(": ") and args:
1481
+ prefix = prefix[:-1] + ": "
1482
+ if len(prefix) > 2 and not prefix.startswith(" "):
1483
+ prefix = " " + prefix
1484
+
1485
+ new_args = []
1486
+ for arg in args:
1487
+ new_args.append(arg.handle)
1488
+ return tl.tensor(builder.create_print(prefix, new_args), tl.void)
1489
+
1490
+
1491
+ def device_assert(cond: tl.tensor, msg: str, file_name: str, func_name, lineno: int, builder: ir.builder) -> tl.tensor:
1492
+ cond_ty = cond.type
1493
+ if not cond_ty.is_block():
1494
+ cond_ty = tl.block_type(cond_ty.scalar, (1, ))
1495
+ cond = tl.tensor(builder.create_splat(cond.handle, (1, )), cond_ty)
1496
+ return tl.tensor(builder.create_assert(cond.handle, msg, file_name, func_name, lineno), tl.void)
1497
+
1498
+
1499
+ def _convert_elem_to_ir_value(builder, elem, require_i64):
1500
+ if isinstance(elem, int):
1501
+ elem = tl.constexpr(elem)
1502
+ if isinstance(elem, tl.constexpr):
1503
+ return builder.get_int64(elem.value) if require_i64 else builder.get_int32(elem.value)
1504
+ elif isinstance(elem, tl.tensor):
1505
+ assert elem.numel.value == 1, "Expected a scalar in shape/strides/offsets"
1506
+ assert elem.dtype.is_int(), "Expected an integer scalar type in shape/strides/offsets"
1507
+ if elem.dtype != tl.int64 and require_i64:
1508
+ return builder.create_int_cast(elem.handle, builder.get_int64_ty(), elem.dtype.is_int_signed())
1509
+ elif elem.dtype != tl.int32:
1510
+ return builder.create_int_cast(elem.handle, builder.get_int32_ty(), elem.dtype.is_int_signed())
1511
+ return elem.handle
1512
+ assert False, f"Unsupported element type in shape/strides/offsets: {type(elem)}"
1513
+
1514
+
1515
+ def _convert_to_ir_values(builder, list_like, require_i64=True):
1516
+ if hasattr(list_like, "__iter__"):
1517
+ return [_convert_elem_to_ir_value(builder, elem, require_i64) for elem in list_like]
1518
+ return [_convert_elem_to_ir_value(builder, list_like, require_i64)]
1519
+
1520
+
1521
+ def make_block_ptr(base: tl.tensor, shape, strides, offsets, block_shape, order, builder: ir.builder) -> tl.tensor:
1522
+ # Convert dynamic arguments to IR values
1523
+ # NOTES(Chenggang): current `shape/strides` are `int64_t`, while `offsets/block_shape` are `int32_t`
1524
+ shape = _convert_to_ir_values(builder, shape)
1525
+ strides = _convert_to_ir_values(builder, strides)
1526
+ offsets = _convert_to_ir_values(builder, offsets, require_i64=False)
1527
+
1528
+ # Check `base` type
1529
+ if not base.type.is_ptr() or base.type.element_ty.is_block():
1530
+ raise ValueError("Expected `base` to be a pointer type (but not a block pointer type or others)")
1531
+
1532
+ # Treat `pointer_type<tl.int1>` as `pointer_type<tl.int8>`
1533
+ if base.type.element_ty == tl.int1:
1534
+ base = cast(base, tl.pointer_type(tl.int8, base.type.address_space), builder)
1535
+
1536
+ # Check whether `block_shape` is static
1537
+ if not hasattr(block_shape, "__iter__"):
1538
+ block_shape = [block_shape]
1539
+ block_shape = [elem.value if isinstance(elem, tl.constexpr) else elem for elem in block_shape]
1540
+ assert all([isinstance(elem, int) and -2**31 <= elem < 2**31 for elem in block_shape]), \
1541
+ "Expected a list of constant integers (`int32_t` range) in `block_shape`"
1542
+
1543
+ # Check `order`
1544
+ if not hasattr(order, "__iter__"):
1545
+ order = [order]
1546
+ order = [elem.value if isinstance(elem, tl.constexpr) else elem for elem in order]
1547
+ assert sorted(order) == list(range(len(order))), "Expected a permutation of (0, 1, ..., len(order)-1) in order"
1548
+
1549
+ # Must have same length
1550
+ assert all([len(block_shape) == len(list_like) for list_like in [shape, strides, offsets, order]]), \
1551
+ "Expected shape/strides/offsets/block_shape to have the same length"
1552
+
1553
+ # Build value, the type is:
1554
+ # `pointer_type<blocked<shape, element_type>>` in Python
1555
+ # `tt.ptr<tensor<shape, element_type>>` in MLIR
1556
+ handle = builder.create_make_block_ptr(base.handle, shape, strides, offsets, block_shape, order)
1557
+ return tl.tensor(handle, tl.pointer_type(tl.block_type(base.type.element_ty, block_shape)))
1558
+
1559
+
1560
+ def advance(base: tl.tensor, offsets, builder: ir.builder) -> tl.tensor:
1561
+ # Convert dynamic offsets to IR values
1562
+ offsets = _convert_to_ir_values(builder, offsets, require_i64=False)
1563
+
1564
+ # Advanced block pointer type is the same as before
1565
+ return tl.tensor(builder.create_advance(base.handle, offsets), base.type)
evalkit_tf437/lib/python3.10/site-packages/triton/tools/__init__.py ADDED
File without changes
evalkit_tf437/lib/python3.10/site-packages/triton/tools/__pycache__/build_extern.cpython-310.pyc ADDED
Binary file (13.7 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/triton/tools/__pycache__/disasm.cpython-310.pyc ADDED
Binary file (2.82 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/triton/tools/build_extern.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import subprocess
3
+ from abc import ABC, abstractmethod
4
+ from typing import Dict, List, Optional
5
+
6
+
7
+ class Symbol:
8
+ _name: str
9
+ _op_name: str
10
+ _ret_type: str
11
+ _arg_names: List[str]
12
+ _arg_types: List[str]
13
+
14
+ def __init__(
15
+ self,
16
+ name: str,
17
+ op_name: str,
18
+ ret_type: str,
19
+ arg_names: List[str],
20
+ arg_types: List[str],
21
+ ) -> None:
22
+ '''
23
+ A symbol is a function declaration.
24
+ :param name: name of the symbol
25
+ :param op_name: name of the operation
26
+ :param ret_type: return type of the operation
27
+ :param arg_names: names of the arguments
28
+ :param arg_types: types of the arguments
29
+ '''
30
+ self._name = name
31
+ self._op_name = op_name
32
+ self._ret_type = ret_type
33
+ self._arg_names = list(arg_names)
34
+ self._arg_types = list(arg_types)
35
+
36
+ @property
37
+ def name(self) -> str:
38
+ return self._name
39
+
40
+ @property
41
+ def op_name(self) -> str:
42
+ return self._op_name
43
+
44
+ @property
45
+ def ret_type(self) -> str:
46
+ return self._ret_type
47
+
48
+ @property
49
+ def arg_names(self) -> List[str]:
50
+ return self._arg_names
51
+
52
+ @property
53
+ def arg_types(self) -> List[str]:
54
+ return self._arg_types
55
+
56
+
57
+ def convert_type(type_str) -> Optional[str]:
58
+ if type_str == "i32":
59
+ return "int32"
60
+ elif type_str == "u32":
61
+ return "uint32"
62
+ elif type_str == "i64":
63
+ return "int64"
64
+ elif type_str == "u64":
65
+ return "uint64"
66
+ elif type_str == "float":
67
+ return "fp32"
68
+ elif type_str == "double":
69
+ return "fp64"
70
+ else:
71
+ # ignore other types, such as pointer types
72
+ return None
73
+
74
+
75
+ def to_unsigned(type_str) -> str:
76
+ if type_str == "int32":
77
+ return "uint32"
78
+ elif type_str == "int64":
79
+ return "uint64"
80
+ else:
81
+ return type_str
82
+
83
+
84
+ class ExternLibrary(ABC):
85
+ _name: str
86
+ _path: str
87
+ _symbols: Dict[str, Symbol]
88
+ _format: bool
89
+ _grouping: bool
90
+
91
+ def __init__(
92
+ self,
93
+ name: str,
94
+ path: str,
95
+ format: bool = True,
96
+ grouping: bool = True,
97
+ ) -> None:
98
+ '''
99
+ Abstract class for extern library.
100
+ :param name: name of the library
101
+ :param path: path of the library
102
+ :param format: whether to format the generated stub file
103
+ '''
104
+ self._name = name
105
+ self._path = path
106
+ self._symbols = {}
107
+ self._format = format
108
+ self._grouping = grouping
109
+
110
+ @property
111
+ def name(self) -> str:
112
+ return self._name
113
+
114
+ @property
115
+ def path(self) -> str:
116
+ return self._path
117
+
118
+ @property
119
+ def symbols(self) -> Dict[str, Symbol]:
120
+ return self._symbols
121
+
122
+ @property
123
+ def grouping(self) -> bool:
124
+ return self._grouping
125
+
126
+ @abstractmethod
127
+ def parse_symbols(self, input_file) -> None:
128
+ pass
129
+
130
+ @abstractmethod
131
+ def _output_stubs(self) -> str:
132
+ pass
133
+
134
+ def generate_stub_file(self, output_dir) -> None:
135
+ file_str = self._output_stubs()
136
+ if file_str is None or len(file_str) == 0:
137
+ raise Exception("file_str is empty")
138
+
139
+ output_file = f"{output_dir}/{self._name}.py"
140
+ with open(output_file, "w") as f:
141
+ f.write(file_str)
142
+ f.close()
143
+ if self._format:
144
+ subprocess.Popen(["autopep8", "-a", "-r", "-i", output_file], stdout=subprocess.PIPE).communicate()
145
+ subprocess.Popen(["isort", output_file], stdout=subprocess.PIPE).communicate()
146
+
147
+
148
+ class Libdevice(ExternLibrary):
149
+ _symbol_groups: Dict[str, List[Symbol]]
150
+
151
+ def __init__(self, path) -> None:
152
+ '''
153
+ Constructor for Libdevice.
154
+ :param path: path of the libdevice library
155
+ '''
156
+ super().__init__("libdevice", path)
157
+ self._symbol_groups = {}
158
+ self.is_pure = True
159
+
160
+ @staticmethod
161
+ def _extract_symbol(line) -> Optional[Symbol]:
162
+ # Extract symbols from line in the following format:
163
+ # "define [internal] <ret_type> @<name>(<arg_types>,)"
164
+ entries = line.split("@")
165
+ ret_str = entries[0]
166
+ func_str = entries[1]
167
+ # Get ret_type, skip internal symbols
168
+ ret_strs = ret_str.split()
169
+ if ret_strs[1] == "internal":
170
+ return None
171
+ ret_type = convert_type(ret_strs[1])
172
+ if ret_type is None:
173
+ return None
174
+ # Get function name
175
+ func_strs = func_str.split("(")
176
+ func_name = func_strs[0].replace("@", "")
177
+ op_name = func_name.replace("__nv_", "")
178
+ if 'ieee' in op_name:
179
+ return None
180
+ # Get arg_types
181
+ arg_strs = func_strs[1].split(",")
182
+ arg_types = []
183
+ arg_names = []
184
+ for i, arg_str in enumerate(arg_strs):
185
+ arg_type = convert_type(arg_str.split()[0])
186
+ if arg_type is None:
187
+ return None
188
+ arg_name = 'arg' + str(i)
189
+ arg_types.append(arg_type)
190
+ arg_names.append(arg_name)
191
+ if op_name == "sad":
192
+ # Special case for sad, where the last argument is an unsigned int
193
+ arg_types[-1] = to_unsigned(arg_types[-1])
194
+ elif op_name.startswith("u"):
195
+ # LLVM does not differentiate between signed and unsigned integer type.
196
+ # We have to convert the types to unsigned
197
+ ret_type = to_unsigned(ret_type)
198
+ for i, arg_type in enumerate(arg_types):
199
+ arg_types[i] = to_unsigned(arg_type)
200
+ return Symbol(func_name, op_name, ret_type, arg_names, arg_types)
201
+
202
+ def _group_symbols(self) -> None:
203
+ symbol_set = {}
204
+ for symbol in self._symbols.values():
205
+ op_name = symbol.op_name
206
+ symbol_set[op_name] = symbol
207
+
208
+ # Group functions together by renaming.
209
+ renaming = {
210
+ 'llabs': 'abs', 'acosf': 'acos', 'acoshf': 'acosh', 'dadd_rd': 'add_rd', 'fadd_rd': 'add_rd', 'dadd_rn':
211
+ 'add_rn', 'fadd_rn': 'add_rn', 'dadd_ru': 'add_ru', 'fadd_ru': 'add_ru', 'dadd_rz': 'add_rz', 'fadd_rz':
212
+ 'add_rz', 'asinf': 'asin', 'asinhf': 'asinh', 'atanf': 'atan', 'atan2f': 'atan2', 'atanhf': 'atanh',
213
+ 'brevll': 'brev', 'cbrtf': 'cbrt', 'ceilf': 'ceil', 'clzll': 'clz', 'copysignf': 'copysign', 'cosf': 'cos',
214
+ 'coshf': 'cosh', 'cospif': 'cospi', 'cyl_bessel_i0f': 'cyl_bessel_i0', 'cyl_bessel_i1f': 'cyl_bessel_i1',
215
+ 'fdiv_rd': 'div_rd', 'ddiv_rd': 'div_rd', 'fdiv_rn': 'div_rn', 'ddiv_rn': 'div_rn', 'fdiv_ru': 'div_ru',
216
+ 'ddiv_ru': 'div_ru', 'fdiv_rz': 'div_rz', 'ddiv_rz': 'div_rz', 'erff': 'erf', 'erfcf': 'erfc', 'erfcinvf':
217
+ 'erfcinv', 'erfcxf': 'erfcx', 'erfinvf': 'erfinv', 'expf': 'exp', 'exp10f': 'exp10', 'exp2f': 'exp2',
218
+ 'expm1f': 'expm1', 'fabsf': 'abs', 'fabs': 'abs', 'fast_fdividef': 'fast_dividef', 'fdimf': 'fdim', 'ffsll':
219
+ 'ffs', 'floorf': 'floor', 'fmaf': 'fma', 'fmaf_rd': 'fma_rd', 'fmaf_rn': 'fma_rn', 'fmaf_ru': 'fma_ru',
220
+ 'fmaf_rz': 'fma_rz', 'fmodf': 'fmod', 'uhadd': 'hadd', 'hypotf': 'hypot', 'ilogbf': 'ilogb', 'isinff':
221
+ 'isinf', 'isinfd': 'isinf', 'isnanf': 'isnan', 'isnand': 'isnan', 'j0f': 'j0', 'j1f': 'j1', 'jnf': 'jn',
222
+ 'ldexpf': 'ldexp', 'lgammaf': 'lgamma', 'llrintf': 'llrint', 'llroundf': 'llround', 'logf': 'log', 'log10f':
223
+ 'log10', 'log1pf': 'log1p', 'log2f': 'log2', 'logbf': 'logb', 'umax': 'max', 'llmax': 'max', 'ullmax':
224
+ 'max', 'fmaxf': 'max', 'fmax': 'max', 'umin': 'min', 'llmin': 'min', 'ullmin': 'min', 'fminf': 'min',
225
+ 'fmin': 'min', 'dmul_rd': 'mul_rd', 'fmul_rd': 'mul_rd', 'dmul_rn': 'mul_rn', 'fmul_rn': 'mul_rn',
226
+ 'dmul_ru': 'mul_ru', 'fmul_ru': 'mul_ru', 'dmul_rz': 'mul_rz', 'fmul_rz': 'mul_rz', 'umul24': 'mul24',
227
+ 'umulhi': 'mulhi', 'mul64hi': 'mulhi', 'umul64hi': 'mulhi', 'nearbyintf': 'nearbyint', 'nextafterf':
228
+ 'nextafter', 'norm3df': 'norm3d', 'norm4df': 'norm4d', 'normcdff': 'normcdf', 'normcdfinvf': 'normcdfinv',
229
+ 'popcll': 'popc', 'powif': 'pow', 'powi': 'pow', 'powf': 'pow', 'rcbrtf': 'rcbrt', 'frcp_rd': 'rcp_rd',
230
+ 'drcp_rd': 'rcp_rd', 'frcp_rn': 'rcp_rn', 'drcp_rn': 'rcp_rn', 'frcp_ru': 'rcp_ru', 'drcp_ru': 'rcp_ru',
231
+ 'frcp_rz': 'rcp_rz', 'drcp_rz': 'rcp_rz', 'remainderf': 'remainder', 'urhadd': 'rhadd', 'rhypotf': 'rhypot',
232
+ 'rintf': 'rint', 'rnorm3df': 'rnorm3d', 'rnorm4df': 'rnorm4d', 'roundf': 'round', 'rsqrtf': 'rsqrt',
233
+ 'frsqrt_rn': 'rsqrt_rn', 'usad': 'sad', 'scalbnf': 'scalbn', 'signbitf': 'signbit', 'signbitd': 'signbit',
234
+ 'sinf': 'sin', 'sinhf': 'sinh', 'sinpif': 'sinpi', 'sqrtf': 'sqrt', 'fsqrt_rd': 'sqrt_rd', 'dsqrt_rd':
235
+ 'sqrt_rd', 'fsqrt_rn': 'sqrt_rn', 'dsqrt_rn': 'sqrt_rn', 'fsqrt_ru': 'sqrt_ru', 'dsqrt_ru': 'sqrt_ru',
236
+ 'fsqrt_rz': 'sqrt_rz', 'dsqrt_rz': 'sqrt_rz', 'fsub_rd': 'sub_rd', 'dsub_rd': 'sub_rd', 'fsub_rn': 'sub_rn',
237
+ 'dsub_rn': 'sub_rn', 'fsub_ru': 'sub_ru', 'dsub_ru': 'sub_ru', 'fsub_rz': 'sub_rz', 'dsub_rz': 'sub_rz',
238
+ 'tanf': 'tan', 'tanhf': 'tanh', 'tgammaf': 'tgamma', 'truncf': 'trunc', 'y0f': 'y0', 'y1f': 'y1', 'ynf':
239
+ 'yn'
240
+ }
241
+
242
+ for symbol in self._symbols.values():
243
+ op_name = symbol.op_name
244
+ if op_name in renaming:
245
+ op_name = renaming[op_name]
246
+ symbol._op_name = op_name
247
+ if op_name in self._symbol_groups:
248
+ self._symbol_groups[op_name].append(symbol)
249
+ else:
250
+ self._symbol_groups[op_name] = [symbol]
251
+
252
+ def parse_symbols(self, input_file) -> None:
253
+ if len(self.symbols) > 0:
254
+ return
255
+ output = subprocess.check_output(["grep", "define", input_file]).decode().splitlines()
256
+ for line in output:
257
+ symbol = self._extract_symbol(line)
258
+ if symbol is None:
259
+ continue
260
+ self._symbols[symbol.name] = symbol
261
+
262
+ self._group_symbols()
263
+
264
+ def _output_stubs(self) -> str:
265
+ # Generate python functions in the following format:
266
+ # @extern.extern
267
+ # def <op_name>(<args>, _builder=None):
268
+ # arg_type_symbol_dict = {[arg_type]: {(symbol, ret_type)}}
269
+ # return core.extern_elementwise("libdevice", <path>, <args>, <arg_type_symbol_dict>, _builder)
270
+ import_str = "from . import core\n"
271
+ import_str += "import os\n"
272
+ import_str += "import functools\n"
273
+
274
+ header_str = ""
275
+ header_str += "@functools.lru_cache()\n"
276
+ header_str += "def libdevice_path():\n"
277
+ header_str += " import torch\n"
278
+ header_str += " third_party_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\", \"third_party\")\n"
279
+ header_str += " if torch.version.hip is None:\n"
280
+ header_str += " default = os.path.join(third_party_dir, \"cuda\", \"lib\", \"libdevice.10.bc\")\n"
281
+ header_str += " else:\n"
282
+ header_str += " default = ''\n"
283
+ header_str += " return os.getenv(\"TRITON_LIBDEVICE_PATH\", default)\n"
284
+ func_str = ""
285
+ for symbols in self._symbol_groups.values():
286
+ func_str += "@core.extern\n"
287
+ func_name_str = f"def {symbols[0].op_name}("
288
+ for arg_name in symbols[0].arg_names:
289
+ func_name_str += f"{arg_name}, "
290
+ func_name_str += "_builder=None):\n"
291
+
292
+ return_str = f"\treturn core.extern_elementwise(\"{self._name}\", libdevice_path(), ["
293
+ for arg_name in symbols[0].arg_names:
294
+ return_str += f"{arg_name}, "
295
+ return_str += "], \n"
296
+
297
+ arg_type_symbol_dict_str = "{"
298
+ for symbol in symbols:
299
+ arg_type_symbol_dict_str += "("
300
+ for arg_type in symbol.arg_types:
301
+ arg_type_symbol_dict_str += f'core.dtype("{arg_type}"),'
302
+ ret_type = f'core.dtype("{symbol.ret_type}")'
303
+ arg_type_symbol_dict_str += "): (\"" + symbol.name + "\", " + ret_type + "),\n"
304
+ arg_type_symbol_dict_str += "}"
305
+
306
+ return_str += arg_type_symbol_dict_str
307
+ return_str += f", is_pure={self.is_pure}"
308
+ return_str += ", _builder=_builder)\n"
309
+
310
+ func_str += func_name_str + return_str + "\n"
311
+ file_str = import_str + header_str + func_str
312
+
313
+ return file_str
314
+
315
+
316
+ class LLVMDisassembler:
317
+ _path: str
318
+ _ll_file: str
319
+
320
+ def __init__(self, path) -> None:
321
+ '''
322
+ Invoke llvm-dis to disassemble the given file.
323
+ :param path: path to llvm-dis
324
+ '''
325
+ self._path = path
326
+ self._ll_file = "/tmp/extern_lib.ll"
327
+
328
+ def disasm(self, lib_path: str) -> None:
329
+ subprocess.Popen([self._path, lib_path, "-o", self.ll_file], stdout=subprocess.PIPE).communicate()
330
+
331
+ @property
332
+ def ll_file(self) -> str:
333
+ return self._ll_file
334
+
335
+ @property
336
+ def path(self) -> str:
337
+ return self._path
338
+
339
+
340
+ extern_libs = ["libdevice"]
341
+
342
+
343
+ def build(
344
+ llvm_dis_path: str,
345
+ lib_path: str,
346
+ lib_name: str,
347
+ output_dir: str,
348
+ ) -> None:
349
+ '''
350
+ Interface function to build the library file.
351
+ :param llvm_dis_path: path to the llvm-dis binary
352
+ :param lib_path: path to the external library file
353
+ :param lib_name: name of the library
354
+ :param output_dir: path to the output directory
355
+ '''
356
+ if lib_name == "libdevice":
357
+ extern_lib = Libdevice(lib_path)
358
+ else:
359
+ raise Exception(f"Unknown extern library: {lib_name}")
360
+
361
+ llvm_disassembler = LLVMDisassembler(llvm_dis_path)
362
+ llvm_disassembler.disasm(lib_path)
363
+
364
+ extern_lib.parse_symbols(llvm_disassembler.ll_file)
365
+ extern_lib.generate_stub_file(output_dir)
366
+
367
+
368
+ if __name__ == "__main__":
369
+ parser = argparse.ArgumentParser()
370
+ parser.add_argument("--llvm-dis", dest="llvm_dis_path", help="Path to llvm-dis", default="llvm-dis")
371
+ parser.add_argument("--lib-path", dest="lib_path", help="Path to the extern library")
372
+ parser.add_argument("--lib-name", dest="lib_name", help="Name of the extern library")
373
+ parser.add_argument("--output", dest="output_dir", help="Output file path", default="/tmp/")
374
+ args = parser.parse_args()
375
+
376
+ build(args.llvm_dis_path, args.lib_path, args.lib_name, args.output_dir)
evalkit_tf437/lib/python3.10/site-packages/triton/tools/compile.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef TT_KERNEL_INCLUDES
2
+ #define TT_KERNEL_INCLUDES
3
+
4
+ #include <cuda.h>
5
+ #include <inttypes.h>
6
+ #include <stdint.h>
7
+ #include <stdio.h>
8
+
9
+ #endif
10
+
11
+ void unload_{kernel_name}(void);
12
+ void load_{kernel_name}(void);
13
+ // tt-linker: {kernel_name}:{full_signature}:{algo_info}
14
+ CUresult{_placeholder} {kernel_name}(CUstream stream, {signature});
evalkit_tf437/lib/python3.10/site-packages/triton/tools/compile.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import binascii
2
+ import hashlib
3
+ import importlib.util
4
+ import sys
5
+ from argparse import ArgumentParser
6
+ from pathlib import Path
7
+ from typing import List
8
+
9
+ import triton
10
+ from triton.compiler.code_generator import kernel_suffix
11
+ from triton.compiler.make_launcher import ty_to_cpp
12
+
13
+ desc = """
14
+ Triton ahead-of-time compiler:
15
+
16
+ This program compiles the kernel with name `kernel-name` in the file at the
17
+ provided `path` into self-contained C source-code that embeds the `cubin`
18
+ data along with utilities to load, unload and launch the kernel.
19
+
20
+ signature is provided as a list of (optionally divisibility-hinted) types
21
+ or constexpr values, e.g.
22
+
23
+ `compile.py --kernel-name kernel --signature "*fp32:16, i32:16, 1024, i32" --out-name kernel /path/to/kernel.py`
24
+
25
+ will compile triton.JITFunction of name `kernel` inside the file `/path/to/kernel.py`.
26
+ Said kernel will be specialized such that argument 0, 1 are assumed to be multiple of 16,
27
+ and argument 2 is assumed to be a compile-time constant of value 1024, i.e. it won't be part of the generated prototype.
28
+
29
+ The resulting entry point will have signature
30
+
31
+ CUresult kernel_{specialization_suffix}(CUstream stream, unsigned gX, unsigned gY, unsigned gZ, float* arg0, int32_t arg1, int32_t arg2)
32
+
33
+ Different such specialized entry points can be combined using the `linker.py` script.
34
+
35
+ NOTE: when resolving the scope of /path/to/kernel.py, the file will be executed from within its parent directory with the python interpreter
36
+ used to run this `compile.py` script
37
+ """
38
+
39
+ if __name__ == "__main__":
40
+
41
+ # command-line arguments
42
+ parser = ArgumentParser(description=desc)
43
+ parser.add_argument("path",
44
+ help="Path to Python source containing desired kernel in its scope. File will be executed.")
45
+ parser.add_argument("--kernel-name", "-n", type=str, default="", help="Name of the kernel to compile",
46
+ required=True)
47
+ parser.add_argument("--num-warps", "-w", type=int, default=1, help="Number of warps to launch the kernel")
48
+ parser.add_argument("--num-stages", "-ns", type=int, default=3,
49
+ help="Number of stages (meta-parameter of the kernel)")
50
+ parser.add_argument("--out-name", "-on", type=str, default=None, help="Out name for the compiled kernel")
51
+ parser.add_argument("--out-path", "-o", type=Path, default=None, help="Out filename")
52
+ parser.add_argument("--signature", "-s", type=str, help="Signature of the kernel", required=True)
53
+ parser.add_argument("--grid", "-g", type=str, help="Launch grid of the kernel", required=True)
54
+ args = parser.parse_args()
55
+
56
+ out_name = args.out_name if args.out_name else args.kernel_name
57
+ out_path = args.out_path if args.out_path else Path(out_name)
58
+
59
+ # execute python sources and extract functions wrapped in JITFunction
60
+ arg_path = Path(args.path)
61
+ sys.path.insert(0, str(arg_path.parent))
62
+ spec = importlib.util.spec_from_file_location(arg_path.stem, arg_path)
63
+ mod = importlib.util.module_from_spec(spec)
64
+ spec.loader.exec_module(mod)
65
+ kernel = getattr(mod, args.kernel_name)
66
+ grid = args.grid.split(",")
67
+ assert len(grid) == 3
68
+
69
+ # validate and parse signature
70
+ signature = list(map(lambda s: s.strip(" "), args.signature.split(",")))
71
+
72
+ def hash_signature(signature: List[str]):
73
+ m = hashlib.sha256()
74
+ m.update(" ".join(signature).encode())
75
+ return m.hexdigest()[:8]
76
+
77
+ meta_sig = f"warps{args.num_warps}xstages{args.num_stages}"
78
+ sig_hash = hash_signature(signature + [meta_sig])
79
+
80
+ def constexpr(s):
81
+ try:
82
+ ret = int(s)
83
+ return ret
84
+ except ValueError:
85
+ pass
86
+ try:
87
+ ret = float(s)
88
+ return ret
89
+ except ValueError:
90
+ pass
91
+ return None
92
+
93
+ hints = {i: constexpr(s.split(":")[1]) for i, s in enumerate(signature) if ":" in s}
94
+ hints = {k: v for k, v in hints.items() if v is not None}
95
+ constexprs = {i: constexpr(s) for i, s in enumerate(signature)}
96
+ constexprs = {k: v for k, v in constexprs.items() if v is not None}
97
+ signature = {i: s.split(":")[0] for i, s in enumerate(signature) if i not in constexprs}
98
+ const_sig = 'x'.join([str(v) for v in constexprs.values()])
99
+ doc_string = [f"{kernel.arg_names[i]}={constexprs[i]}" for i in constexprs.keys()]
100
+ doc_string += [f"num_warps={args.num_warps}", f"num_stages={args.num_stages}"]
101
+
102
+ # compile ast into cubin
103
+ for h in hints.values():
104
+ assert h in [1, 16], f"Only 1 and 16 are valid hints, got {h}"
105
+ divisible_by_16 = [i for i, h in hints.items() if h == 16]
106
+ equal_to_1 = [i for i, h in hints.items() if h == 1]
107
+ config = triton.compiler.instance_descriptor(divisible_by_16=divisible_by_16, equal_to_1=equal_to_1)
108
+ for i in equal_to_1:
109
+ constexprs.update({i: 1})
110
+ ccinfo = triton.compile(kernel, signature=signature, constants=constexprs, configs=[config],
111
+ num_warps=args.num_warps, num_stages=args.num_stages)
112
+ arg_names = []
113
+ arg_types = []
114
+ for i in signature.keys():
115
+ if i not in equal_to_1:
116
+ arg_names += [kernel.arg_names[i]]
117
+ arg_types += [signature[i]]
118
+
119
+ # dump C stub code
120
+ suffix = kernel_suffix(signature.values(), config)
121
+ func_name = '_'.join([out_name, sig_hash, suffix])
122
+ triton_kernel_name = '_'.join([args.kernel_name, suffix])
123
+ hex_ = str(binascii.hexlify(ccinfo.asm["cubin"]))[2:-1]
124
+ params = {
125
+ "kernel_name": func_name,
126
+ "triton_kernel_name": triton_kernel_name,
127
+ "bin_size": len(hex_),
128
+ "bin_data": ", ".join([f"0x{x}{y}" for x, y in zip(hex_[::2], hex_[1::2])]),
129
+ "signature": ", ".join([f"{ty_to_cpp(ty)} {name}" for name, ty in zip(arg_names, arg_types)]),
130
+ "full_signature": ", ".join([f"{ty_to_cpp(signature[i])} {kernel.arg_names[i]}" for i in signature.keys()]),
131
+ "arg_pointers": ", ".join([f"&{arg}" for arg in arg_names]),
132
+ "num_args": len(arg_names),
133
+ "kernel_docstring": doc_string,
134
+ "shared": ccinfo.shared,
135
+ "num_warps": args.num_warps,
136
+ "algo_info": '_'.join([const_sig, meta_sig]),
137
+ "gridX": grid[0],
138
+ "gridY": grid[1],
139
+ "gridZ": grid[2],
140
+ "_placeholder": "",
141
+ }
142
+ for ext in ['h', 'c']:
143
+ template_path = Path(__file__).parent / f"compile.{ext}"
144
+ with out_path.with_suffix(f".{sig_hash}_{suffix}.{ext}").open("w") as fp:
145
+ fp.write(Path(template_path).read_text().format(**params))
falcon/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (375 Bytes). View file
 
falcon/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/all.cpython-310.pyc ADDED
Binary file (9.13 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/product.cpython-310.pyc ADDED
Binary file (18.2 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/algorithms/operators/__pycache__/unary.cpython-310.pyc ADDED
Binary file (2.19 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/algorithms/operators/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (187 Bytes). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # graph drawing and interface to graphviz
2
+
3
+ from .layout import *
4
+ from .nx_latex import *
5
+ from .nx_pylab import *
6
+ from . import nx_agraph
7
+ from . import nx_pydot
falcon/lib/python3.10/site-packages/networkx/drawing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (296 Bytes). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/__pycache__/layout.cpython-310.pyc ADDED
Binary file (40.9 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_agraph.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_latex.cpython-310.pyc ADDED
Binary file (22.2 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pydot.cpython-310.pyc ADDED
Binary file (8.45 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-310.pyc ADDED
Binary file (54.5 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/layout.py ADDED
@@ -0,0 +1,1630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ******
3
+ Layout
4
+ ******
5
+
6
+ Node positioning algorithms for graph drawing.
7
+
8
+ For `random_layout()` the possible resulting shape
9
+ is a square of side [0, scale] (default: [0, 1])
10
+ Changing `center` shifts the layout by that amount.
11
+
12
+ For the other layout routines, the extent is
13
+ [center - scale, center + scale] (default: [-1, 1]).
14
+
15
+ Warning: Most layout routines have only been tested in 2-dimensions.
16
+
17
+ """
18
+
19
+ import networkx as nx
20
+ from networkx.utils import np_random_state
21
+
22
+ __all__ = [
23
+ "bipartite_layout",
24
+ "circular_layout",
25
+ "forceatlas2_layout",
26
+ "kamada_kawai_layout",
27
+ "random_layout",
28
+ "rescale_layout",
29
+ "rescale_layout_dict",
30
+ "shell_layout",
31
+ "spring_layout",
32
+ "spectral_layout",
33
+ "planar_layout",
34
+ "fruchterman_reingold_layout",
35
+ "spiral_layout",
36
+ "multipartite_layout",
37
+ "bfs_layout",
38
+ "arf_layout",
39
+ ]
40
+
41
+
42
+ def _process_params(G, center, dim):
43
+ # Some boilerplate code.
44
+ import numpy as np
45
+
46
+ if not isinstance(G, nx.Graph):
47
+ empty_graph = nx.Graph()
48
+ empty_graph.add_nodes_from(G)
49
+ G = empty_graph
50
+
51
+ if center is None:
52
+ center = np.zeros(dim)
53
+ else:
54
+ center = np.asarray(center)
55
+
56
+ if len(center) != dim:
57
+ msg = "length of center coordinates must match dimension of layout"
58
+ raise ValueError(msg)
59
+
60
+ return G, center
61
+
62
+
63
+ @np_random_state(3)
64
+ def random_layout(G, center=None, dim=2, seed=None):
65
+ """Position nodes uniformly at random in the unit square.
66
+
67
+ For every node, a position is generated by choosing each of dim
68
+ coordinates uniformly at random on the interval [0.0, 1.0).
69
+
70
+ NumPy (http://scipy.org) is required for this function.
71
+
72
+ Parameters
73
+ ----------
74
+ G : NetworkX graph or list of nodes
75
+ A position will be assigned to every node in G.
76
+
77
+ center : array-like or None
78
+ Coordinate pair around which to center the layout.
79
+
80
+ dim : int
81
+ Dimension of layout.
82
+
83
+ seed : int, RandomState instance or None optional (default=None)
84
+ Set the random state for deterministic node layouts.
85
+ If int, `seed` is the seed used by the random number generator,
86
+ if numpy.random.RandomState instance, `seed` is the random
87
+ number generator,
88
+ if None, the random number generator is the RandomState instance used
89
+ by numpy.random.
90
+
91
+ Returns
92
+ -------
93
+ pos : dict
94
+ A dictionary of positions keyed by node
95
+
96
+ Examples
97
+ --------
98
+ >>> G = nx.lollipop_graph(4, 3)
99
+ >>> pos = nx.random_layout(G)
100
+
101
+ """
102
+ import numpy as np
103
+
104
+ G, center = _process_params(G, center, dim)
105
+ pos = seed.rand(len(G), dim) + center
106
+ pos = pos.astype(np.float32)
107
+ pos = dict(zip(G, pos))
108
+
109
+ return pos
110
+
111
+
112
+ def circular_layout(G, scale=1, center=None, dim=2):
113
+ # dim=2 only
114
+ """Position nodes on a circle.
115
+
116
+ Parameters
117
+ ----------
118
+ G : NetworkX graph or list of nodes
119
+ A position will be assigned to every node in G.
120
+
121
+ scale : number (default: 1)
122
+ Scale factor for positions.
123
+
124
+ center : array-like or None
125
+ Coordinate pair around which to center the layout.
126
+
127
+ dim : int
128
+ Dimension of layout.
129
+ If dim>2, the remaining dimensions are set to zero
130
+ in the returned positions.
131
+ If dim<2, a ValueError is raised.
132
+
133
+ Returns
134
+ -------
135
+ pos : dict
136
+ A dictionary of positions keyed by node
137
+
138
+ Raises
139
+ ------
140
+ ValueError
141
+ If dim < 2
142
+
143
+ Examples
144
+ --------
145
+ >>> G = nx.path_graph(4)
146
+ >>> pos = nx.circular_layout(G)
147
+
148
+ Notes
149
+ -----
150
+ This algorithm currently only works in two dimensions and does not
151
+ try to minimize edge crossings.
152
+
153
+ """
154
+ import numpy as np
155
+
156
+ if dim < 2:
157
+ raise ValueError("cannot handle dimensions < 2")
158
+
159
+ G, center = _process_params(G, center, dim)
160
+
161
+ paddims = max(0, (dim - 2))
162
+
163
+ if len(G) == 0:
164
+ pos = {}
165
+ elif len(G) == 1:
166
+ pos = {nx.utils.arbitrary_element(G): center}
167
+ else:
168
+ # Discard the extra angle since it matches 0 radians.
169
+ theta = np.linspace(0, 1, len(G) + 1)[:-1] * 2 * np.pi
170
+ theta = theta.astype(np.float32)
171
+ pos = np.column_stack(
172
+ [np.cos(theta), np.sin(theta), np.zeros((len(G), paddims))]
173
+ )
174
+ pos = rescale_layout(pos, scale=scale) + center
175
+ pos = dict(zip(G, pos))
176
+
177
+ return pos
178
+
179
+
180
+ def shell_layout(G, nlist=None, rotate=None, scale=1, center=None, dim=2):
181
+ """Position nodes in concentric circles.
182
+
183
+ Parameters
184
+ ----------
185
+ G : NetworkX graph or list of nodes
186
+ A position will be assigned to every node in G.
187
+
188
+ nlist : list of lists
189
+ List of node lists for each shell.
190
+
191
+ rotate : angle in radians (default=pi/len(nlist))
192
+ Angle by which to rotate the starting position of each shell
193
+ relative to the starting position of the previous shell.
194
+ To recreate behavior before v2.5 use rotate=0.
195
+
196
+ scale : number (default: 1)
197
+ Scale factor for positions.
198
+
199
+ center : array-like or None
200
+ Coordinate pair around which to center the layout.
201
+
202
+ dim : int
203
+ Dimension of layout, currently only dim=2 is supported.
204
+ Other dimension values result in a ValueError.
205
+
206
+ Returns
207
+ -------
208
+ pos : dict
209
+ A dictionary of positions keyed by node
210
+
211
+ Raises
212
+ ------
213
+ ValueError
214
+ If dim != 2
215
+
216
+ Examples
217
+ --------
218
+ >>> G = nx.path_graph(4)
219
+ >>> shells = [[0], [1, 2, 3]]
220
+ >>> pos = nx.shell_layout(G, shells)
221
+
222
+ Notes
223
+ -----
224
+ This algorithm currently only works in two dimensions and does not
225
+ try to minimize edge crossings.
226
+
227
+ """
228
+ import numpy as np
229
+
230
+ if dim != 2:
231
+ raise ValueError("can only handle 2 dimensions")
232
+
233
+ G, center = _process_params(G, center, dim)
234
+
235
+ if len(G) == 0:
236
+ return {}
237
+ if len(G) == 1:
238
+ return {nx.utils.arbitrary_element(G): center}
239
+
240
+ if nlist is None:
241
+ # draw the whole graph in one shell
242
+ nlist = [list(G)]
243
+
244
+ radius_bump = scale / len(nlist)
245
+
246
+ if len(nlist[0]) == 1:
247
+ # single node at center
248
+ radius = 0.0
249
+ else:
250
+ # else start at r=1
251
+ radius = radius_bump
252
+
253
+ if rotate is None:
254
+ rotate = np.pi / len(nlist)
255
+ first_theta = rotate
256
+ npos = {}
257
+ for nodes in nlist:
258
+ # Discard the last angle (endpoint=False) since 2*pi matches 0 radians
259
+ theta = (
260
+ np.linspace(0, 2 * np.pi, len(nodes), endpoint=False, dtype=np.float32)
261
+ + first_theta
262
+ )
263
+ pos = radius * np.column_stack([np.cos(theta), np.sin(theta)]) + center
264
+ npos.update(zip(nodes, pos))
265
+ radius += radius_bump
266
+ first_theta += rotate
267
+
268
+ return npos
269
+
270
+
271
+ def bipartite_layout(
272
+ G, nodes, align="vertical", scale=1, center=None, aspect_ratio=4 / 3
273
+ ):
274
+ """Position nodes in two straight lines.
275
+
276
+ Parameters
277
+ ----------
278
+ G : NetworkX graph or list of nodes
279
+ A position will be assigned to every node in G.
280
+
281
+ nodes : list or container
282
+ Nodes in one node set of the bipartite graph.
283
+ This set will be placed on left or top.
284
+
285
+ align : string (default='vertical')
286
+ The alignment of nodes. Vertical or horizontal.
287
+
288
+ scale : number (default: 1)
289
+ Scale factor for positions.
290
+
291
+ center : array-like or None
292
+ Coordinate pair around which to center the layout.
293
+
294
+ aspect_ratio : number (default=4/3):
295
+ The ratio of the width to the height of the layout.
296
+
297
+ Returns
298
+ -------
299
+ pos : dict
300
+ A dictionary of positions keyed by node.
301
+
302
+ Examples
303
+ --------
304
+ >>> G = nx.bipartite.gnmk_random_graph(3, 5, 10, seed=123)
305
+ >>> top = nx.bipartite.sets(G)[0]
306
+ >>> pos = nx.bipartite_layout(G, top)
307
+
308
+ Notes
309
+ -----
310
+ This algorithm currently only works in two dimensions and does not
311
+ try to minimize edge crossings.
312
+
313
+ """
314
+
315
+ import numpy as np
316
+
317
+ if align not in ("vertical", "horizontal"):
318
+ msg = "align must be either vertical or horizontal."
319
+ raise ValueError(msg)
320
+
321
+ G, center = _process_params(G, center=center, dim=2)
322
+ if len(G) == 0:
323
+ return {}
324
+
325
+ height = 1
326
+ width = aspect_ratio * height
327
+ offset = (width / 2, height / 2)
328
+
329
+ top = dict.fromkeys(nodes)
330
+ bottom = [v for v in G if v not in top]
331
+ nodes = list(top) + bottom
332
+
333
+ left_xs = np.repeat(0, len(top))
334
+ right_xs = np.repeat(width, len(bottom))
335
+ left_ys = np.linspace(0, height, len(top))
336
+ right_ys = np.linspace(0, height, len(bottom))
337
+
338
+ top_pos = np.column_stack([left_xs, left_ys]) - offset
339
+ bottom_pos = np.column_stack([right_xs, right_ys]) - offset
340
+
341
+ pos = np.concatenate([top_pos, bottom_pos])
342
+ pos = rescale_layout(pos, scale=scale) + center
343
+ if align == "horizontal":
344
+ pos = pos[:, ::-1] # swap x and y coords
345
+ pos = dict(zip(nodes, pos))
346
+ return pos
347
+
348
+
349
+ @np_random_state(10)
350
+ def spring_layout(
351
+ G,
352
+ k=None,
353
+ pos=None,
354
+ fixed=None,
355
+ iterations=50,
356
+ threshold=1e-4,
357
+ weight="weight",
358
+ scale=1,
359
+ center=None,
360
+ dim=2,
361
+ seed=None,
362
+ ):
363
+ """Position nodes using Fruchterman-Reingold force-directed algorithm.
364
+
365
+ The algorithm simulates a force-directed representation of the network
366
+ treating edges as springs holding nodes close, while treating nodes
367
+ as repelling objects, sometimes called an anti-gravity force.
368
+ Simulation continues until the positions are close to an equilibrium.
369
+
370
+ There are some hard-coded values: minimal distance between
371
+ nodes (0.01) and "temperature" of 0.1 to ensure nodes don't fly away.
372
+ During the simulation, `k` helps determine the distance between nodes,
373
+ though `scale` and `center` determine the size and place after
374
+ rescaling occurs at the end of the simulation.
375
+
376
+ Fixing some nodes doesn't allow them to move in the simulation.
377
+ It also turns off the rescaling feature at the simulation's end.
378
+ In addition, setting `scale` to `None` turns off rescaling.
379
+
380
+ Parameters
381
+ ----------
382
+ G : NetworkX graph or list of nodes
383
+ A position will be assigned to every node in G.
384
+
385
+ k : float (default=None)
386
+ Optimal distance between nodes. If None the distance is set to
387
+ 1/sqrt(n) where n is the number of nodes. Increase this value
388
+ to move nodes farther apart.
389
+
390
+ pos : dict or None optional (default=None)
391
+ Initial positions for nodes as a dictionary with node as keys
392
+ and values as a coordinate list or tuple. If None, then use
393
+ random initial positions.
394
+
395
+ fixed : list or None optional (default=None)
396
+ Nodes to keep fixed at initial position.
397
+ Nodes not in ``G.nodes`` are ignored.
398
+ ValueError raised if `fixed` specified and `pos` not.
399
+
400
+ iterations : int optional (default=50)
401
+ Maximum number of iterations taken
402
+
403
+ threshold: float optional (default = 1e-4)
404
+ Threshold for relative error in node position changes.
405
+ The iteration stops if the error is below this threshold.
406
+
407
+ weight : string or None optional (default='weight')
408
+ The edge attribute that holds the numerical value used for
409
+ the edge weight. Larger means a stronger attractive force.
410
+ If None, then all edge weights are 1.
411
+
412
+ scale : number or None (default: 1)
413
+ Scale factor for positions. Not used unless `fixed is None`.
414
+ If scale is None, no rescaling is performed.
415
+
416
+ center : array-like or None
417
+ Coordinate pair around which to center the layout.
418
+ Not used unless `fixed is None`.
419
+
420
+ dim : int
421
+ Dimension of layout.
422
+
423
+ seed : int, RandomState instance or None optional (default=None)
424
+ Used only for the initial positions in the algorithm.
425
+ Set the random state for deterministic node layouts.
426
+ If int, `seed` is the seed used by the random number generator,
427
+ if numpy.random.RandomState instance, `seed` is the random
428
+ number generator,
429
+ if None, the random number generator is the RandomState instance used
430
+ by numpy.random.
431
+
432
+ Returns
433
+ -------
434
+ pos : dict
435
+ A dictionary of positions keyed by node
436
+
437
+ Examples
438
+ --------
439
+ >>> G = nx.path_graph(4)
440
+ >>> pos = nx.spring_layout(G)
441
+
442
+ # The same using longer but equivalent function name
443
+ >>> pos = nx.fruchterman_reingold_layout(G)
444
+ """
445
+ import numpy as np
446
+
447
+ G, center = _process_params(G, center, dim)
448
+
449
+ if fixed is not None:
450
+ if pos is None:
451
+ raise ValueError("nodes are fixed without positions given")
452
+ for node in fixed:
453
+ if node not in pos:
454
+ raise ValueError("nodes are fixed without positions given")
455
+ nfixed = {node: i for i, node in enumerate(G)}
456
+ fixed = np.asarray([nfixed[node] for node in fixed if node in nfixed])
457
+
458
+ if pos is not None:
459
+ # Determine size of existing domain to adjust initial positions
460
+ dom_size = max(coord for pos_tup in pos.values() for coord in pos_tup)
461
+ if dom_size == 0:
462
+ dom_size = 1
463
+ pos_arr = seed.rand(len(G), dim) * dom_size + center
464
+
465
+ for i, n in enumerate(G):
466
+ if n in pos:
467
+ pos_arr[i] = np.asarray(pos[n])
468
+ else:
469
+ pos_arr = None
470
+ dom_size = 1
471
+
472
+ if len(G) == 0:
473
+ return {}
474
+ if len(G) == 1:
475
+ return {nx.utils.arbitrary_element(G.nodes()): center}
476
+
477
+ try:
478
+ # Sparse matrix
479
+ if len(G) < 500: # sparse solver for large graphs
480
+ raise ValueError
481
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype="f")
482
+ if k is None and fixed is not None:
483
+ # We must adjust k by domain size for layouts not near 1x1
484
+ nnodes, _ = A.shape
485
+ k = dom_size / np.sqrt(nnodes)
486
+ pos = _sparse_fruchterman_reingold(
487
+ A, k, pos_arr, fixed, iterations, threshold, dim, seed
488
+ )
489
+ except ValueError:
490
+ A = nx.to_numpy_array(G, weight=weight)
491
+ if k is None and fixed is not None:
492
+ # We must adjust k by domain size for layouts not near 1x1
493
+ nnodes, _ = A.shape
494
+ k = dom_size / np.sqrt(nnodes)
495
+ pos = _fruchterman_reingold(
496
+ A, k, pos_arr, fixed, iterations, threshold, dim, seed
497
+ )
498
+ if fixed is None and scale is not None:
499
+ pos = rescale_layout(pos, scale=scale) + center
500
+ pos = dict(zip(G, pos))
501
+ return pos
502
+
503
+
504
+ fruchterman_reingold_layout = spring_layout
505
+
506
+
507
+ @np_random_state(7)
508
+ def _fruchterman_reingold(
509
+ A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
510
+ ):
511
+ # Position nodes in adjacency matrix A using Fruchterman-Reingold
512
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
513
+ import numpy as np
514
+
515
+ try:
516
+ nnodes, _ = A.shape
517
+ except AttributeError as err:
518
+ msg = "fruchterman_reingold() takes an adjacency matrix as input"
519
+ raise nx.NetworkXError(msg) from err
520
+
521
+ if pos is None:
522
+ # random initial positions
523
+ pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
524
+ else:
525
+ # make sure positions are of same type as matrix
526
+ pos = pos.astype(A.dtype)
527
+
528
+ # optimal distance between nodes
529
+ if k is None:
530
+ k = np.sqrt(1.0 / nnodes)
531
+ # the initial "temperature" is about .1 of domain area (=1x1)
532
+ # this is the largest step allowed in the dynamics.
533
+ # We need to calculate this in case our fixed positions force our domain
534
+ # to be much bigger than 1x1
535
+ t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
536
+ # simple cooling scheme.
537
+ # linearly step down by dt on each iteration so last iteration is size dt.
538
+ dt = t / (iterations + 1)
539
+ delta = np.zeros((pos.shape[0], pos.shape[0], pos.shape[1]), dtype=A.dtype)
540
+ # the inscrutable (but fast) version
541
+ # this is still O(V^2)
542
+ # could use multilevel methods to speed this up significantly
543
+ for iteration in range(iterations):
544
+ # matrix of difference between points
545
+ delta = pos[:, np.newaxis, :] - pos[np.newaxis, :, :]
546
+ # distance between points
547
+ distance = np.linalg.norm(delta, axis=-1)
548
+ # enforce minimum distance of 0.01
549
+ np.clip(distance, 0.01, None, out=distance)
550
+ # displacement "force"
551
+ displacement = np.einsum(
552
+ "ijk,ij->ik", delta, (k * k / distance**2 - A * distance / k)
553
+ )
554
+ # update positions
555
+ length = np.linalg.norm(displacement, axis=-1)
556
+ length = np.where(length < 0.01, 0.1, length)
557
+ delta_pos = np.einsum("ij,i->ij", displacement, t / length)
558
+ if fixed is not None:
559
+ # don't change positions of fixed nodes
560
+ delta_pos[fixed] = 0.0
561
+ pos += delta_pos
562
+ # cool temperature
563
+ t -= dt
564
+ if (np.linalg.norm(delta_pos) / nnodes) < threshold:
565
+ break
566
+ return pos
567
+
568
+
569
+ @np_random_state(7)
570
+ def _sparse_fruchterman_reingold(
571
+ A, k=None, pos=None, fixed=None, iterations=50, threshold=1e-4, dim=2, seed=None
572
+ ):
573
+ # Position nodes in adjacency matrix A using Fruchterman-Reingold
574
+ # Entry point for NetworkX graph is fruchterman_reingold_layout()
575
+ # Sparse version
576
+ import numpy as np
577
+ import scipy as sp
578
+
579
+ try:
580
+ nnodes, _ = A.shape
581
+ except AttributeError as err:
582
+ msg = "fruchterman_reingold() takes an adjacency matrix as input"
583
+ raise nx.NetworkXError(msg) from err
584
+ # make sure we have a LIst of Lists representation
585
+ try:
586
+ A = A.tolil()
587
+ except AttributeError:
588
+ A = (sp.sparse.coo_array(A)).tolil()
589
+
590
+ if pos is None:
591
+ # random initial positions
592
+ pos = np.asarray(seed.rand(nnodes, dim), dtype=A.dtype)
593
+ else:
594
+ # make sure positions are of same type as matrix
595
+ pos = pos.astype(A.dtype)
596
+
597
+ # no fixed nodes
598
+ if fixed is None:
599
+ fixed = []
600
+
601
+ # optimal distance between nodes
602
+ if k is None:
603
+ k = np.sqrt(1.0 / nnodes)
604
+ # the initial "temperature" is about .1 of domain area (=1x1)
605
+ # this is the largest step allowed in the dynamics.
606
+ t = max(max(pos.T[0]) - min(pos.T[0]), max(pos.T[1]) - min(pos.T[1])) * 0.1
607
+ # simple cooling scheme.
608
+ # linearly step down by dt on each iteration so last iteration is size dt.
609
+ dt = t / (iterations + 1)
610
+
611
+ displacement = np.zeros((dim, nnodes))
612
+ for iteration in range(iterations):
613
+ displacement *= 0
614
+ # loop over rows
615
+ for i in range(A.shape[0]):
616
+ if i in fixed:
617
+ continue
618
+ # difference between this row's node position and all others
619
+ delta = (pos[i] - pos).T
620
+ # distance between points
621
+ distance = np.sqrt((delta**2).sum(axis=0))
622
+ # enforce minimum distance of 0.01
623
+ distance = np.where(distance < 0.01, 0.01, distance)
624
+ # the adjacency matrix row
625
+ Ai = A.getrowview(i).toarray() # TODO: revisit w/ sparse 1D container
626
+ # displacement "force"
627
+ displacement[:, i] += (
628
+ delta * (k * k / distance**2 - Ai * distance / k)
629
+ ).sum(axis=1)
630
+ # update positions
631
+ length = np.sqrt((displacement**2).sum(axis=0))
632
+ length = np.where(length < 0.01, 0.1, length)
633
+ delta_pos = (displacement * t / length).T
634
+ pos += delta_pos
635
+ # cool temperature
636
+ t -= dt
637
+ if (np.linalg.norm(delta_pos) / nnodes) < threshold:
638
+ break
639
+ return pos
640
+
641
+
642
+ def kamada_kawai_layout(
643
+ G, dist=None, pos=None, weight="weight", scale=1, center=None, dim=2
644
+ ):
645
+ """Position nodes using Kamada-Kawai path-length cost-function.
646
+
647
+ Parameters
648
+ ----------
649
+ G : NetworkX graph or list of nodes
650
+ A position will be assigned to every node in G.
651
+
652
+ dist : dict (default=None)
653
+ A two-level dictionary of optimal distances between nodes,
654
+ indexed by source and destination node.
655
+ If None, the distance is computed using shortest_path_length().
656
+
657
+ pos : dict or None optional (default=None)
658
+ Initial positions for nodes as a dictionary with node as keys
659
+ and values as a coordinate list or tuple. If None, then use
660
+ circular_layout() for dim >= 2 and a linear layout for dim == 1.
661
+
662
+ weight : string or None optional (default='weight')
663
+ The edge attribute that holds the numerical value used for
664
+ the edge weight. If None, then all edge weights are 1.
665
+
666
+ scale : number (default: 1)
667
+ Scale factor for positions.
668
+
669
+ center : array-like or None
670
+ Coordinate pair around which to center the layout.
671
+
672
+ dim : int
673
+ Dimension of layout.
674
+
675
+ Returns
676
+ -------
677
+ pos : dict
678
+ A dictionary of positions keyed by node
679
+
680
+ Examples
681
+ --------
682
+ >>> G = nx.path_graph(4)
683
+ >>> pos = nx.kamada_kawai_layout(G)
684
+ """
685
+ import numpy as np
686
+
687
+ G, center = _process_params(G, center, dim)
688
+ nNodes = len(G)
689
+ if nNodes == 0:
690
+ return {}
691
+
692
+ if dist is None:
693
+ dist = dict(nx.shortest_path_length(G, weight=weight))
694
+ dist_mtx = 1e6 * np.ones((nNodes, nNodes))
695
+ for row, nr in enumerate(G):
696
+ if nr not in dist:
697
+ continue
698
+ rdist = dist[nr]
699
+ for col, nc in enumerate(G):
700
+ if nc not in rdist:
701
+ continue
702
+ dist_mtx[row][col] = rdist[nc]
703
+
704
+ if pos is None:
705
+ if dim >= 3:
706
+ pos = random_layout(G, dim=dim)
707
+ elif dim == 2:
708
+ pos = circular_layout(G, dim=dim)
709
+ else:
710
+ pos = dict(zip(G, np.linspace(0, 1, len(G))))
711
+ pos_arr = np.array([pos[n] for n in G])
712
+
713
+ pos = _kamada_kawai_solve(dist_mtx, pos_arr, dim)
714
+
715
+ pos = rescale_layout(pos, scale=scale) + center
716
+ return dict(zip(G, pos))
717
+
718
+
719
+ def _kamada_kawai_solve(dist_mtx, pos_arr, dim):
720
+ # Anneal node locations based on the Kamada-Kawai cost-function,
721
+ # using the supplied matrix of preferred inter-node distances,
722
+ # and starting locations.
723
+
724
+ import numpy as np
725
+ import scipy as sp
726
+
727
+ meanwt = 1e-3
728
+ costargs = (np, 1 / (dist_mtx + np.eye(dist_mtx.shape[0]) * 1e-3), meanwt, dim)
729
+
730
+ optresult = sp.optimize.minimize(
731
+ _kamada_kawai_costfn,
732
+ pos_arr.ravel(),
733
+ method="L-BFGS-B",
734
+ args=costargs,
735
+ jac=True,
736
+ )
737
+
738
+ return optresult.x.reshape((-1, dim))
739
+
740
+
741
+ def _kamada_kawai_costfn(pos_vec, np, invdist, meanweight, dim):
742
+ # Cost-function and gradient for Kamada-Kawai layout algorithm
743
+ nNodes = invdist.shape[0]
744
+ pos_arr = pos_vec.reshape((nNodes, dim))
745
+
746
+ delta = pos_arr[:, np.newaxis, :] - pos_arr[np.newaxis, :, :]
747
+ nodesep = np.linalg.norm(delta, axis=-1)
748
+ direction = np.einsum("ijk,ij->ijk", delta, 1 / (nodesep + np.eye(nNodes) * 1e-3))
749
+
750
+ offset = nodesep * invdist - 1.0
751
+ offset[np.diag_indices(nNodes)] = 0
752
+
753
+ cost = 0.5 * np.sum(offset**2)
754
+ grad = np.einsum("ij,ij,ijk->ik", invdist, offset, direction) - np.einsum(
755
+ "ij,ij,ijk->jk", invdist, offset, direction
756
+ )
757
+
758
+ # Additional parabolic term to encourage mean position to be near origin:
759
+ sumpos = np.sum(pos_arr, axis=0)
760
+ cost += 0.5 * meanweight * np.sum(sumpos**2)
761
+ grad += meanweight * sumpos
762
+
763
+ return (cost, grad.ravel())
764
+
765
+
766
+ def spectral_layout(G, weight="weight", scale=1, center=None, dim=2):
767
+ """Position nodes using the eigenvectors of the graph Laplacian.
768
+
769
+ Using the unnormalized Laplacian, the layout shows possible clusters of
770
+ nodes which are an approximation of the ratio cut. If dim is the number of
771
+ dimensions then the positions are the entries of the dim eigenvectors
772
+ corresponding to the ascending eigenvalues starting from the second one.
773
+
774
+ Parameters
775
+ ----------
776
+ G : NetworkX graph or list of nodes
777
+ A position will be assigned to every node in G.
778
+
779
+ weight : string or None optional (default='weight')
780
+ The edge attribute that holds the numerical value used for
781
+ the edge weight. If None, then all edge weights are 1.
782
+
783
+ scale : number (default: 1)
784
+ Scale factor for positions.
785
+
786
+ center : array-like or None
787
+ Coordinate pair around which to center the layout.
788
+
789
+ dim : int
790
+ Dimension of layout.
791
+
792
+ Returns
793
+ -------
794
+ pos : dict
795
+ A dictionary of positions keyed by node
796
+
797
+ Examples
798
+ --------
799
+ >>> G = nx.path_graph(4)
800
+ >>> pos = nx.spectral_layout(G)
801
+
802
+ Notes
803
+ -----
804
+ Directed graphs will be considered as undirected graphs when
805
+ positioning the nodes.
806
+
807
+ For larger graphs (>500 nodes) this will use the SciPy sparse
808
+ eigenvalue solver (ARPACK).
809
+ """
810
+ # handle some special cases that break the eigensolvers
811
+ import numpy as np
812
+
813
+ G, center = _process_params(G, center, dim)
814
+
815
+ if len(G) <= 2:
816
+ if len(G) == 0:
817
+ pos = np.array([])
818
+ elif len(G) == 1:
819
+ pos = np.array([center])
820
+ else:
821
+ pos = np.array([np.zeros(dim), np.array(center) * 2.0])
822
+ return dict(zip(G, pos))
823
+ try:
824
+ # Sparse matrix
825
+ if len(G) < 500: # dense solver is faster for small graphs
826
+ raise ValueError
827
+ A = nx.to_scipy_sparse_array(G, weight=weight, dtype="d")
828
+ # Symmetrize directed graphs
829
+ if G.is_directed():
830
+ A = A + np.transpose(A)
831
+ pos = _sparse_spectral(A, dim)
832
+ except (ImportError, ValueError):
833
+ # Dense matrix
834
+ A = nx.to_numpy_array(G, weight=weight)
835
+ # Symmetrize directed graphs
836
+ if G.is_directed():
837
+ A += A.T
838
+ pos = _spectral(A, dim)
839
+
840
+ pos = rescale_layout(pos, scale=scale) + center
841
+ pos = dict(zip(G, pos))
842
+ return pos
843
+
844
+
845
+ def _spectral(A, dim=2):
846
+ # Input adjacency matrix A
847
+ # Uses dense eigenvalue solver from numpy
848
+ import numpy as np
849
+
850
+ try:
851
+ nnodes, _ = A.shape
852
+ except AttributeError as err:
853
+ msg = "spectral() takes an adjacency matrix as input"
854
+ raise nx.NetworkXError(msg) from err
855
+
856
+ # form Laplacian matrix where D is diagonal of degrees
857
+ D = np.identity(nnodes, dtype=A.dtype) * np.sum(A, axis=1)
858
+ L = D - A
859
+
860
+ eigenvalues, eigenvectors = np.linalg.eig(L)
861
+ # sort and keep smallest nonzero
862
+ index = np.argsort(eigenvalues)[1 : dim + 1] # 0 index is zero eigenvalue
863
+ return np.real(eigenvectors[:, index])
864
+
865
+
866
+ def _sparse_spectral(A, dim=2):
867
+ # Input adjacency matrix A
868
+ # Uses sparse eigenvalue solver from scipy
869
+ # Could use multilevel methods here, see Koren "On spectral graph drawing"
870
+ import numpy as np
871
+ import scipy as sp
872
+
873
+ try:
874
+ nnodes, _ = A.shape
875
+ except AttributeError as err:
876
+ msg = "sparse_spectral() takes an adjacency matrix as input"
877
+ raise nx.NetworkXError(msg) from err
878
+
879
+ # form Laplacian matrix
880
+ # TODO: Rm csr_array wrapper in favor of spdiags array constructor when available
881
+ D = sp.sparse.csr_array(sp.sparse.spdiags(A.sum(axis=1), 0, nnodes, nnodes))
882
+ L = D - A
883
+
884
+ k = dim + 1
885
+ # number of Lanczos vectors for ARPACK solver.What is the right scaling?
886
+ ncv = max(2 * k + 1, int(np.sqrt(nnodes)))
887
+ # return smallest k eigenvalues and eigenvectors
888
+ eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(L, k, which="SM", ncv=ncv)
889
+ index = np.argsort(eigenvalues)[1:k] # 0 index is zero eigenvalue
890
+ return np.real(eigenvectors[:, index])
891
+
892
+
893
+ def planar_layout(G, scale=1, center=None, dim=2):
894
+ """Position nodes without edge intersections.
895
+
896
+ Parameters
897
+ ----------
898
+ G : NetworkX graph or list of nodes
899
+ A position will be assigned to every node in G. If G is of type
900
+ nx.PlanarEmbedding, the positions are selected accordingly.
901
+
902
+ scale : number (default: 1)
903
+ Scale factor for positions.
904
+
905
+ center : array-like or None
906
+ Coordinate pair around which to center the layout.
907
+
908
+ dim : int
909
+ Dimension of layout.
910
+
911
+ Returns
912
+ -------
913
+ pos : dict
914
+ A dictionary of positions keyed by node
915
+
916
+ Raises
917
+ ------
918
+ NetworkXException
919
+ If G is not planar
920
+
921
+ Examples
922
+ --------
923
+ >>> G = nx.path_graph(4)
924
+ >>> pos = nx.planar_layout(G)
925
+ """
926
+ import numpy as np
927
+
928
+ if dim != 2:
929
+ raise ValueError("can only handle 2 dimensions")
930
+
931
+ G, center = _process_params(G, center, dim)
932
+
933
+ if len(G) == 0:
934
+ return {}
935
+
936
+ if isinstance(G, nx.PlanarEmbedding):
937
+ embedding = G
938
+ else:
939
+ is_planar, embedding = nx.check_planarity(G)
940
+ if not is_planar:
941
+ raise nx.NetworkXException("G is not planar.")
942
+ pos = nx.combinatorial_embedding_to_pos(embedding)
943
+ node_list = list(embedding)
944
+ pos = np.vstack([pos[x] for x in node_list])
945
+ pos = pos.astype(np.float64)
946
+ pos = rescale_layout(pos, scale=scale) + center
947
+ return dict(zip(node_list, pos))
948
+
949
+
950
+ def spiral_layout(G, scale=1, center=None, dim=2, resolution=0.35, equidistant=False):
951
+ """Position nodes in a spiral layout.
952
+
953
+ Parameters
954
+ ----------
955
+ G : NetworkX graph or list of nodes
956
+ A position will be assigned to every node in G.
957
+ scale : number (default: 1)
958
+ Scale factor for positions.
959
+ center : array-like or None
960
+ Coordinate pair around which to center the layout.
961
+ dim : int, default=2
962
+ Dimension of layout, currently only dim=2 is supported.
963
+ Other dimension values result in a ValueError.
964
+ resolution : float, default=0.35
965
+ The compactness of the spiral layout returned.
966
+ Lower values result in more compressed spiral layouts.
967
+ equidistant : bool, default=False
968
+ If True, nodes will be positioned equidistant from each other
969
+ by decreasing angle further from center.
970
+ If False, nodes will be positioned at equal angles
971
+ from each other by increasing separation further from center.
972
+
973
+ Returns
974
+ -------
975
+ pos : dict
976
+ A dictionary of positions keyed by node
977
+
978
+ Raises
979
+ ------
980
+ ValueError
981
+ If dim != 2
982
+
983
+ Examples
984
+ --------
985
+ >>> G = nx.path_graph(4)
986
+ >>> pos = nx.spiral_layout(G)
987
+ >>> nx.draw(G, pos=pos)
988
+
989
+ Notes
990
+ -----
991
+ This algorithm currently only works in two dimensions.
992
+
993
+ """
994
+ import numpy as np
995
+
996
+ if dim != 2:
997
+ raise ValueError("can only handle 2 dimensions")
998
+
999
+ G, center = _process_params(G, center, dim)
1000
+
1001
+ if len(G) == 0:
1002
+ return {}
1003
+ if len(G) == 1:
1004
+ return {nx.utils.arbitrary_element(G): center}
1005
+
1006
+ pos = []
1007
+ if equidistant:
1008
+ chord = 1
1009
+ step = 0.5
1010
+ theta = resolution
1011
+ theta += chord / (step * theta)
1012
+ for _ in range(len(G)):
1013
+ r = step * theta
1014
+ theta += chord / r
1015
+ pos.append([np.cos(theta) * r, np.sin(theta) * r])
1016
+
1017
+ else:
1018
+ dist = np.arange(len(G), dtype=float)
1019
+ angle = resolution * dist
1020
+ pos = np.transpose(dist * np.array([np.cos(angle), np.sin(angle)]))
1021
+
1022
+ pos = rescale_layout(np.array(pos), scale=scale) + center
1023
+
1024
+ pos = dict(zip(G, pos))
1025
+
1026
+ return pos
1027
+
1028
+
1029
+ def multipartite_layout(G, subset_key="subset", align="vertical", scale=1, center=None):
1030
+ """Position nodes in layers of straight lines.
1031
+
1032
+ Parameters
1033
+ ----------
1034
+ G : NetworkX graph or list of nodes
1035
+ A position will be assigned to every node in G.
1036
+
1037
+ subset_key : string or dict (default='subset')
1038
+ If a string, the key of node data in G that holds the node subset.
1039
+ If a dict, keyed by layer number to the nodes in that layer/subset.
1040
+
1041
+ align : string (default='vertical')
1042
+ The alignment of nodes. Vertical or horizontal.
1043
+
1044
+ scale : number (default: 1)
1045
+ Scale factor for positions.
1046
+
1047
+ center : array-like or None
1048
+ Coordinate pair around which to center the layout.
1049
+
1050
+ Returns
1051
+ -------
1052
+ pos : dict
1053
+ A dictionary of positions keyed by node.
1054
+
1055
+ Examples
1056
+ --------
1057
+ >>> G = nx.complete_multipartite_graph(28, 16, 10)
1058
+ >>> pos = nx.multipartite_layout(G)
1059
+
1060
+ or use a dict to provide the layers of the layout
1061
+
1062
+ >>> G = nx.Graph([(0, 1), (1, 2), (1, 3), (3, 4)])
1063
+ >>> layers = {"a": [0], "b": [1], "c": [2, 3], "d": [4]}
1064
+ >>> pos = nx.multipartite_layout(G, subset_key=layers)
1065
+
1066
+ Notes
1067
+ -----
1068
+ This algorithm currently only works in two dimensions and does not
1069
+ try to minimize edge crossings.
1070
+
1071
+ Network does not need to be a complete multipartite graph. As long as nodes
1072
+ have subset_key data, they will be placed in the corresponding layers.
1073
+
1074
+ """
1075
+ import numpy as np
1076
+
1077
+ if align not in ("vertical", "horizontal"):
1078
+ msg = "align must be either vertical or horizontal."
1079
+ raise ValueError(msg)
1080
+
1081
+ G, center = _process_params(G, center=center, dim=2)
1082
+ if len(G) == 0:
1083
+ return {}
1084
+
1085
+ try:
1086
+ # check if subset_key is dict-like
1087
+ if len(G) != sum(len(nodes) for nodes in subset_key.values()):
1088
+ raise nx.NetworkXError(
1089
+ "all nodes must be in one subset of `subset_key` dict"
1090
+ )
1091
+ except AttributeError:
1092
+ # subset_key is not a dict, hence a string
1093
+ node_to_subset = nx.get_node_attributes(G, subset_key)
1094
+ if len(node_to_subset) != len(G):
1095
+ raise nx.NetworkXError(
1096
+ f"all nodes need a subset_key attribute: {subset_key}"
1097
+ )
1098
+ subset_key = nx.utils.groups(node_to_subset)
1099
+
1100
+ # Sort by layer, if possible
1101
+ try:
1102
+ layers = dict(sorted(subset_key.items()))
1103
+ except TypeError:
1104
+ layers = subset_key
1105
+
1106
+ pos = None
1107
+ nodes = []
1108
+ width = len(layers)
1109
+ for i, layer in enumerate(layers.values()):
1110
+ height = len(layer)
1111
+ xs = np.repeat(i, height)
1112
+ ys = np.arange(0, height, dtype=float)
1113
+ offset = ((width - 1) / 2, (height - 1) / 2)
1114
+ layer_pos = np.column_stack([xs, ys]) - offset
1115
+ if pos is None:
1116
+ pos = layer_pos
1117
+ else:
1118
+ pos = np.concatenate([pos, layer_pos])
1119
+ nodes.extend(layer)
1120
+ pos = rescale_layout(pos, scale=scale) + center
1121
+ if align == "horizontal":
1122
+ pos = pos[:, ::-1] # swap x and y coords
1123
+ pos = dict(zip(nodes, pos))
1124
+ return pos
1125
+
1126
+
1127
+ @np_random_state("seed")
1128
+ def arf_layout(
1129
+ G,
1130
+ pos=None,
1131
+ scaling=1,
1132
+ a=1.1,
1133
+ etol=1e-6,
1134
+ dt=1e-3,
1135
+ max_iter=1000,
1136
+ *,
1137
+ seed=None,
1138
+ ):
1139
+ """Arf layout for networkx
1140
+
1141
+ The attractive and repulsive forces (arf) layout [1]
1142
+ improves the spring layout in three ways. First, it
1143
+ prevents congestion of highly connected nodes due to
1144
+ strong forcing between nodes. Second, it utilizes the
1145
+ layout space more effectively by preventing large gaps
1146
+ that spring layout tends to create. Lastly, the arf
1147
+ layout represents symmetries in the layout better than
1148
+ the default spring layout.
1149
+
1150
+ Parameters
1151
+ ----------
1152
+ G : nx.Graph or nx.DiGraph
1153
+ Networkx graph.
1154
+ pos : dict
1155
+ Initial position of the nodes. If set to None a
1156
+ random layout will be used.
1157
+ scaling : float
1158
+ Scales the radius of the circular layout space.
1159
+ a : float
1160
+ Strength of springs between connected nodes. Should be larger than 1. The greater a, the clearer the separation ofunconnected sub clusters.
1161
+ etol : float
1162
+ Gradient sum of spring forces must be larger than `etol` before successful termination.
1163
+ dt : float
1164
+ Time step for force differential equation simulations.
1165
+ max_iter : int
1166
+ Max iterations before termination of the algorithm.
1167
+ seed : int, RandomState instance or None optional (default=None)
1168
+ Set the random state for deterministic node layouts.
1169
+ If int, `seed` is the seed used by the random number generator,
1170
+ if numpy.random.RandomState instance, `seed` is the random
1171
+ number generator,
1172
+ if None, the random number generator is the RandomState instance used
1173
+ by numpy.random.
1174
+
1175
+ References
1176
+ .. [1] "Self-Organization Applied to Dynamic Network Layout", M. Geipel,
1177
+ International Journal of Modern Physics C, 2007, Vol 18, No 10, pp. 1537-1549.
1178
+ https://doi.org/10.1142/S0129183107011558 https://arxiv.org/abs/0704.1748
1179
+
1180
+ Returns
1181
+ -------
1182
+ pos : dict
1183
+ A dictionary of positions keyed by node.
1184
+
1185
+ Examples
1186
+ --------
1187
+ >>> G = nx.grid_graph((5, 5))
1188
+ >>> pos = nx.arf_layout(G)
1189
+
1190
+ """
1191
+ import warnings
1192
+
1193
+ import numpy as np
1194
+
1195
+ if a <= 1:
1196
+ msg = "The parameter a should be larger than 1"
1197
+ raise ValueError(msg)
1198
+
1199
+ pos_tmp = nx.random_layout(G, seed=seed)
1200
+ if pos is None:
1201
+ pos = pos_tmp
1202
+ else:
1203
+ for node in G.nodes():
1204
+ if node not in pos:
1205
+ pos[node] = pos_tmp[node].copy()
1206
+
1207
+ # Initialize spring constant matrix
1208
+ N = len(G)
1209
+ # No nodes no computation
1210
+ if N == 0:
1211
+ return pos
1212
+
1213
+ # init force of springs
1214
+ K = np.ones((N, N)) - np.eye(N)
1215
+ node_order = {node: i for i, node in enumerate(G)}
1216
+ for x, y in G.edges():
1217
+ if x != y:
1218
+ idx, jdx = (node_order[i] for i in (x, y))
1219
+ K[idx, jdx] = a
1220
+
1221
+ # vectorize values
1222
+ p = np.asarray(list(pos.values()))
1223
+
1224
+ # equation 10 in [1]
1225
+ rho = scaling * np.sqrt(N)
1226
+
1227
+ # looping variables
1228
+ error = etol + 1
1229
+ n_iter = 0
1230
+ while error > etol:
1231
+ diff = p[:, np.newaxis] - p[np.newaxis]
1232
+ A = np.linalg.norm(diff, axis=-1)[..., np.newaxis]
1233
+ # attraction_force - repulsions force
1234
+ # suppress nans due to division; caused by diagonal set to zero.
1235
+ # Does not affect the computation due to nansum
1236
+ with warnings.catch_warnings():
1237
+ warnings.simplefilter("ignore")
1238
+ change = K[..., np.newaxis] * diff - rho / A * diff
1239
+ change = np.nansum(change, axis=0)
1240
+ p += change * dt
1241
+
1242
+ error = np.linalg.norm(change, axis=-1).sum()
1243
+ if n_iter > max_iter:
1244
+ break
1245
+ n_iter += 1
1246
+ return dict(zip(G.nodes(), p))
1247
+
1248
+
1249
+ @np_random_state("seed")
1250
+ def forceatlas2_layout(
1251
+ G,
1252
+ pos=None,
1253
+ *,
1254
+ max_iter=100,
1255
+ jitter_tolerance=1.0,
1256
+ scaling_ratio=2.0,
1257
+ gravity=1.0,
1258
+ distributed_action=False,
1259
+ strong_gravity=False,
1260
+ node_mass=None,
1261
+ node_size=None,
1262
+ weight=None,
1263
+ dissuade_hubs=False,
1264
+ linlog=False,
1265
+ seed=None,
1266
+ dim=2,
1267
+ ):
1268
+ """Position nodes using the ForceAtlas2 force-directed layout algorithm.
1269
+
1270
+ This function applies the ForceAtlas2 layout algorithm [1]_ to a NetworkX graph,
1271
+ positioning the nodes in a way that visually represents the structure of the graph.
1272
+ The algorithm uses physical simulation to minimize the energy of the system,
1273
+ resulting in a more readable layout.
1274
+
1275
+ Parameters
1276
+ ----------
1277
+ G : nx.Graph
1278
+ A NetworkX graph to be laid out.
1279
+ pos : dict or None, optional
1280
+ Initial positions of the nodes. If None, random initial positions are used.
1281
+ max_iter : int (default: 100)
1282
+ Number of iterations for the layout optimization.
1283
+ jitter_tolerance : float (default: 1.0)
1284
+ Controls the tolerance for adjusting the speed of layout generation.
1285
+ scaling_ratio : float (default: 2.0)
1286
+ Determines the scaling of attraction and repulsion forces.
1287
+ distributed_attraction : bool (default: False)
1288
+ Distributes the attraction force evenly among nodes.
1289
+ strong_gravity : bool (default: False)
1290
+ Applies a strong gravitational pull towards the center.
1291
+ node_mass : dict or None, optional
1292
+ Maps nodes to their masses, influencing the attraction to other nodes.
1293
+ node_size : dict or None, optional
1294
+ Maps nodes to their sizes, preventing crowding by creating a halo effect.
1295
+ dissuade_hubs : bool (default: False)
1296
+ Prevents the clustering of hub nodes.
1297
+ linlog : bool (default: False)
1298
+ Uses logarithmic attraction instead of linear.
1299
+ seed : int, RandomState instance or None optional (default=None)
1300
+ Used only for the initial positions in the algorithm.
1301
+ Set the random state for deterministic node layouts.
1302
+ If int, `seed` is the seed used by the random number generator,
1303
+ if numpy.random.RandomState instance, `seed` is the random
1304
+ number generator,
1305
+ if None, the random number generator is the RandomState instance used
1306
+ by numpy.random.
1307
+ dim : int (default: 2)
1308
+ Sets the dimensions for the layout. Ignored if `pos` is provided.
1309
+
1310
+ Examples
1311
+ --------
1312
+ >>> import networkx as nx
1313
+ >>> G = nx.florentine_families_graph()
1314
+ >>> pos = nx.forceatlas2_layout(G)
1315
+ >>> nx.draw(G, pos=pos)
1316
+
1317
+ References
1318
+ ----------
1319
+ .. [1] Jacomy, M., Venturini, T., Heymann, S., & Bastian, M. (2014).
1320
+ ForceAtlas2, a continuous graph layout algorithm for handy network
1321
+ visualization designed for the Gephi software. PloS one, 9(6), e98679.
1322
+ https://doi.org/10.1371/journal.pone.0098679
1323
+ """
1324
+ import numpy as np
1325
+
1326
+ if len(G) == 0:
1327
+ return {}
1328
+ # parse optional pos positions
1329
+ if pos is None:
1330
+ pos = nx.random_layout(G, dim=dim, seed=seed)
1331
+ pos_arr = np.array(list(pos.values()))
1332
+ else:
1333
+ # set default node interval within the initial pos values
1334
+ pos_init = np.array(list(pos.values()))
1335
+ max_pos = pos_init.max(axis=0)
1336
+ min_pos = pos_init.min(axis=0)
1337
+ dim = max_pos.size
1338
+ pos_arr = min_pos + seed.rand(len(G), dim) * (max_pos - min_pos)
1339
+ for idx, node in enumerate(G):
1340
+ if node in pos:
1341
+ pos_arr[idx] = pos[node].copy()
1342
+
1343
+ mass = np.zeros(len(G))
1344
+ size = np.zeros(len(G))
1345
+
1346
+ # Only adjust for size when the users specifies size other than default (1)
1347
+ adjust_sizes = False
1348
+ if node_size is None:
1349
+ node_size = {}
1350
+ else:
1351
+ adjust_sizes = True
1352
+
1353
+ if node_mass is None:
1354
+ node_mass = {}
1355
+
1356
+ for idx, node in enumerate(G):
1357
+ mass[idx] = node_mass.get(node, G.degree(node) + 1)
1358
+ size[idx] = node_size.get(node, 1)
1359
+
1360
+ n = len(G)
1361
+ gravities = np.zeros((n, dim))
1362
+ attraction = np.zeros((n, dim))
1363
+ repulsion = np.zeros((n, dim))
1364
+ A = nx.to_numpy_array(G, weight=weight)
1365
+
1366
+ def estimate_factor(n, swing, traction, speed, speed_efficiency, jitter_tolerance):
1367
+ """Computes the scaling factor for the force in the ForceAtlas2 layout algorithm.
1368
+
1369
+ This helper function adjusts the speed and
1370
+ efficiency of the layout generation based on the
1371
+ current state of the system, such as the number of
1372
+ nodes, current swing, and traction forces.
1373
+
1374
+ Parameters
1375
+ ----------
1376
+ n : int
1377
+ Number of nodes in the graph.
1378
+ swing : float
1379
+ The current swing, representing the oscillation of the nodes.
1380
+ traction : float
1381
+ The current traction force, representing the attraction between nodes.
1382
+ speed : float
1383
+ The current speed of the layout generation.
1384
+ speed_efficiency : float
1385
+ The efficiency of the current speed, influencing how fast the layout converges.
1386
+ jitter_tolerance : float
1387
+ The tolerance for jitter, affecting how much speed adjustment is allowed.
1388
+
1389
+ Returns
1390
+ -------
1391
+ tuple
1392
+ A tuple containing the updated speed and speed efficiency.
1393
+
1394
+ Notes
1395
+ -----
1396
+ This function is a part of the ForceAtlas2 layout algorithm and is used to dynamically adjust the
1397
+ layout parameters to achieve an optimal and stable visualization.
1398
+
1399
+ """
1400
+ import numpy as np
1401
+
1402
+ # estimate jitter
1403
+ opt_jitter = 0.05 * np.sqrt(n)
1404
+ min_jitter = np.sqrt(opt_jitter)
1405
+ max_jitter = 10
1406
+ min_speed_efficiency = 0.05
1407
+
1408
+ other = min(max_jitter, opt_jitter * traction / n**2)
1409
+ jitter = jitter_tolerance * max(min_jitter, other)
1410
+
1411
+ if swing / traction > 2.0:
1412
+ if speed_efficiency > min_speed_efficiency:
1413
+ speed_efficiency *= 0.5
1414
+ jitter = max(jitter, jitter_tolerance)
1415
+ if swing == 0:
1416
+ target_speed = np.inf
1417
+ else:
1418
+ target_speed = jitter * speed_efficiency * traction / swing
1419
+
1420
+ if swing > jitter * traction:
1421
+ if speed_efficiency > min_speed_efficiency:
1422
+ speed_efficiency *= 0.7
1423
+ elif speed < 1000:
1424
+ speed_efficiency *= 1.3
1425
+
1426
+ max_rise = 0.5
1427
+ speed = speed + min(target_speed - speed, max_rise * speed)
1428
+ return speed, speed_efficiency
1429
+
1430
+ speed = 1
1431
+ speed_efficiency = 1
1432
+ swing = 1
1433
+ traction = 1
1434
+ for _ in range(max_iter):
1435
+ # compute pairwise difference
1436
+ diff = pos_arr[:, None] - pos_arr[None]
1437
+ # compute pairwise distance
1438
+ distance = np.linalg.norm(diff, axis=-1)
1439
+
1440
+ # linear attraction
1441
+ if linlog:
1442
+ attraction = -np.log(1 + distance) / distance
1443
+ np.fill_diagonal(attraction, 0)
1444
+ attraction = np.einsum("ij, ij -> ij", attraction, A)
1445
+ attraction = np.einsum("ijk, ij -> ik", diff, attraction)
1446
+
1447
+ else:
1448
+ attraction = -np.einsum("ijk, ij -> ik", diff, A)
1449
+
1450
+ if distributed_action:
1451
+ attraction /= mass[:, None]
1452
+
1453
+ # repulsion
1454
+ tmp = mass[:, None] @ mass[None]
1455
+ if adjust_sizes:
1456
+ distance += -size[:, None] - size[None]
1457
+
1458
+ d2 = distance**2
1459
+ # remove self-interaction
1460
+ np.fill_diagonal(tmp, 0)
1461
+ np.fill_diagonal(d2, 1)
1462
+ factor = (tmp / d2) * scaling_ratio
1463
+ repulsion = np.einsum("ijk, ij -> ik", diff, factor)
1464
+
1465
+ # gravity
1466
+ gravities = (
1467
+ -gravity
1468
+ * mass[:, None]
1469
+ * pos_arr
1470
+ / np.linalg.norm(pos_arr, axis=-1)[:, None]
1471
+ )
1472
+
1473
+ if strong_gravity:
1474
+ gravities *= np.linalg.norm(pos_arr, axis=-1)[:, None]
1475
+ # total forces
1476
+ update = attraction + repulsion + gravities
1477
+
1478
+ # compute total swing and traction
1479
+ swing += (mass * np.linalg.norm(pos_arr - update, axis=-1)).sum()
1480
+ traction += (0.5 * mass * np.linalg.norm(pos_arr + update, axis=-1)).sum()
1481
+
1482
+ speed, speed_efficiency = estimate_factor(
1483
+ n,
1484
+ swing,
1485
+ traction,
1486
+ speed,
1487
+ speed_efficiency,
1488
+ jitter_tolerance,
1489
+ )
1490
+
1491
+ # update pos
1492
+ if adjust_sizes:
1493
+ swinging = mass * np.linalg.norm(update, axis=-1)
1494
+ factor = 0.1 * speed / (1 + np.sqrt(speed * swinging))
1495
+ df = np.linalg.norm(update, axis=-1)
1496
+ factor = np.minimum(factor * df, 10.0 * np.ones(df.shape)) / df
1497
+ else:
1498
+ swinging = mass * np.linalg.norm(update, axis=-1)
1499
+ factor = speed / (1 + np.sqrt(speed * swinging))
1500
+
1501
+ pos_arr += update * factor[:, None]
1502
+ if abs((update * factor[:, None]).sum()) < 1e-10:
1503
+ break
1504
+
1505
+ return dict(zip(G, pos_arr))
1506
+
1507
+
1508
+ def rescale_layout(pos, scale=1):
1509
+ """Returns scaled position array to (-scale, scale) in all axes.
1510
+
1511
+ The function acts on NumPy arrays which hold position information.
1512
+ Each position is one row of the array. The dimension of the space
1513
+ equals the number of columns. Each coordinate in one column.
1514
+
1515
+ To rescale, the mean (center) is subtracted from each axis separately.
1516
+ Then all values are scaled so that the largest magnitude value
1517
+ from all axes equals `scale` (thus, the aspect ratio is preserved).
1518
+ The resulting NumPy Array is returned (order of rows unchanged).
1519
+
1520
+ Parameters
1521
+ ----------
1522
+ pos : numpy array
1523
+ positions to be scaled. Each row is a position.
1524
+
1525
+ scale : number (default: 1)
1526
+ The size of the resulting extent in all directions.
1527
+
1528
+ Returns
1529
+ -------
1530
+ pos : numpy array
1531
+ scaled positions. Each row is a position.
1532
+
1533
+ See Also
1534
+ --------
1535
+ rescale_layout_dict
1536
+ """
1537
+ import numpy as np
1538
+
1539
+ # Find max length over all dimensions
1540
+ pos -= pos.mean(axis=0)
1541
+ lim = np.abs(pos).max() # max coordinate for all axes
1542
+ # rescale to (-scale, scale) in all directions, preserves aspect
1543
+ if lim > 0:
1544
+ pos *= scale / lim
1545
+ return pos
1546
+
1547
+
1548
+ def rescale_layout_dict(pos, scale=1):
1549
+ """Return a dictionary of scaled positions keyed by node
1550
+
1551
+ Parameters
1552
+ ----------
1553
+ pos : A dictionary of positions keyed by node
1554
+
1555
+ scale : number (default: 1)
1556
+ The size of the resulting extent in all directions.
1557
+
1558
+ Returns
1559
+ -------
1560
+ pos : A dictionary of positions keyed by node
1561
+
1562
+ Examples
1563
+ --------
1564
+ >>> import numpy as np
1565
+ >>> pos = {0: np.array((0, 0)), 1: np.array((1, 1)), 2: np.array((0.5, 0.5))}
1566
+ >>> nx.rescale_layout_dict(pos)
1567
+ {0: array([-1., -1.]), 1: array([1., 1.]), 2: array([0., 0.])}
1568
+
1569
+ >>> pos = {0: np.array((0, 0)), 1: np.array((-1, 1)), 2: np.array((-0.5, 0.5))}
1570
+ >>> nx.rescale_layout_dict(pos, scale=2)
1571
+ {0: array([ 2., -2.]), 1: array([-2., 2.]), 2: array([0., 0.])}
1572
+
1573
+ See Also
1574
+ --------
1575
+ rescale_layout
1576
+ """
1577
+ import numpy as np
1578
+
1579
+ if not pos: # empty_graph
1580
+ return {}
1581
+ pos_v = np.array(list(pos.values()))
1582
+ pos_v = rescale_layout(pos_v, scale=scale)
1583
+ return dict(zip(pos, pos_v))
1584
+
1585
+
1586
+ def bfs_layout(G, start, *, align="vertical", scale=1, center=None):
1587
+ """Position nodes according to breadth-first search algorithm.
1588
+
1589
+ Parameters
1590
+ ----------
1591
+ G : NetworkX graph
1592
+ A position will be assigned to every node in G.
1593
+
1594
+ start : node in `G`
1595
+ Starting node for bfs
1596
+
1597
+ center : array-like or None
1598
+ Coordinate pair around which to center the layout.
1599
+
1600
+ Returns
1601
+ -------
1602
+ pos : dict
1603
+ A dictionary of positions keyed by node.
1604
+
1605
+ Examples
1606
+ --------
1607
+ >>> G = nx.path_graph(4)
1608
+ >>> pos = nx.bfs_layout(G, 0)
1609
+
1610
+ Notes
1611
+ -----
1612
+ This algorithm currently only works in two dimensions and does not
1613
+ try to minimize edge crossings.
1614
+
1615
+ """
1616
+ G, center = _process_params(G, center, 2)
1617
+
1618
+ # Compute layers with BFS
1619
+ layers = dict(enumerate(nx.bfs_layers(G, start)))
1620
+
1621
+ if len(G) != sum(len(nodes) for nodes in layers.values()):
1622
+ raise nx.NetworkXError(
1623
+ "bfs_layout didn't include all nodes. Perhaps use input graph:\n"
1624
+ " G.subgraph(nx.node_connected_component(G, start))"
1625
+ )
1626
+
1627
+ # Compute node positions with multipartite_layout
1628
+ return multipartite_layout(
1629
+ G, subset_key=layers, align=align, scale=scale, center=center
1630
+ )
falcon/lib/python3.10/site-packages/networkx/drawing/nx_agraph.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ***************
3
+ Graphviz AGraph
4
+ ***************
5
+
6
+ Interface to pygraphviz AGraph class.
7
+
8
+ Examples
9
+ --------
10
+ >>> G = nx.complete_graph(5)
11
+ >>> A = nx.nx_agraph.to_agraph(G)
12
+ >>> H = nx.nx_agraph.from_agraph(A)
13
+
14
+ See Also
15
+ --------
16
+ - Pygraphviz: http://pygraphviz.github.io/
17
+ - Graphviz: https://www.graphviz.org
18
+ - DOT Language: http://www.graphviz.org/doc/info/lang.html
19
+ """
20
+
21
+ import os
22
+ import tempfile
23
+
24
+ import networkx as nx
25
+
26
+ __all__ = [
27
+ "from_agraph",
28
+ "to_agraph",
29
+ "write_dot",
30
+ "read_dot",
31
+ "graphviz_layout",
32
+ "pygraphviz_layout",
33
+ "view_pygraphviz",
34
+ ]
35
+
36
+
37
+ @nx._dispatchable(graphs=None, returns_graph=True)
38
+ def from_agraph(A, create_using=None):
39
+ """Returns a NetworkX Graph or DiGraph from a PyGraphviz graph.
40
+
41
+ Parameters
42
+ ----------
43
+ A : PyGraphviz AGraph
44
+ A graph created with PyGraphviz
45
+
46
+ create_using : NetworkX graph constructor, optional (default=None)
47
+ Graph type to create. If graph instance, then cleared before populated.
48
+ If `None`, then the appropriate Graph type is inferred from `A`.
49
+
50
+ Examples
51
+ --------
52
+ >>> K5 = nx.complete_graph(5)
53
+ >>> A = nx.nx_agraph.to_agraph(K5)
54
+ >>> G = nx.nx_agraph.from_agraph(A)
55
+
56
+ Notes
57
+ -----
58
+ The Graph G will have a dictionary G.graph_attr containing
59
+ the default graphviz attributes for graphs, nodes and edges.
60
+
61
+ Default node attributes will be in the dictionary G.node_attr
62
+ which is keyed by node.
63
+
64
+ Edge attributes will be returned as edge data in G. With
65
+ edge_attr=False the edge data will be the Graphviz edge weight
66
+ attribute or the value 1 if no edge weight attribute is found.
67
+
68
+ """
69
+ if create_using is None:
70
+ if A.is_directed():
71
+ if A.is_strict():
72
+ create_using = nx.DiGraph
73
+ else:
74
+ create_using = nx.MultiDiGraph
75
+ else:
76
+ if A.is_strict():
77
+ create_using = nx.Graph
78
+ else:
79
+ create_using = nx.MultiGraph
80
+
81
+ # assign defaults
82
+ N = nx.empty_graph(0, create_using)
83
+ if A.name is not None:
84
+ N.name = A.name
85
+
86
+ # add graph attributes
87
+ N.graph.update(A.graph_attr)
88
+
89
+ # add nodes, attributes to N.node_attr
90
+ for n in A.nodes():
91
+ str_attr = {str(k): v for k, v in n.attr.items()}
92
+ N.add_node(str(n), **str_attr)
93
+
94
+ # add edges, assign edge data as dictionary of attributes
95
+ for e in A.edges():
96
+ u, v = str(e[0]), str(e[1])
97
+ attr = dict(e.attr)
98
+ str_attr = {str(k): v for k, v in attr.items()}
99
+ if not N.is_multigraph():
100
+ if e.name is not None:
101
+ str_attr["key"] = e.name
102
+ N.add_edge(u, v, **str_attr)
103
+ else:
104
+ N.add_edge(u, v, key=e.name, **str_attr)
105
+
106
+ # add default attributes for graph, nodes, and edges
107
+ # hang them on N.graph_attr
108
+ N.graph["graph"] = dict(A.graph_attr)
109
+ N.graph["node"] = dict(A.node_attr)
110
+ N.graph["edge"] = dict(A.edge_attr)
111
+ return N
112
+
113
+
114
+ def to_agraph(N):
115
+ """Returns a pygraphviz graph from a NetworkX graph N.
116
+
117
+ Parameters
118
+ ----------
119
+ N : NetworkX graph
120
+ A graph created with NetworkX
121
+
122
+ Examples
123
+ --------
124
+ >>> K5 = nx.complete_graph(5)
125
+ >>> A = nx.nx_agraph.to_agraph(K5)
126
+
127
+ Notes
128
+ -----
129
+ If N has an dict N.graph_attr an attempt will be made first
130
+ to copy properties attached to the graph (see from_agraph)
131
+ and then updated with the calling arguments if any.
132
+
133
+ """
134
+ try:
135
+ import pygraphviz
136
+ except ImportError as err:
137
+ raise ImportError("requires pygraphviz http://pygraphviz.github.io/") from err
138
+ directed = N.is_directed()
139
+ strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
140
+
141
+ A = pygraphviz.AGraph(name=N.name, strict=strict, directed=directed)
142
+
143
+ # default graph attributes
144
+ A.graph_attr.update(N.graph.get("graph", {}))
145
+ A.node_attr.update(N.graph.get("node", {}))
146
+ A.edge_attr.update(N.graph.get("edge", {}))
147
+
148
+ A.graph_attr.update(
149
+ (k, v) for k, v in N.graph.items() if k not in ("graph", "node", "edge")
150
+ )
151
+
152
+ # add nodes
153
+ for n, nodedata in N.nodes(data=True):
154
+ A.add_node(n)
155
+ # Add node data
156
+ a = A.get_node(n)
157
+ for key, val in nodedata.items():
158
+ if key == "pos":
159
+ a.attr["pos"] = f"{val[0]},{val[1]}!"
160
+ else:
161
+ a.attr[key] = str(val)
162
+
163
+ # loop over edges
164
+ if N.is_multigraph():
165
+ for u, v, key, edgedata in N.edges(data=True, keys=True):
166
+ str_edgedata = {k: str(v) for k, v in edgedata.items() if k != "key"}
167
+ A.add_edge(u, v, key=str(key))
168
+ # Add edge data
169
+ a = A.get_edge(u, v)
170
+ a.attr.update(str_edgedata)
171
+
172
+ else:
173
+ for u, v, edgedata in N.edges(data=True):
174
+ str_edgedata = {k: str(v) for k, v in edgedata.items()}
175
+ A.add_edge(u, v)
176
+ # Add edge data
177
+ a = A.get_edge(u, v)
178
+ a.attr.update(str_edgedata)
179
+
180
+ return A
181
+
182
+
183
+ def write_dot(G, path):
184
+ """Write NetworkX graph G to Graphviz dot format on path.
185
+
186
+ Parameters
187
+ ----------
188
+ G : graph
189
+ A networkx graph
190
+ path : filename
191
+ Filename or file handle to write
192
+
193
+ Notes
194
+ -----
195
+ To use a specific graph layout, call ``A.layout`` prior to `write_dot`.
196
+ Note that some graphviz layouts are not guaranteed to be deterministic,
197
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
198
+ """
199
+ A = to_agraph(G)
200
+ A.write(path)
201
+ A.clear()
202
+ return
203
+
204
+
205
+ @nx._dispatchable(name="agraph_read_dot", graphs=None, returns_graph=True)
206
+ def read_dot(path):
207
+ """Returns a NetworkX graph from a dot file on path.
208
+
209
+ Parameters
210
+ ----------
211
+ path : file or string
212
+ File name or file handle to read.
213
+ """
214
+ try:
215
+ import pygraphviz
216
+ except ImportError as err:
217
+ raise ImportError(
218
+ "read_dot() requires pygraphviz http://pygraphviz.github.io/"
219
+ ) from err
220
+ A = pygraphviz.AGraph(file=path)
221
+ gr = from_agraph(A)
222
+ A.clear()
223
+ return gr
224
+
225
+
226
+ def graphviz_layout(G, prog="neato", root=None, args=""):
227
+ """Create node positions for G using Graphviz.
228
+
229
+ Parameters
230
+ ----------
231
+ G : NetworkX graph
232
+ A graph created with NetworkX
233
+ prog : string
234
+ Name of Graphviz layout program
235
+ root : string, optional
236
+ Root node for twopi layout
237
+ args : string, optional
238
+ Extra arguments to Graphviz layout program
239
+
240
+ Returns
241
+ -------
242
+ Dictionary of x, y, positions keyed by node.
243
+
244
+ Examples
245
+ --------
246
+ >>> G = nx.petersen_graph()
247
+ >>> pos = nx.nx_agraph.graphviz_layout(G)
248
+ >>> pos = nx.nx_agraph.graphviz_layout(G, prog="dot")
249
+
250
+ Notes
251
+ -----
252
+ This is a wrapper for pygraphviz_layout.
253
+
254
+ Note that some graphviz layouts are not guaranteed to be deterministic,
255
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
256
+ """
257
+ return pygraphviz_layout(G, prog=prog, root=root, args=args)
258
+
259
+
260
+ def pygraphviz_layout(G, prog="neato", root=None, args=""):
261
+ """Create node positions for G using Graphviz.
262
+
263
+ Parameters
264
+ ----------
265
+ G : NetworkX graph
266
+ A graph created with NetworkX
267
+ prog : string
268
+ Name of Graphviz layout program
269
+ root : string, optional
270
+ Root node for twopi layout
271
+ args : string, optional
272
+ Extra arguments to Graphviz layout program
273
+
274
+ Returns
275
+ -------
276
+ node_pos : dict
277
+ Dictionary of x, y, positions keyed by node.
278
+
279
+ Examples
280
+ --------
281
+ >>> G = nx.petersen_graph()
282
+ >>> pos = nx.nx_agraph.graphviz_layout(G)
283
+ >>> pos = nx.nx_agraph.graphviz_layout(G, prog="dot")
284
+
285
+ Notes
286
+ -----
287
+ If you use complex node objects, they may have the same string
288
+ representation and GraphViz could treat them as the same node.
289
+ The layout may assign both nodes a single location. See Issue #1568
290
+ If this occurs in your case, consider relabeling the nodes just
291
+ for the layout computation using something similar to::
292
+
293
+ >>> H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
294
+ >>> H_layout = nx.nx_agraph.pygraphviz_layout(G, prog="dot")
295
+ >>> G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
296
+
297
+ Note that some graphviz layouts are not guaranteed to be deterministic,
298
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
299
+ """
300
+ try:
301
+ import pygraphviz
302
+ except ImportError as err:
303
+ raise ImportError("requires pygraphviz http://pygraphviz.github.io/") from err
304
+ if root is not None:
305
+ args += f"-Groot={root}"
306
+ A = to_agraph(G)
307
+ A.layout(prog=prog, args=args)
308
+ node_pos = {}
309
+ for n in G:
310
+ node = pygraphviz.Node(A, n)
311
+ try:
312
+ xs = node.attr["pos"].split(",")
313
+ node_pos[n] = tuple(float(x) for x in xs)
314
+ except:
315
+ print("no position for node", n)
316
+ node_pos[n] = (0.0, 0.0)
317
+ return node_pos
318
+
319
+
320
+ @nx.utils.open_file(5, "w+b")
321
+ def view_pygraphviz(
322
+ G, edgelabel=None, prog="dot", args="", suffix="", path=None, show=True
323
+ ):
324
+ """Views the graph G using the specified layout algorithm.
325
+
326
+ Parameters
327
+ ----------
328
+ G : NetworkX graph
329
+ The machine to draw.
330
+ edgelabel : str, callable, None
331
+ If a string, then it specifies the edge attribute to be displayed
332
+ on the edge labels. If a callable, then it is called for each
333
+ edge and it should return the string to be displayed on the edges.
334
+ The function signature of `edgelabel` should be edgelabel(data),
335
+ where `data` is the edge attribute dictionary.
336
+ prog : string
337
+ Name of Graphviz layout program.
338
+ args : str
339
+ Additional arguments to pass to the Graphviz layout program.
340
+ suffix : str
341
+ If `filename` is None, we save to a temporary file. The value of
342
+ `suffix` will appear at the tail end of the temporary filename.
343
+ path : str, None
344
+ The filename used to save the image. If None, save to a temporary
345
+ file. File formats are the same as those from pygraphviz.agraph.draw.
346
+ show : bool, default = True
347
+ Whether to display the graph with :mod:`PIL.Image.show`,
348
+ default is `True`. If `False`, the rendered graph is still available
349
+ at `path`.
350
+
351
+ Returns
352
+ -------
353
+ path : str
354
+ The filename of the generated image.
355
+ A : PyGraphviz graph
356
+ The PyGraphviz graph instance used to generate the image.
357
+
358
+ Notes
359
+ -----
360
+ If this function is called in succession too quickly, sometimes the
361
+ image is not displayed. So you might consider time.sleep(.5) between
362
+ calls if you experience problems.
363
+
364
+ Note that some graphviz layouts are not guaranteed to be deterministic,
365
+ see https://gitlab.com/graphviz/graphviz/-/issues/1767 for more info.
366
+
367
+ """
368
+ if not len(G):
369
+ raise nx.NetworkXException("An empty graph cannot be drawn.")
370
+
371
+ # If we are providing default values for graphviz, these must be set
372
+ # before any nodes or edges are added to the PyGraphviz graph object.
373
+ # The reason for this is that default values only affect incoming objects.
374
+ # If you change the default values after the objects have been added,
375
+ # then they inherit no value and are set only if explicitly set.
376
+
377
+ # to_agraph() uses these values.
378
+ attrs = ["edge", "node", "graph"]
379
+ for attr in attrs:
380
+ if attr not in G.graph:
381
+ G.graph[attr] = {}
382
+
383
+ # These are the default values.
384
+ edge_attrs = {"fontsize": "10"}
385
+ node_attrs = {
386
+ "style": "filled",
387
+ "fillcolor": "#0000FF40",
388
+ "height": "0.75",
389
+ "width": "0.75",
390
+ "shape": "circle",
391
+ }
392
+ graph_attrs = {}
393
+
394
+ def update_attrs(which, attrs):
395
+ # Update graph attributes. Return list of those which were added.
396
+ added = []
397
+ for k, v in attrs.items():
398
+ if k not in G.graph[which]:
399
+ G.graph[which][k] = v
400
+ added.append(k)
401
+
402
+ def clean_attrs(which, added):
403
+ # Remove added attributes
404
+ for attr in added:
405
+ del G.graph[which][attr]
406
+ if not G.graph[which]:
407
+ del G.graph[which]
408
+
409
+ # Update all default values
410
+ update_attrs("edge", edge_attrs)
411
+ update_attrs("node", node_attrs)
412
+ update_attrs("graph", graph_attrs)
413
+
414
+ # Convert to agraph, so we inherit default values
415
+ A = to_agraph(G)
416
+
417
+ # Remove the default values we added to the original graph.
418
+ clean_attrs("edge", edge_attrs)
419
+ clean_attrs("node", node_attrs)
420
+ clean_attrs("graph", graph_attrs)
421
+
422
+ # If the user passed in an edgelabel, we update the labels for all edges.
423
+ if edgelabel is not None:
424
+ if not callable(edgelabel):
425
+
426
+ def func(data):
427
+ return "".join([" ", str(data[edgelabel]), " "])
428
+
429
+ else:
430
+ func = edgelabel
431
+
432
+ # update all the edge labels
433
+ if G.is_multigraph():
434
+ for u, v, key, data in G.edges(keys=True, data=True):
435
+ # PyGraphviz doesn't convert the key to a string. See #339
436
+ edge = A.get_edge(u, v, str(key))
437
+ edge.attr["label"] = str(func(data))
438
+ else:
439
+ for u, v, data in G.edges(data=True):
440
+ edge = A.get_edge(u, v)
441
+ edge.attr["label"] = str(func(data))
442
+
443
+ if path is None:
444
+ ext = "png"
445
+ if suffix:
446
+ suffix = f"_{suffix}.{ext}"
447
+ else:
448
+ suffix = f".{ext}"
449
+ path = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
450
+ else:
451
+ # Assume the decorator worked and it is a file-object.
452
+ pass
453
+
454
+ # Write graph to file
455
+ A.draw(path=path, format=None, prog=prog, args=args)
456
+ path.close()
457
+
458
+ # Show graph in a new window (depends on platform configuration)
459
+ if show:
460
+ from PIL import Image
461
+
462
+ Image.open(path.name).show()
463
+
464
+ return path.name, A
falcon/lib/python3.10/site-packages/networkx/drawing/nx_latex.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ *****
3
+ LaTeX
4
+ *****
5
+
6
+ Export NetworkX graphs in LaTeX format using the TikZ library within TeX/LaTeX.
7
+ Usually, you will want the drawing to appear in a figure environment so
8
+ you use ``to_latex(G, caption="A caption")``. If you want the raw
9
+ drawing commands without a figure environment use :func:`to_latex_raw`.
10
+ And if you want to write to a file instead of just returning the latex
11
+ code as a string, use ``write_latex(G, "filename.tex", caption="A caption")``.
12
+
13
+ To construct a figure with subfigures for each graph to be shown, provide
14
+ ``to_latex`` or ``write_latex`` a list of graphs, a list of subcaptions,
15
+ and a number of rows of subfigures inside the figure.
16
+
17
+ To be able to refer to the figures or subfigures in latex using ``\\ref``,
18
+ the keyword ``latex_label`` is available for figures and `sub_labels` for
19
+ a list of labels, one for each subfigure.
20
+
21
+ We intend to eventually provide an interface to the TikZ Graph
22
+ features which include e.g. layout algorithms.
23
+
24
+ Let us know via github what you'd like to see available, or better yet
25
+ give us some code to do it, or even better make a github pull request
26
+ to add the feature.
27
+
28
+ The TikZ approach
29
+ =================
30
+ Drawing options can be stored on the graph as node/edge attributes, or
31
+ can be provided as dicts keyed by node/edge to a string of the options
32
+ for that node/edge. Similarly a label can be shown for each node/edge
33
+ by specifying the labels as graph node/edge attributes or by providing
34
+ a dict keyed by node/edge to the text to be written for that node/edge.
35
+
36
+ Options for the tikzpicture environment (e.g. "[scale=2]") can be provided
37
+ via a keyword argument. Similarly default node and edge options can be
38
+ provided through keywords arguments. The default node options are applied
39
+ to the single TikZ "path" that draws all nodes (and no edges). The default edge
40
+ options are applied to a TikZ "scope" which contains a path for each edge.
41
+
42
+ Examples
43
+ ========
44
+ >>> G = nx.path_graph(3)
45
+ >>> nx.write_latex(G, "just_my_figure.tex", as_document=True)
46
+ >>> nx.write_latex(G, "my_figure.tex", caption="A path graph", latex_label="fig1")
47
+ >>> latex_code = nx.to_latex(G) # a string rather than a file
48
+
49
+ You can change many features of the nodes and edges.
50
+
51
+ >>> G = nx.path_graph(4, create_using=nx.DiGraph)
52
+ >>> pos = {n: (n, n) for n in G} # nodes set on a line
53
+
54
+ >>> G.nodes[0]["style"] = "blue"
55
+ >>> G.nodes[2]["style"] = "line width=3,draw"
56
+ >>> G.nodes[3]["label"] = "Stop"
57
+ >>> G.edges[(0, 1)]["label"] = "1st Step"
58
+ >>> G.edges[(0, 1)]["label_opts"] = "near start"
59
+ >>> G.edges[(1, 2)]["style"] = "line width=3"
60
+ >>> G.edges[(1, 2)]["label"] = "2nd Step"
61
+ >>> G.edges[(2, 3)]["style"] = "green"
62
+ >>> G.edges[(2, 3)]["label"] = "3rd Step"
63
+ >>> G.edges[(2, 3)]["label_opts"] = "near end"
64
+
65
+ >>> nx.write_latex(G, "latex_graph.tex", pos=pos, as_document=True)
66
+
67
+ Then compile the LaTeX using something like ``pdflatex latex_graph.tex``
68
+ and view the pdf file created: ``latex_graph.pdf``.
69
+
70
+ If you want **subfigures** each containing one graph, you can input a list of graphs.
71
+
72
+ >>> H1 = nx.path_graph(4)
73
+ >>> H2 = nx.complete_graph(4)
74
+ >>> H3 = nx.path_graph(8)
75
+ >>> H4 = nx.complete_graph(8)
76
+ >>> graphs = [H1, H2, H3, H4]
77
+ >>> caps = ["Path 4", "Complete graph 4", "Path 8", "Complete graph 8"]
78
+ >>> lbls = ["fig2a", "fig2b", "fig2c", "fig2d"]
79
+ >>> nx.write_latex(graphs, "subfigs.tex", n_rows=2, sub_captions=caps, sub_labels=lbls)
80
+ >>> latex_code = nx.to_latex(graphs, n_rows=2, sub_captions=caps, sub_labels=lbls)
81
+
82
+ >>> node_color = {0: "red", 1: "orange", 2: "blue", 3: "gray!90"}
83
+ >>> edge_width = {e: "line width=1.5" for e in H3.edges}
84
+ >>> pos = nx.circular_layout(H3)
85
+ >>> latex_code = nx.to_latex(H3, pos, node_options=node_color, edge_options=edge_width)
86
+ >>> print(latex_code)
87
+ \documentclass{report}
88
+ \usepackage{tikz}
89
+ \usepackage{subcaption}
90
+ <BLANKLINE>
91
+ \begin{document}
92
+ \begin{figure}
93
+ \begin{tikzpicture}
94
+ \draw
95
+ (1.0, 0.0) node[red] (0){0}
96
+ (0.707, 0.707) node[orange] (1){1}
97
+ (-0.0, 1.0) node[blue] (2){2}
98
+ (-0.707, 0.707) node[gray!90] (3){3}
99
+ (-1.0, -0.0) node (4){4}
100
+ (-0.707, -0.707) node (5){5}
101
+ (0.0, -1.0) node (6){6}
102
+ (0.707, -0.707) node (7){7};
103
+ \begin{scope}[-]
104
+ \draw[line width=1.5] (0) to (1);
105
+ \draw[line width=1.5] (1) to (2);
106
+ \draw[line width=1.5] (2) to (3);
107
+ \draw[line width=1.5] (3) to (4);
108
+ \draw[line width=1.5] (4) to (5);
109
+ \draw[line width=1.5] (5) to (6);
110
+ \draw[line width=1.5] (6) to (7);
111
+ \end{scope}
112
+ \end{tikzpicture}
113
+ \end{figure}
114
+ \end{document}
115
+
116
+ Notes
117
+ -----
118
+ If you want to change the preamble/postamble of the figure/document/subfigure
119
+ environment, use the keyword arguments: `figure_wrapper`, `document_wrapper`,
120
+ `subfigure_wrapper`. The default values are stored in private variables
121
+ e.g. ``nx.nx_layout._DOCUMENT_WRAPPER``
122
+
123
+ References
124
+ ----------
125
+ TikZ: https://tikz.dev/
126
+
127
+ TikZ options details: https://tikz.dev/tikz-actions
128
+ """
129
+
130
+ import numbers
131
+ import os
132
+
133
+ import networkx as nx
134
+
135
+ __all__ = [
136
+ "to_latex_raw",
137
+ "to_latex",
138
+ "write_latex",
139
+ ]
140
+
141
+
142
+ @nx.utils.not_implemented_for("multigraph")
143
+ def to_latex_raw(
144
+ G,
145
+ pos="pos",
146
+ tikz_options="",
147
+ default_node_options="",
148
+ node_options="node_options",
149
+ node_label="label",
150
+ default_edge_options="",
151
+ edge_options="edge_options",
152
+ edge_label="label",
153
+ edge_label_options="edge_label_options",
154
+ ):
155
+ """Return a string of the LaTeX/TikZ code to draw `G`
156
+
157
+ This function produces just the code for the tikzpicture
158
+ without any enclosing environment.
159
+
160
+ Parameters
161
+ ==========
162
+ G : NetworkX graph
163
+ The NetworkX graph to be drawn
164
+ pos : string or dict (default "pos")
165
+ The name of the node attribute on `G` that holds the position of each node.
166
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
167
+ They can also be strings to denote positions in TikZ style, such as (x, y)
168
+ or (angle:radius).
169
+ If a dict, it should be keyed by node to a position.
170
+ If an empty dict, a circular layout is computed by TikZ.
171
+ tikz_options : string
172
+ The tikzpicture options description defining the options for the picture.
173
+ Often large scale options like `[scale=2]`.
174
+ default_node_options : string
175
+ The draw options for a path of nodes. Individual node options override these.
176
+ node_options : string or dict
177
+ The name of the node attribute on `G` that holds the options for each node.
178
+ Or a dict keyed by node to a string holding the options for that node.
179
+ node_label : string or dict
180
+ The name of the node attribute on `G` that holds the node label (text)
181
+ displayed for each node. If the attribute is "" or not present, the node
182
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
183
+ Or a dict keyed by node to a string holding the label for that node.
184
+ default_edge_options : string
185
+ The options for the scope drawing all edges. The default is "[-]" for
186
+ undirected graphs and "[->]" for directed graphs.
187
+ edge_options : string or dict
188
+ The name of the edge attribute on `G` that holds the options for each edge.
189
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
190
+ "loop," is added to the options for the self-loop edge. Hence you can
191
+ use "[loop above]" explicitly, but the default is "[loop]".
192
+ Or a dict keyed by edge to a string holding the options for that edge.
193
+ edge_label : string or dict
194
+ The name of the edge attribute on `G` that holds the edge label (text)
195
+ displayed for each edge. If the attribute is "" or not present, no edge
196
+ label is drawn.
197
+ Or a dict keyed by edge to a string holding the label for that edge.
198
+ edge_label_options : string or dict
199
+ The name of the edge attribute on `G` that holds the label options for
200
+ each edge. For example, "[sloped,above,blue]". The default is no options.
201
+ Or a dict keyed by edge to a string holding the label options for that edge.
202
+
203
+ Returns
204
+ =======
205
+ latex_code : string
206
+ The text string which draws the desired graph(s) when compiled by LaTeX.
207
+
208
+ See Also
209
+ ========
210
+ to_latex
211
+ write_latex
212
+ """
213
+ i4 = "\n "
214
+ i8 = "\n "
215
+
216
+ # set up position dict
217
+ # TODO allow pos to be None and use a nice TikZ default
218
+ if not isinstance(pos, dict):
219
+ pos = nx.get_node_attributes(G, pos)
220
+ if not pos:
221
+ # circular layout with radius 2
222
+ pos = {n: f"({round(360.0 * i / len(G), 3)}:2)" for i, n in enumerate(G)}
223
+ for node in G:
224
+ if node not in pos:
225
+ raise nx.NetworkXError(f"node {node} has no specified pos {pos}")
226
+ posnode = pos[node]
227
+ if not isinstance(posnode, str):
228
+ try:
229
+ posx, posy = posnode
230
+ pos[node] = f"({round(posx, 3)}, {round(posy, 3)})"
231
+ except (TypeError, ValueError):
232
+ msg = f"position pos[{node}] is not 2-tuple or a string: {posnode}"
233
+ raise nx.NetworkXError(msg)
234
+
235
+ # set up all the dicts
236
+ if not isinstance(node_options, dict):
237
+ node_options = nx.get_node_attributes(G, node_options)
238
+ if not isinstance(node_label, dict):
239
+ node_label = nx.get_node_attributes(G, node_label)
240
+ if not isinstance(edge_options, dict):
241
+ edge_options = nx.get_edge_attributes(G, edge_options)
242
+ if not isinstance(edge_label, dict):
243
+ edge_label = nx.get_edge_attributes(G, edge_label)
244
+ if not isinstance(edge_label_options, dict):
245
+ edge_label_options = nx.get_edge_attributes(G, edge_label_options)
246
+
247
+ # process default options (add brackets or not)
248
+ topts = "" if tikz_options == "" else f"[{tikz_options.strip('[]')}]"
249
+ defn = "" if default_node_options == "" else f"[{default_node_options.strip('[]')}]"
250
+ linestyle = f"{'->' if G.is_directed() else '-'}"
251
+ if default_edge_options == "":
252
+ defe = "[" + linestyle + "]"
253
+ elif "-" in default_edge_options:
254
+ defe = default_edge_options
255
+ else:
256
+ defe = f"[{linestyle},{default_edge_options.strip('[]')}]"
257
+
258
+ # Construct the string line by line
259
+ result = " \\begin{tikzpicture}" + topts
260
+ result += i4 + " \\draw" + defn
261
+ # load the nodes
262
+ for n in G:
263
+ # node options goes inside square brackets
264
+ nopts = f"[{node_options[n].strip('[]')}]" if n in node_options else ""
265
+ # node text goes inside curly brackets {}
266
+ ntext = f"{{{node_label[n]}}}" if n in node_label else f"{{{n}}}"
267
+
268
+ result += i8 + f"{pos[n]} node{nopts} ({n}){ntext}"
269
+ result += ";\n"
270
+
271
+ # load the edges
272
+ result += " \\begin{scope}" + defe
273
+ for edge in G.edges:
274
+ u, v = edge[:2]
275
+ e_opts = f"{edge_options[edge]}".strip("[]") if edge in edge_options else ""
276
+ # add loop options for selfloops if not present
277
+ if u == v and "loop" not in e_opts:
278
+ e_opts = "loop," + e_opts
279
+ e_opts = f"[{e_opts}]" if e_opts != "" else ""
280
+ # TODO -- handle bending of multiedges
281
+
282
+ els = edge_label_options[edge] if edge in edge_label_options else ""
283
+ # edge label options goes inside square brackets []
284
+ els = f"[{els.strip('[]')}]"
285
+ # edge text is drawn using the TikZ node command inside curly brackets {}
286
+ e_label = f" node{els} {{{edge_label[edge]}}}" if edge in edge_label else ""
287
+
288
+ result += i8 + f"\\draw{e_opts} ({u}) to{e_label} ({v});"
289
+
290
+ result += "\n \\end{scope}\n \\end{tikzpicture}\n"
291
+ return result
292
+
293
+
294
+ _DOC_WRAPPER_TIKZ = r"""\documentclass{{report}}
295
+ \usepackage{{tikz}}
296
+ \usepackage{{subcaption}}
297
+
298
+ \begin{{document}}
299
+ {content}
300
+ \end{{document}}"""
301
+
302
+
303
+ _FIG_WRAPPER = r"""\begin{{figure}}
304
+ {content}{caption}{label}
305
+ \end{{figure}}"""
306
+
307
+
308
+ _SUBFIG_WRAPPER = r""" \begin{{subfigure}}{{{size}\textwidth}}
309
+ {content}{caption}{label}
310
+ \end{{subfigure}}"""
311
+
312
+
313
+ def to_latex(
314
+ Gbunch,
315
+ pos="pos",
316
+ tikz_options="",
317
+ default_node_options="",
318
+ node_options="node_options",
319
+ node_label="node_label",
320
+ default_edge_options="",
321
+ edge_options="edge_options",
322
+ edge_label="edge_label",
323
+ edge_label_options="edge_label_options",
324
+ caption="",
325
+ latex_label="",
326
+ sub_captions=None,
327
+ sub_labels=None,
328
+ n_rows=1,
329
+ as_document=True,
330
+ document_wrapper=_DOC_WRAPPER_TIKZ,
331
+ figure_wrapper=_FIG_WRAPPER,
332
+ subfigure_wrapper=_SUBFIG_WRAPPER,
333
+ ):
334
+ """Return latex code to draw the graph(s) in `Gbunch`
335
+
336
+ The TikZ drawing utility in LaTeX is used to draw the graph(s).
337
+ If `Gbunch` is a graph, it is drawn in a figure environment.
338
+ If `Gbunch` is an iterable of graphs, each is drawn in a subfigure environment
339
+ within a single figure environment.
340
+
341
+ If `as_document` is True, the figure is wrapped inside a document environment
342
+ so that the resulting string is ready to be compiled by LaTeX. Otherwise,
343
+ the string is ready for inclusion in a larger tex document using ``\\include``
344
+ or ``\\input`` statements.
345
+
346
+ Parameters
347
+ ==========
348
+ Gbunch : NetworkX graph or iterable of NetworkX graphs
349
+ The NetworkX graph to be drawn or an iterable of graphs
350
+ to be drawn inside subfigures of a single figure.
351
+ pos : string or list of strings
352
+ The name of the node attribute on `G` that holds the position of each node.
353
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
354
+ They can also be strings to denote positions in TikZ style, such as (x, y)
355
+ or (angle:radius).
356
+ If a dict, it should be keyed by node to a position.
357
+ If an empty dict, a circular layout is computed by TikZ.
358
+ If you are drawing many graphs in subfigures, use a list of position dicts.
359
+ tikz_options : string
360
+ The tikzpicture options description defining the options for the picture.
361
+ Often large scale options like `[scale=2]`.
362
+ default_node_options : string
363
+ The draw options for a path of nodes. Individual node options override these.
364
+ node_options : string or dict
365
+ The name of the node attribute on `G` that holds the options for each node.
366
+ Or a dict keyed by node to a string holding the options for that node.
367
+ node_label : string or dict
368
+ The name of the node attribute on `G` that holds the node label (text)
369
+ displayed for each node. If the attribute is "" or not present, the node
370
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
371
+ Or a dict keyed by node to a string holding the label for that node.
372
+ default_edge_options : string
373
+ The options for the scope drawing all edges. The default is "[-]" for
374
+ undirected graphs and "[->]" for directed graphs.
375
+ edge_options : string or dict
376
+ The name of the edge attribute on `G` that holds the options for each edge.
377
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
378
+ "loop," is added to the options for the self-loop edge. Hence you can
379
+ use "[loop above]" explicitly, but the default is "[loop]".
380
+ Or a dict keyed by edge to a string holding the options for that edge.
381
+ edge_label : string or dict
382
+ The name of the edge attribute on `G` that holds the edge label (text)
383
+ displayed for each edge. If the attribute is "" or not present, no edge
384
+ label is drawn.
385
+ Or a dict keyed by edge to a string holding the label for that edge.
386
+ edge_label_options : string or dict
387
+ The name of the edge attribute on `G` that holds the label options for
388
+ each edge. For example, "[sloped,above,blue]". The default is no options.
389
+ Or a dict keyed by edge to a string holding the label options for that edge.
390
+ caption : string
391
+ The caption string for the figure environment
392
+ latex_label : string
393
+ The latex label used for the figure for easy referral from the main text
394
+ sub_captions : list of strings
395
+ The sub_caption string for each subfigure in the figure
396
+ sub_latex_labels : list of strings
397
+ The latex label for each subfigure in the figure
398
+ n_rows : int
399
+ The number of rows of subfigures to arrange for multiple graphs
400
+ as_document : bool
401
+ Whether to wrap the latex code in a document environment for compiling
402
+ document_wrapper : formatted text string with variable ``content``.
403
+ This text is called to evaluate the content embedded in a document
404
+ environment with a preamble setting up TikZ.
405
+ figure_wrapper : formatted text string
406
+ This text is evaluated with variables ``content``, ``caption`` and ``label``.
407
+ It wraps the content and if a caption is provided, adds the latex code for
408
+ that caption, and if a label is provided, adds the latex code for a label.
409
+ subfigure_wrapper : formatted text string
410
+ This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
411
+ It wraps the content and if a caption is provided, adds the latex code for
412
+ that caption, and if a label is provided, adds the latex code for a label.
413
+ The size is the vertical size of each row of subfigures as a fraction.
414
+
415
+ Returns
416
+ =======
417
+ latex_code : string
418
+ The text string which draws the desired graph(s) when compiled by LaTeX.
419
+
420
+ See Also
421
+ ========
422
+ write_latex
423
+ to_latex_raw
424
+ """
425
+ if hasattr(Gbunch, "adj"):
426
+ raw = to_latex_raw(
427
+ Gbunch,
428
+ pos,
429
+ tikz_options,
430
+ default_node_options,
431
+ node_options,
432
+ node_label,
433
+ default_edge_options,
434
+ edge_options,
435
+ edge_label,
436
+ edge_label_options,
437
+ )
438
+ else: # iterator of graphs
439
+ sbf = subfigure_wrapper
440
+ size = 1 / n_rows
441
+
442
+ N = len(Gbunch)
443
+ if isinstance(pos, str | dict):
444
+ pos = [pos] * N
445
+ if sub_captions is None:
446
+ sub_captions = [""] * N
447
+ if sub_labels is None:
448
+ sub_labels = [""] * N
449
+ if not (len(Gbunch) == len(pos) == len(sub_captions) == len(sub_labels)):
450
+ raise nx.NetworkXError(
451
+ "length of Gbunch, sub_captions and sub_figures must agree"
452
+ )
453
+
454
+ raw = ""
455
+ for G, pos, subcap, sublbl in zip(Gbunch, pos, sub_captions, sub_labels):
456
+ subraw = to_latex_raw(
457
+ G,
458
+ pos,
459
+ tikz_options,
460
+ default_node_options,
461
+ node_options,
462
+ node_label,
463
+ default_edge_options,
464
+ edge_options,
465
+ edge_label,
466
+ edge_label_options,
467
+ )
468
+ cap = f" \\caption{{{subcap}}}" if subcap else ""
469
+ lbl = f"\\label{{{sublbl}}}" if sublbl else ""
470
+ raw += sbf.format(size=size, content=subraw, caption=cap, label=lbl)
471
+ raw += "\n"
472
+
473
+ # put raw latex code into a figure environment and optionally into a document
474
+ raw = raw[:-1]
475
+ cap = f"\n \\caption{{{caption}}}" if caption else ""
476
+ lbl = f"\\label{{{latex_label}}}" if latex_label else ""
477
+ fig = figure_wrapper.format(content=raw, caption=cap, label=lbl)
478
+ if as_document:
479
+ return document_wrapper.format(content=fig)
480
+ return fig
481
+
482
+
483
+ @nx.utils.open_file(1, mode="w")
484
+ def write_latex(Gbunch, path, **options):
485
+ """Write the latex code to draw the graph(s) onto `path`.
486
+
487
+ This convenience function creates the latex drawing code as a string
488
+ and writes that to a file ready to be compiled when `as_document` is True
489
+ or ready to be ``import`` ed or ``include`` ed into your main LaTeX document.
490
+
491
+ The `path` argument can be a string filename or a file handle to write to.
492
+
493
+ Parameters
494
+ ----------
495
+ Gbunch : NetworkX graph or iterable of NetworkX graphs
496
+ If Gbunch is a graph, it is drawn in a figure environment.
497
+ If Gbunch is an iterable of graphs, each is drawn in a subfigure
498
+ environment within a single figure environment.
499
+ path : filename
500
+ Filename or file handle to write to
501
+ options : dict
502
+ By default, TikZ is used with options: (others are ignored)::
503
+
504
+ pos : string or dict or list
505
+ The name of the node attribute on `G` that holds the position of each node.
506
+ Positions can be sequences of length 2 with numbers for (x,y) coordinates.
507
+ They can also be strings to denote positions in TikZ style, such as (x, y)
508
+ or (angle:radius).
509
+ If a dict, it should be keyed by node to a position.
510
+ If an empty dict, a circular layout is computed by TikZ.
511
+ If you are drawing many graphs in subfigures, use a list of position dicts.
512
+ tikz_options : string
513
+ The tikzpicture options description defining the options for the picture.
514
+ Often large scale options like `[scale=2]`.
515
+ default_node_options : string
516
+ The draw options for a path of nodes. Individual node options override these.
517
+ node_options : string or dict
518
+ The name of the node attribute on `G` that holds the options for each node.
519
+ Or a dict keyed by node to a string holding the options for that node.
520
+ node_label : string or dict
521
+ The name of the node attribute on `G` that holds the node label (text)
522
+ displayed for each node. If the attribute is "" or not present, the node
523
+ itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed.
524
+ Or a dict keyed by node to a string holding the label for that node.
525
+ default_edge_options : string
526
+ The options for the scope drawing all edges. The default is "[-]" for
527
+ undirected graphs and "[->]" for directed graphs.
528
+ edge_options : string or dict
529
+ The name of the edge attribute on `G` that holds the options for each edge.
530
+ If the edge is a self-loop and ``"loop" not in edge_options`` the option
531
+ "loop," is added to the options for the self-loop edge. Hence you can
532
+ use "[loop above]" explicitly, but the default is "[loop]".
533
+ Or a dict keyed by edge to a string holding the options for that edge.
534
+ edge_label : string or dict
535
+ The name of the edge attribute on `G` that holds the edge label (text)
536
+ displayed for each edge. If the attribute is "" or not present, no edge
537
+ label is drawn.
538
+ Or a dict keyed by edge to a string holding the label for that edge.
539
+ edge_label_options : string or dict
540
+ The name of the edge attribute on `G` that holds the label options for
541
+ each edge. For example, "[sloped,above,blue]". The default is no options.
542
+ Or a dict keyed by edge to a string holding the label options for that edge.
543
+ caption : string
544
+ The caption string for the figure environment
545
+ latex_label : string
546
+ The latex label used for the figure for easy referral from the main text
547
+ sub_captions : list of strings
548
+ The sub_caption string for each subfigure in the figure
549
+ sub_latex_labels : list of strings
550
+ The latex label for each subfigure in the figure
551
+ n_rows : int
552
+ The number of rows of subfigures to arrange for multiple graphs
553
+ as_document : bool
554
+ Whether to wrap the latex code in a document environment for compiling
555
+ document_wrapper : formatted text string with variable ``content``.
556
+ This text is called to evaluate the content embedded in a document
557
+ environment with a preamble setting up the TikZ syntax.
558
+ figure_wrapper : formatted text string
559
+ This text is evaluated with variables ``content``, ``caption`` and ``label``.
560
+ It wraps the content and if a caption is provided, adds the latex code for
561
+ that caption, and if a label is provided, adds the latex code for a label.
562
+ subfigure_wrapper : formatted text string
563
+ This text evaluate variables ``size``, ``content``, ``caption`` and ``label``.
564
+ It wraps the content and if a caption is provided, adds the latex code for
565
+ that caption, and if a label is provided, adds the latex code for a label.
566
+ The size is the vertical size of each row of subfigures as a fraction.
567
+
568
+ See Also
569
+ ========
570
+ to_latex
571
+ """
572
+ path.write(to_latex(Gbunch, **options))
falcon/lib/python3.10/site-packages/networkx/drawing/nx_pydot.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ *****
3
+ Pydot
4
+ *****
5
+
6
+ Import and export NetworkX graphs in Graphviz dot format using pydot.
7
+
8
+ Either this module or nx_agraph can be used to interface with graphviz.
9
+
10
+ Examples
11
+ --------
12
+ >>> G = nx.complete_graph(5)
13
+ >>> PG = nx.nx_pydot.to_pydot(G)
14
+ >>> H = nx.nx_pydot.from_pydot(PG)
15
+
16
+ See Also
17
+ --------
18
+ - pydot: https://github.com/erocarrera/pydot
19
+ - Graphviz: https://www.graphviz.org
20
+ - DOT Language: http://www.graphviz.org/doc/info/lang.html
21
+ """
22
+
23
+ from locale import getpreferredencoding
24
+
25
+ import networkx as nx
26
+ from networkx.utils import open_file
27
+
28
+ __all__ = [
29
+ "write_dot",
30
+ "read_dot",
31
+ "graphviz_layout",
32
+ "pydot_layout",
33
+ "to_pydot",
34
+ "from_pydot",
35
+ ]
36
+
37
+
38
+ @open_file(1, mode="w")
39
+ def write_dot(G, path):
40
+ """Write NetworkX graph G to Graphviz dot format on path.
41
+
42
+ Path can be a string or a file handle.
43
+ """
44
+ P = to_pydot(G)
45
+ path.write(P.to_string())
46
+ return
47
+
48
+
49
+ @open_file(0, mode="r")
50
+ @nx._dispatchable(name="pydot_read_dot", graphs=None, returns_graph=True)
51
+ def read_dot(path):
52
+ """Returns a NetworkX :class:`MultiGraph` or :class:`MultiDiGraph` from the
53
+ dot file with the passed path.
54
+
55
+ If this file contains multiple graphs, only the first such graph is
56
+ returned. All graphs _except_ the first are silently ignored.
57
+
58
+ Parameters
59
+ ----------
60
+ path : str or file
61
+ Filename or file handle.
62
+
63
+ Returns
64
+ -------
65
+ G : MultiGraph or MultiDiGraph
66
+ A :class:`MultiGraph` or :class:`MultiDiGraph`.
67
+
68
+ Notes
69
+ -----
70
+ Use `G = nx.Graph(nx.nx_pydot.read_dot(path))` to return a :class:`Graph` instead of a
71
+ :class:`MultiGraph`.
72
+ """
73
+ import pydot
74
+
75
+ data = path.read()
76
+
77
+ # List of one or more "pydot.Dot" instances deserialized from this file.
78
+ P_list = pydot.graph_from_dot_data(data)
79
+
80
+ # Convert only the first such instance into a NetworkX graph.
81
+ return from_pydot(P_list[0])
82
+
83
+
84
+ @nx._dispatchable(graphs=None, returns_graph=True)
85
+ def from_pydot(P):
86
+ """Returns a NetworkX graph from a Pydot graph.
87
+
88
+ Parameters
89
+ ----------
90
+ P : Pydot graph
91
+ A graph created with Pydot
92
+
93
+ Returns
94
+ -------
95
+ G : NetworkX multigraph
96
+ A MultiGraph or MultiDiGraph.
97
+
98
+ Examples
99
+ --------
100
+ >>> K5 = nx.complete_graph(5)
101
+ >>> A = nx.nx_pydot.to_pydot(K5)
102
+ >>> G = nx.nx_pydot.from_pydot(A) # return MultiGraph
103
+
104
+ # make a Graph instead of MultiGraph
105
+ >>> G = nx.Graph(nx.nx_pydot.from_pydot(A))
106
+
107
+ """
108
+
109
+ if P.get_strict(None): # pydot bug: get_strict() shouldn't take argument
110
+ multiedges = False
111
+ else:
112
+ multiedges = True
113
+
114
+ if P.get_type() == "graph": # undirected
115
+ if multiedges:
116
+ N = nx.MultiGraph()
117
+ else:
118
+ N = nx.Graph()
119
+ else:
120
+ if multiedges:
121
+ N = nx.MultiDiGraph()
122
+ else:
123
+ N = nx.DiGraph()
124
+
125
+ # assign defaults
126
+ name = P.get_name().strip('"')
127
+ if name != "":
128
+ N.name = name
129
+
130
+ # add nodes, attributes to N.node_attr
131
+ for p in P.get_node_list():
132
+ n = p.get_name().strip('"')
133
+ if n in ("node", "graph", "edge"):
134
+ continue
135
+ N.add_node(n, **p.get_attributes())
136
+
137
+ # add edges
138
+ for e in P.get_edge_list():
139
+ u = e.get_source()
140
+ v = e.get_destination()
141
+ attr = e.get_attributes()
142
+ s = []
143
+ d = []
144
+
145
+ if isinstance(u, str):
146
+ s.append(u.strip('"'))
147
+ else:
148
+ for unodes in u["nodes"]:
149
+ s.append(unodes.strip('"'))
150
+
151
+ if isinstance(v, str):
152
+ d.append(v.strip('"'))
153
+ else:
154
+ for vnodes in v["nodes"]:
155
+ d.append(vnodes.strip('"'))
156
+
157
+ for source_node in s:
158
+ for destination_node in d:
159
+ N.add_edge(source_node, destination_node, **attr)
160
+
161
+ # add default attributes for graph, nodes, edges
162
+ pattr = P.get_attributes()
163
+ if pattr:
164
+ N.graph["graph"] = pattr
165
+ try:
166
+ N.graph["node"] = P.get_node_defaults()[0]
167
+ except (IndexError, TypeError):
168
+ pass # N.graph['node']={}
169
+ try:
170
+ N.graph["edge"] = P.get_edge_defaults()[0]
171
+ except (IndexError, TypeError):
172
+ pass # N.graph['edge']={}
173
+ return N
174
+
175
+
176
+ def to_pydot(N):
177
+ """Returns a pydot graph from a NetworkX graph N.
178
+
179
+ Parameters
180
+ ----------
181
+ N : NetworkX graph
182
+ A graph created with NetworkX
183
+
184
+ Examples
185
+ --------
186
+ >>> K5 = nx.complete_graph(5)
187
+ >>> P = nx.nx_pydot.to_pydot(K5)
188
+
189
+ Notes
190
+ -----
191
+
192
+ """
193
+ import pydot
194
+
195
+ # set Graphviz graph type
196
+ if N.is_directed():
197
+ graph_type = "digraph"
198
+ else:
199
+ graph_type = "graph"
200
+ strict = nx.number_of_selfloops(N) == 0 and not N.is_multigraph()
201
+
202
+ name = N.name
203
+ graph_defaults = N.graph.get("graph", {})
204
+ if name == "":
205
+ P = pydot.Dot("", graph_type=graph_type, strict=strict, **graph_defaults)
206
+ else:
207
+ P = pydot.Dot(
208
+ f'"{name}"', graph_type=graph_type, strict=strict, **graph_defaults
209
+ )
210
+ try:
211
+ P.set_node_defaults(**N.graph["node"])
212
+ except KeyError:
213
+ pass
214
+ try:
215
+ P.set_edge_defaults(**N.graph["edge"])
216
+ except KeyError:
217
+ pass
218
+
219
+ for n, nodedata in N.nodes(data=True):
220
+ str_nodedata = {str(k): str(v) for k, v in nodedata.items()}
221
+ n = str(n)
222
+ p = pydot.Node(n, **str_nodedata)
223
+ P.add_node(p)
224
+
225
+ if N.is_multigraph():
226
+ for u, v, key, edgedata in N.edges(data=True, keys=True):
227
+ str_edgedata = {str(k): str(v) for k, v in edgedata.items() if k != "key"}
228
+ u, v = str(u), str(v)
229
+ edge = pydot.Edge(u, v, key=str(key), **str_edgedata)
230
+ P.add_edge(edge)
231
+
232
+ else:
233
+ for u, v, edgedata in N.edges(data=True):
234
+ str_edgedata = {str(k): str(v) for k, v in edgedata.items()}
235
+ u, v = str(u), str(v)
236
+ edge = pydot.Edge(u, v, **str_edgedata)
237
+ P.add_edge(edge)
238
+ return P
239
+
240
+
241
+ def graphviz_layout(G, prog="neato", root=None):
242
+ """Create node positions using Pydot and Graphviz.
243
+
244
+ Returns a dictionary of positions keyed by node.
245
+
246
+ Parameters
247
+ ----------
248
+ G : NetworkX Graph
249
+ The graph for which the layout is computed.
250
+ prog : string (default: 'neato')
251
+ The name of the GraphViz program to use for layout.
252
+ Options depend on GraphViz version but may include:
253
+ 'dot', 'twopi', 'fdp', 'sfdp', 'circo'
254
+ root : Node from G or None (default: None)
255
+ The node of G from which to start some layout algorithms.
256
+
257
+ Returns
258
+ -------
259
+ Dictionary of (x, y) positions keyed by node.
260
+
261
+ Examples
262
+ --------
263
+ >>> G = nx.complete_graph(4)
264
+ >>> pos = nx.nx_pydot.graphviz_layout(G)
265
+ >>> pos = nx.nx_pydot.graphviz_layout(G, prog="dot")
266
+
267
+ Notes
268
+ -----
269
+ This is a wrapper for pydot_layout.
270
+ """
271
+ return pydot_layout(G=G, prog=prog, root=root)
272
+
273
+
274
+ def pydot_layout(G, prog="neato", root=None):
275
+ """Create node positions using :mod:`pydot` and Graphviz.
276
+
277
+ Parameters
278
+ ----------
279
+ G : Graph
280
+ NetworkX graph to be laid out.
281
+ prog : string (default: 'neato')
282
+ Name of the GraphViz command to use for layout.
283
+ Options depend on GraphViz version but may include:
284
+ 'dot', 'twopi', 'fdp', 'sfdp', 'circo'
285
+ root : Node from G or None (default: None)
286
+ The node of G from which to start some layout algorithms.
287
+
288
+ Returns
289
+ -------
290
+ dict
291
+ Dictionary of positions keyed by node.
292
+
293
+ Examples
294
+ --------
295
+ >>> G = nx.complete_graph(4)
296
+ >>> pos = nx.nx_pydot.pydot_layout(G)
297
+ >>> pos = nx.nx_pydot.pydot_layout(G, prog="dot")
298
+
299
+ Notes
300
+ -----
301
+ If you use complex node objects, they may have the same string
302
+ representation and GraphViz could treat them as the same node.
303
+ The layout may assign both nodes a single location. See Issue #1568
304
+ If this occurs in your case, consider relabeling the nodes just
305
+ for the layout computation using something similar to::
306
+
307
+ H = nx.convert_node_labels_to_integers(G, label_attribute="node_label")
308
+ H_layout = nx.nx_pydot.pydot_layout(H, prog="dot")
309
+ G_layout = {H.nodes[n]["node_label"]: p for n, p in H_layout.items()}
310
+
311
+ """
312
+ import pydot
313
+
314
+ P = to_pydot(G)
315
+ if root is not None:
316
+ P.set("root", str(root))
317
+
318
+ # List of low-level bytes comprising a string in the dot language converted
319
+ # from the passed graph with the passed external GraphViz command.
320
+ D_bytes = P.create_dot(prog=prog)
321
+
322
+ # Unique string decoded from these bytes with the preferred locale encoding
323
+ D = str(D_bytes, encoding=getpreferredencoding())
324
+
325
+ if D == "": # no data returned
326
+ print(f"Graphviz layout with {prog} failed")
327
+ print()
328
+ print("To debug what happened try:")
329
+ print("P = nx.nx_pydot.to_pydot(G)")
330
+ print('P.write_dot("file.dot")')
331
+ print(f"And then run {prog} on file.dot")
332
+ return
333
+
334
+ # List of one or more "pydot.Dot" instances deserialized from this string.
335
+ Q_list = pydot.graph_from_dot_data(D)
336
+ assert len(Q_list) == 1
337
+
338
+ # The first and only such instance, as guaranteed by the above assertion.
339
+ Q = Q_list[0]
340
+
341
+ node_pos = {}
342
+ for n in G.nodes():
343
+ str_n = str(n)
344
+ node = Q.get_node(pydot.quote_id_if_necessary(str_n))
345
+
346
+ if isinstance(node, list):
347
+ node = node[0]
348
+ pos = node.get_pos()[1:-1] # strip leading and trailing double quotes
349
+ if pos is not None:
350
+ xx, yy = pos.split(",")
351
+ node_pos[n] = (float(xx), float(yy))
352
+ return node_pos
falcon/lib/python3.10/site-packages/networkx/drawing/nx_pylab.py ADDED
@@ -0,0 +1,1979 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ **********
3
+ Matplotlib
4
+ **********
5
+
6
+ Draw networks with matplotlib.
7
+
8
+ Examples
9
+ --------
10
+ >>> G = nx.complete_graph(5)
11
+ >>> nx.draw(G)
12
+
13
+ See Also
14
+ --------
15
+ - :doc:`matplotlib <matplotlib:index>`
16
+ - :func:`matplotlib.pyplot.scatter`
17
+ - :obj:`matplotlib.patches.FancyArrowPatch`
18
+ """
19
+
20
+ import collections
21
+ import itertools
22
+ from numbers import Number
23
+
24
+ import networkx as nx
25
+ from networkx.drawing.layout import (
26
+ circular_layout,
27
+ forceatlas2_layout,
28
+ kamada_kawai_layout,
29
+ planar_layout,
30
+ random_layout,
31
+ shell_layout,
32
+ spectral_layout,
33
+ spring_layout,
34
+ )
35
+
36
+ __all__ = [
37
+ "draw",
38
+ "draw_networkx",
39
+ "draw_networkx_nodes",
40
+ "draw_networkx_edges",
41
+ "draw_networkx_labels",
42
+ "draw_networkx_edge_labels",
43
+ "draw_circular",
44
+ "draw_kamada_kawai",
45
+ "draw_random",
46
+ "draw_spectral",
47
+ "draw_spring",
48
+ "draw_planar",
49
+ "draw_shell",
50
+ "draw_forceatlas2",
51
+ ]
52
+
53
+
54
+ def draw(G, pos=None, ax=None, **kwds):
55
+ """Draw the graph G with Matplotlib.
56
+
57
+ Draw the graph as a simple representation with no node
58
+ labels or edge labels and using the full Matplotlib figure area
59
+ and no axis labels by default. See draw_networkx() for more
60
+ full-featured drawing that allows title, axis labels etc.
61
+
62
+ Parameters
63
+ ----------
64
+ G : graph
65
+ A networkx graph
66
+
67
+ pos : dictionary, optional
68
+ A dictionary with nodes as keys and positions as values.
69
+ If not specified a spring layout positioning will be computed.
70
+ See :py:mod:`networkx.drawing.layout` for functions that
71
+ compute node positions.
72
+
73
+ ax : Matplotlib Axes object, optional
74
+ Draw the graph in specified Matplotlib axes.
75
+
76
+ kwds : optional keywords
77
+ See networkx.draw_networkx() for a description of optional keywords.
78
+
79
+ Examples
80
+ --------
81
+ >>> G = nx.dodecahedral_graph()
82
+ >>> nx.draw(G)
83
+ >>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
84
+
85
+ See Also
86
+ --------
87
+ draw_networkx
88
+ draw_networkx_nodes
89
+ draw_networkx_edges
90
+ draw_networkx_labels
91
+ draw_networkx_edge_labels
92
+
93
+ Notes
94
+ -----
95
+ This function has the same name as pylab.draw and pyplot.draw
96
+ so beware when using `from networkx import *`
97
+
98
+ since you might overwrite the pylab.draw function.
99
+
100
+ With pyplot use
101
+
102
+ >>> import matplotlib.pyplot as plt
103
+ >>> G = nx.dodecahedral_graph()
104
+ >>> nx.draw(G) # networkx draw()
105
+ >>> plt.draw() # pyplot draw()
106
+
107
+ Also see the NetworkX drawing examples at
108
+ https://networkx.org/documentation/latest/auto_examples/index.html
109
+ """
110
+ import matplotlib.pyplot as plt
111
+
112
+ if ax is None:
113
+ cf = plt.gcf()
114
+ else:
115
+ cf = ax.get_figure()
116
+ cf.set_facecolor("w")
117
+ if ax is None:
118
+ if cf.axes:
119
+ ax = cf.gca()
120
+ else:
121
+ ax = cf.add_axes((0, 0, 1, 1))
122
+
123
+ if "with_labels" not in kwds:
124
+ kwds["with_labels"] = "labels" in kwds
125
+
126
+ draw_networkx(G, pos=pos, ax=ax, **kwds)
127
+ ax.set_axis_off()
128
+ plt.draw_if_interactive()
129
+ return
130
+
131
+
132
+ def draw_networkx(G, pos=None, arrows=None, with_labels=True, **kwds):
133
+ r"""Draw the graph G using Matplotlib.
134
+
135
+ Draw the graph with Matplotlib with options for node positions,
136
+ labeling, titles, and many other drawing features.
137
+ See draw() for simple drawing without labels or axes.
138
+
139
+ Parameters
140
+ ----------
141
+ G : graph
142
+ A networkx graph
143
+
144
+ pos : dictionary, optional
145
+ A dictionary with nodes as keys and positions as values.
146
+ If not specified a spring layout positioning will be computed.
147
+ See :py:mod:`networkx.drawing.layout` for functions that
148
+ compute node positions.
149
+
150
+ arrows : bool or None, optional (default=None)
151
+ If `None`, directed graphs draw arrowheads with
152
+ `~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
153
+ via `~matplotlib.collections.LineCollection` for speed.
154
+ If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
155
+ If `False`, draw edges using LineCollection (linear and fast).
156
+ For directed graphs, if True draw arrowheads.
157
+ Note: Arrows will be the same color as edges.
158
+
159
+ arrowstyle : str (default='-\|>' for directed graphs)
160
+ For directed graphs, choose the style of the arrowsheads.
161
+ For undirected graphs default to '-'
162
+
163
+ See `matplotlib.patches.ArrowStyle` for more options.
164
+
165
+ arrowsize : int or list (default=10)
166
+ For directed graphs, choose the size of the arrow head's length and
167
+ width. A list of values can be passed in to assign a different size for arrow head's length and width.
168
+ See `matplotlib.patches.FancyArrowPatch` for attribute `mutation_scale`
169
+ for more info.
170
+
171
+ with_labels : bool (default=True)
172
+ Set to True to draw labels on the nodes.
173
+
174
+ ax : Matplotlib Axes object, optional
175
+ Draw the graph in the specified Matplotlib axes.
176
+
177
+ nodelist : list (default=list(G))
178
+ Draw only specified nodes
179
+
180
+ edgelist : list (default=list(G.edges()))
181
+ Draw only specified edges
182
+
183
+ node_size : scalar or array (default=300)
184
+ Size of nodes. If an array is specified it must be the
185
+ same length as nodelist.
186
+
187
+ node_color : color or array of colors (default='#1f78b4')
188
+ Node color. Can be a single color or a sequence of colors with the same
189
+ length as nodelist. Color can be string or rgb (or rgba) tuple of
190
+ floats from 0-1. If numeric values are specified they will be
191
+ mapped to colors using the cmap and vmin,vmax parameters. See
192
+ matplotlib.scatter for more details.
193
+
194
+ node_shape : string (default='o')
195
+ The shape of the node. Specification is as matplotlib.scatter
196
+ marker, one of 'so^>v<dph8'.
197
+
198
+ alpha : float or None (default=None)
199
+ The node and edge transparency
200
+
201
+ cmap : Matplotlib colormap, optional
202
+ Colormap for mapping intensities of nodes
203
+
204
+ vmin,vmax : float, optional
205
+ Minimum and maximum for node colormap scaling
206
+
207
+ linewidths : scalar or sequence (default=1.0)
208
+ Line width of symbol border
209
+
210
+ width : float or array of floats (default=1.0)
211
+ Line width of edges
212
+
213
+ edge_color : color or array of colors (default='k')
214
+ Edge color. Can be a single color or a sequence of colors with the same
215
+ length as edgelist. Color can be string or rgb (or rgba) tuple of
216
+ floats from 0-1. If numeric values are specified they will be
217
+ mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.
218
+
219
+ edge_cmap : Matplotlib colormap, optional
220
+ Colormap for mapping intensities of edges
221
+
222
+ edge_vmin,edge_vmax : floats, optional
223
+ Minimum and maximum for edge colormap scaling
224
+
225
+ style : string (default=solid line)
226
+ Edge line style e.g.: '-', '--', '-.', ':'
227
+ or words like 'solid' or 'dashed'.
228
+ (See `matplotlib.patches.FancyArrowPatch`: `linestyle`)
229
+
230
+ labels : dictionary (default=None)
231
+ Node labels in a dictionary of text labels keyed by node
232
+
233
+ font_size : int (default=12 for nodes, 10 for edges)
234
+ Font size for text labels
235
+
236
+ font_color : color (default='k' black)
237
+ Font color string. Color can be string or rgb (or rgba) tuple of
238
+ floats from 0-1.
239
+
240
+ font_weight : string (default='normal')
241
+ Font weight
242
+
243
+ font_family : string (default='sans-serif')
244
+ Font family
245
+
246
+ label : string, optional
247
+ Label for graph legend
248
+
249
+ hide_ticks : bool, optional
250
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
251
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
252
+ use ``hide_ticks=False``.
253
+
254
+ kwds : optional keywords
255
+ See networkx.draw_networkx_nodes(), networkx.draw_networkx_edges(), and
256
+ networkx.draw_networkx_labels() for a description of optional keywords.
257
+
258
+ Notes
259
+ -----
260
+ For directed graphs, arrows are drawn at the head end. Arrows can be
261
+ turned off with keyword arrows=False.
262
+
263
+ Examples
264
+ --------
265
+ >>> G = nx.dodecahedral_graph()
266
+ >>> nx.draw(G)
267
+ >>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
268
+
269
+ >>> import matplotlib.pyplot as plt
270
+ >>> limits = plt.axis("off") # turn off axis
271
+
272
+ Also see the NetworkX drawing examples at
273
+ https://networkx.org/documentation/latest/auto_examples/index.html
274
+
275
+ See Also
276
+ --------
277
+ draw
278
+ draw_networkx_nodes
279
+ draw_networkx_edges
280
+ draw_networkx_labels
281
+ draw_networkx_edge_labels
282
+ """
283
+ from inspect import signature
284
+
285
+ import matplotlib.pyplot as plt
286
+
287
+ # Get all valid keywords by inspecting the signatures of draw_networkx_nodes,
288
+ # draw_networkx_edges, draw_networkx_labels
289
+
290
+ valid_node_kwds = signature(draw_networkx_nodes).parameters.keys()
291
+ valid_edge_kwds = signature(draw_networkx_edges).parameters.keys()
292
+ valid_label_kwds = signature(draw_networkx_labels).parameters.keys()
293
+
294
+ # Create a set with all valid keywords across the three functions and
295
+ # remove the arguments of this function (draw_networkx)
296
+ valid_kwds = (valid_node_kwds | valid_edge_kwds | valid_label_kwds) - {
297
+ "G",
298
+ "pos",
299
+ "arrows",
300
+ "with_labels",
301
+ }
302
+
303
+ if any(k not in valid_kwds for k in kwds):
304
+ invalid_args = ", ".join([k for k in kwds if k not in valid_kwds])
305
+ raise ValueError(f"Received invalid argument(s): {invalid_args}")
306
+
307
+ node_kwds = {k: v for k, v in kwds.items() if k in valid_node_kwds}
308
+ edge_kwds = {k: v for k, v in kwds.items() if k in valid_edge_kwds}
309
+ label_kwds = {k: v for k, v in kwds.items() if k in valid_label_kwds}
310
+
311
+ if pos is None:
312
+ pos = nx.drawing.spring_layout(G) # default to spring layout
313
+
314
+ draw_networkx_nodes(G, pos, **node_kwds)
315
+ draw_networkx_edges(G, pos, arrows=arrows, **edge_kwds)
316
+ if with_labels:
317
+ draw_networkx_labels(G, pos, **label_kwds)
318
+ plt.draw_if_interactive()
319
+
320
+
321
+ def draw_networkx_nodes(
322
+ G,
323
+ pos,
324
+ nodelist=None,
325
+ node_size=300,
326
+ node_color="#1f78b4",
327
+ node_shape="o",
328
+ alpha=None,
329
+ cmap=None,
330
+ vmin=None,
331
+ vmax=None,
332
+ ax=None,
333
+ linewidths=None,
334
+ edgecolors=None,
335
+ label=None,
336
+ margins=None,
337
+ hide_ticks=True,
338
+ ):
339
+ """Draw the nodes of the graph G.
340
+
341
+ This draws only the nodes of the graph G.
342
+
343
+ Parameters
344
+ ----------
345
+ G : graph
346
+ A networkx graph
347
+
348
+ pos : dictionary
349
+ A dictionary with nodes as keys and positions as values.
350
+ Positions should be sequences of length 2.
351
+
352
+ ax : Matplotlib Axes object, optional
353
+ Draw the graph in the specified Matplotlib axes.
354
+
355
+ nodelist : list (default list(G))
356
+ Draw only specified nodes
357
+
358
+ node_size : scalar or array (default=300)
359
+ Size of nodes. If an array it must be the same length as nodelist.
360
+
361
+ node_color : color or array of colors (default='#1f78b4')
362
+ Node color. Can be a single color or a sequence of colors with the same
363
+ length as nodelist. Color can be string or rgb (or rgba) tuple of
364
+ floats from 0-1. If numeric values are specified they will be
365
+ mapped to colors using the cmap and vmin,vmax parameters. See
366
+ matplotlib.scatter for more details.
367
+
368
+ node_shape : string (default='o')
369
+ The shape of the node. Specification is as matplotlib.scatter
370
+ marker, one of 'so^>v<dph8'.
371
+
372
+ alpha : float or array of floats (default=None)
373
+ The node transparency. This can be a single alpha value,
374
+ in which case it will be applied to all the nodes of color. Otherwise,
375
+ if it is an array, the elements of alpha will be applied to the colors
376
+ in order (cycling through alpha multiple times if necessary).
377
+
378
+ cmap : Matplotlib colormap (default=None)
379
+ Colormap for mapping intensities of nodes
380
+
381
+ vmin,vmax : floats or None (default=None)
382
+ Minimum and maximum for node colormap scaling
383
+
384
+ linewidths : [None | scalar | sequence] (default=1.0)
385
+ Line width of symbol border
386
+
387
+ edgecolors : [None | scalar | sequence] (default = node_color)
388
+ Colors of node borders. Can be a single color or a sequence of colors with the
389
+ same length as nodelist. Color can be string or rgb (or rgba) tuple of floats
390
+ from 0-1. If numeric values are specified they will be mapped to colors
391
+ using the cmap and vmin,vmax parameters. See `~matplotlib.pyplot.scatter` for more details.
392
+
393
+ label : [None | string]
394
+ Label for legend
395
+
396
+ margins : float or 2-tuple, optional
397
+ Sets the padding for axis autoscaling. Increase margin to prevent
398
+ clipping for nodes that are near the edges of an image. Values should
399
+ be in the range ``[0, 1]``. See :meth:`matplotlib.axes.Axes.margins`
400
+ for details. The default is `None`, which uses the Matplotlib default.
401
+
402
+ hide_ticks : bool, optional
403
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
404
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
405
+ use ``hide_ticks=False``.
406
+
407
+ Returns
408
+ -------
409
+ matplotlib.collections.PathCollection
410
+ `PathCollection` of the nodes.
411
+
412
+ Examples
413
+ --------
414
+ >>> G = nx.dodecahedral_graph()
415
+ >>> nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
416
+
417
+ Also see the NetworkX drawing examples at
418
+ https://networkx.org/documentation/latest/auto_examples/index.html
419
+
420
+ See Also
421
+ --------
422
+ draw
423
+ draw_networkx
424
+ draw_networkx_edges
425
+ draw_networkx_labels
426
+ draw_networkx_edge_labels
427
+ """
428
+ from collections.abc import Iterable
429
+
430
+ import matplotlib as mpl
431
+ import matplotlib.collections # call as mpl.collections
432
+ import matplotlib.pyplot as plt
433
+ import numpy as np
434
+
435
+ if ax is None:
436
+ ax = plt.gca()
437
+
438
+ if nodelist is None:
439
+ nodelist = list(G)
440
+
441
+ if len(nodelist) == 0: # empty nodelist, no drawing
442
+ return mpl.collections.PathCollection(None)
443
+
444
+ try:
445
+ xy = np.asarray([pos[v] for v in nodelist])
446
+ except KeyError as err:
447
+ raise nx.NetworkXError(f"Node {err} has no position.") from err
448
+
449
+ if isinstance(alpha, Iterable):
450
+ node_color = apply_alpha(node_color, alpha, nodelist, cmap, vmin, vmax)
451
+ alpha = None
452
+
453
+ if not isinstance(node_shape, np.ndarray) and not isinstance(node_shape, list):
454
+ node_shape = np.array([node_shape for _ in range(len(nodelist))])
455
+
456
+ for shape in np.unique(node_shape):
457
+ node_collection = ax.scatter(
458
+ xy[node_shape == shape, 0],
459
+ xy[node_shape == shape, 1],
460
+ s=node_size,
461
+ c=node_color,
462
+ marker=shape,
463
+ cmap=cmap,
464
+ vmin=vmin,
465
+ vmax=vmax,
466
+ alpha=alpha,
467
+ linewidths=linewidths,
468
+ edgecolors=edgecolors,
469
+ label=label,
470
+ )
471
+ if hide_ticks:
472
+ ax.tick_params(
473
+ axis="both",
474
+ which="both",
475
+ bottom=False,
476
+ left=False,
477
+ labelbottom=False,
478
+ labelleft=False,
479
+ )
480
+
481
+ if margins is not None:
482
+ if isinstance(margins, Iterable):
483
+ ax.margins(*margins)
484
+ else:
485
+ ax.margins(margins)
486
+
487
+ node_collection.set_zorder(2)
488
+ return node_collection
489
+
490
+
491
+ class FancyArrowFactory:
492
+ """Draw arrows with `matplotlib.patches.FancyarrowPatch`"""
493
+
494
+ class ConnectionStyleFactory:
495
+ def __init__(self, connectionstyles, selfloop_height, ax=None):
496
+ import matplotlib as mpl
497
+ import matplotlib.path # call as mpl.path
498
+ import numpy as np
499
+
500
+ self.ax = ax
501
+ self.mpl = mpl
502
+ self.np = np
503
+ self.base_connection_styles = [
504
+ mpl.patches.ConnectionStyle(cs) for cs in connectionstyles
505
+ ]
506
+ self.n = len(self.base_connection_styles)
507
+ self.selfloop_height = selfloop_height
508
+
509
+ def curved(self, edge_index):
510
+ return self.base_connection_styles[edge_index % self.n]
511
+
512
+ def self_loop(self, edge_index):
513
+ def self_loop_connection(posA, posB, *args, **kwargs):
514
+ if not self.np.all(posA == posB):
515
+ raise nx.NetworkXError(
516
+ "`self_loop` connection style method"
517
+ "is only to be used for self-loops"
518
+ )
519
+ # this is called with _screen space_ values
520
+ # so convert back to data space
521
+ data_loc = self.ax.transData.inverted().transform(posA)
522
+ v_shift = 0.1 * self.selfloop_height
523
+ h_shift = v_shift * 0.5
524
+ # put the top of the loop first so arrow is not hidden by node
525
+ path = self.np.asarray(
526
+ [
527
+ # 1
528
+ [0, v_shift],
529
+ # 4 4 4
530
+ [h_shift, v_shift],
531
+ [h_shift, 0],
532
+ [0, 0],
533
+ # 4 4 4
534
+ [-h_shift, 0],
535
+ [-h_shift, v_shift],
536
+ [0, v_shift],
537
+ ]
538
+ )
539
+ # Rotate self loop 90 deg. if more than 1
540
+ # This will allow for maximum of 4 visible self loops
541
+ if edge_index % 4:
542
+ x, y = path.T
543
+ for _ in range(edge_index % 4):
544
+ x, y = y, -x
545
+ path = self.np.array([x, y]).T
546
+ return self.mpl.path.Path(
547
+ self.ax.transData.transform(data_loc + path), [1, 4, 4, 4, 4, 4, 4]
548
+ )
549
+
550
+ return self_loop_connection
551
+
552
+ def __init__(
553
+ self,
554
+ edge_pos,
555
+ edgelist,
556
+ nodelist,
557
+ edge_indices,
558
+ node_size,
559
+ selfloop_height,
560
+ connectionstyle="arc3",
561
+ node_shape="o",
562
+ arrowstyle="-",
563
+ arrowsize=10,
564
+ edge_color="k",
565
+ alpha=None,
566
+ linewidth=1.0,
567
+ style="solid",
568
+ min_source_margin=0,
569
+ min_target_margin=0,
570
+ ax=None,
571
+ ):
572
+ import matplotlib as mpl
573
+ import matplotlib.patches # call as mpl.patches
574
+ import matplotlib.pyplot as plt
575
+ import numpy as np
576
+
577
+ if isinstance(connectionstyle, str):
578
+ connectionstyle = [connectionstyle]
579
+ elif np.iterable(connectionstyle):
580
+ connectionstyle = list(connectionstyle)
581
+ else:
582
+ msg = "ConnectionStyleFactory arg `connectionstyle` must be str or iterable"
583
+ raise nx.NetworkXError(msg)
584
+ self.ax = ax
585
+ self.mpl = mpl
586
+ self.np = np
587
+ self.edge_pos = edge_pos
588
+ self.edgelist = edgelist
589
+ self.nodelist = nodelist
590
+ self.node_shape = node_shape
591
+ self.min_source_margin = min_source_margin
592
+ self.min_target_margin = min_target_margin
593
+ self.edge_indices = edge_indices
594
+ self.node_size = node_size
595
+ self.connectionstyle_factory = self.ConnectionStyleFactory(
596
+ connectionstyle, selfloop_height, ax
597
+ )
598
+ self.arrowstyle = arrowstyle
599
+ self.arrowsize = arrowsize
600
+ self.arrow_colors = mpl.colors.colorConverter.to_rgba_array(edge_color, alpha)
601
+ self.linewidth = linewidth
602
+ self.style = style
603
+ if isinstance(arrowsize, list) and len(arrowsize) != len(edge_pos):
604
+ raise ValueError("arrowsize should have the same length as edgelist")
605
+
606
+ def __call__(self, i):
607
+ (x1, y1), (x2, y2) = self.edge_pos[i]
608
+ shrink_source = 0 # space from source to tail
609
+ shrink_target = 0 # space from head to target
610
+ if (
611
+ self.np.iterable(self.min_source_margin)
612
+ and not isinstance(self.min_source_margin, str)
613
+ and not isinstance(self.min_source_margin, tuple)
614
+ ):
615
+ min_source_margin = self.min_source_margin[i]
616
+ else:
617
+ min_source_margin = self.min_source_margin
618
+
619
+ if (
620
+ self.np.iterable(self.min_target_margin)
621
+ and not isinstance(self.min_target_margin, str)
622
+ and not isinstance(self.min_target_margin, tuple)
623
+ ):
624
+ min_target_margin = self.min_target_margin[i]
625
+ else:
626
+ min_target_margin = self.min_target_margin
627
+
628
+ if self.np.iterable(self.node_size): # many node sizes
629
+ source, target = self.edgelist[i][:2]
630
+ source_node_size = self.node_size[self.nodelist.index(source)]
631
+ target_node_size = self.node_size[self.nodelist.index(target)]
632
+ shrink_source = self.to_marker_edge(source_node_size, self.node_shape)
633
+ shrink_target = self.to_marker_edge(target_node_size, self.node_shape)
634
+ else:
635
+ shrink_source = self.to_marker_edge(self.node_size, self.node_shape)
636
+ shrink_target = shrink_source
637
+ shrink_source = max(shrink_source, min_source_margin)
638
+ shrink_target = max(shrink_target, min_target_margin)
639
+
640
+ # scale factor of arrow head
641
+ if isinstance(self.arrowsize, list):
642
+ mutation_scale = self.arrowsize[i]
643
+ else:
644
+ mutation_scale = self.arrowsize
645
+
646
+ if len(self.arrow_colors) > i:
647
+ arrow_color = self.arrow_colors[i]
648
+ elif len(self.arrow_colors) == 1:
649
+ arrow_color = self.arrow_colors[0]
650
+ else: # Cycle through colors
651
+ arrow_color = self.arrow_colors[i % len(self.arrow_colors)]
652
+
653
+ if self.np.iterable(self.linewidth):
654
+ if len(self.linewidth) > i:
655
+ linewidth = self.linewidth[i]
656
+ else:
657
+ linewidth = self.linewidth[i % len(self.linewidth)]
658
+ else:
659
+ linewidth = self.linewidth
660
+
661
+ if (
662
+ self.np.iterable(self.style)
663
+ and not isinstance(self.style, str)
664
+ and not isinstance(self.style, tuple)
665
+ ):
666
+ if len(self.style) > i:
667
+ linestyle = self.style[i]
668
+ else: # Cycle through styles
669
+ linestyle = self.style[i % len(self.style)]
670
+ else:
671
+ linestyle = self.style
672
+
673
+ if x1 == x2 and y1 == y2:
674
+ connectionstyle = self.connectionstyle_factory.self_loop(
675
+ self.edge_indices[i]
676
+ )
677
+ else:
678
+ connectionstyle = self.connectionstyle_factory.curved(self.edge_indices[i])
679
+
680
+ if (
681
+ self.np.iterable(self.arrowstyle)
682
+ and not isinstance(self.arrowstyle, str)
683
+ and not isinstance(self.arrowstyle, tuple)
684
+ ):
685
+ arrowstyle = self.arrowstyle[i]
686
+ else:
687
+ arrowstyle = self.arrowstyle
688
+
689
+ return self.mpl.patches.FancyArrowPatch(
690
+ (x1, y1),
691
+ (x2, y2),
692
+ arrowstyle=arrowstyle,
693
+ shrinkA=shrink_source,
694
+ shrinkB=shrink_target,
695
+ mutation_scale=mutation_scale,
696
+ color=arrow_color,
697
+ linewidth=linewidth,
698
+ connectionstyle=connectionstyle,
699
+ linestyle=linestyle,
700
+ zorder=1, # arrows go behind nodes
701
+ )
702
+
703
+ def to_marker_edge(self, marker_size, marker):
704
+ if marker in "s^>v<d": # `large` markers need extra space
705
+ return self.np.sqrt(2 * marker_size) / 2
706
+ else:
707
+ return self.np.sqrt(marker_size) / 2
708
+
709
+
710
+ def draw_networkx_edges(
711
+ G,
712
+ pos,
713
+ edgelist=None,
714
+ width=1.0,
715
+ edge_color="k",
716
+ style="solid",
717
+ alpha=None,
718
+ arrowstyle=None,
719
+ arrowsize=10,
720
+ edge_cmap=None,
721
+ edge_vmin=None,
722
+ edge_vmax=None,
723
+ ax=None,
724
+ arrows=None,
725
+ label=None,
726
+ node_size=300,
727
+ nodelist=None,
728
+ node_shape="o",
729
+ connectionstyle="arc3",
730
+ min_source_margin=0,
731
+ min_target_margin=0,
732
+ hide_ticks=True,
733
+ ):
734
+ r"""Draw the edges of the graph G.
735
+
736
+ This draws only the edges of the graph G.
737
+
738
+ Parameters
739
+ ----------
740
+ G : graph
741
+ A networkx graph
742
+
743
+ pos : dictionary
744
+ A dictionary with nodes as keys and positions as values.
745
+ Positions should be sequences of length 2.
746
+
747
+ edgelist : collection of edge tuples (default=G.edges())
748
+ Draw only specified edges
749
+
750
+ width : float or array of floats (default=1.0)
751
+ Line width of edges
752
+
753
+ edge_color : color or array of colors (default='k')
754
+ Edge color. Can be a single color or a sequence of colors with the same
755
+ length as edgelist. Color can be string or rgb (or rgba) tuple of
756
+ floats from 0-1. If numeric values are specified they will be
757
+ mapped to colors using the edge_cmap and edge_vmin,edge_vmax parameters.
758
+
759
+ style : string or array of strings (default='solid')
760
+ Edge line style e.g.: '-', '--', '-.', ':'
761
+ or words like 'solid' or 'dashed'.
762
+ Can be a single style or a sequence of styles with the same
763
+ length as the edge list.
764
+ If less styles than edges are given the styles will cycle.
765
+ If more styles than edges are given the styles will be used sequentially
766
+ and not be exhausted.
767
+ Also, `(offset, onoffseq)` tuples can be used as style instead of a strings.
768
+ (See `matplotlib.patches.FancyArrowPatch`: `linestyle`)
769
+
770
+ alpha : float or array of floats (default=None)
771
+ The edge transparency. This can be a single alpha value,
772
+ in which case it will be applied to all specified edges. Otherwise,
773
+ if it is an array, the elements of alpha will be applied to the colors
774
+ in order (cycling through alpha multiple times if necessary).
775
+
776
+ edge_cmap : Matplotlib colormap, optional
777
+ Colormap for mapping intensities of edges
778
+
779
+ edge_vmin,edge_vmax : floats, optional
780
+ Minimum and maximum for edge colormap scaling
781
+
782
+ ax : Matplotlib Axes object, optional
783
+ Draw the graph in the specified Matplotlib axes.
784
+
785
+ arrows : bool or None, optional (default=None)
786
+ If `None`, directed graphs draw arrowheads with
787
+ `~matplotlib.patches.FancyArrowPatch`, while undirected graphs draw edges
788
+ via `~matplotlib.collections.LineCollection` for speed.
789
+ If `True`, draw arrowheads with FancyArrowPatches (bendable and stylish).
790
+ If `False`, draw edges using LineCollection (linear and fast).
791
+
792
+ Note: Arrowheads will be the same color as edges.
793
+
794
+ arrowstyle : str or list of strs (default='-\|>' for directed graphs)
795
+ For directed graphs and `arrows==True` defaults to '-\|>',
796
+ For undirected graphs default to '-'.
797
+
798
+ See `matplotlib.patches.ArrowStyle` for more options.
799
+
800
+ arrowsize : int or list of ints(default=10)
801
+ For directed graphs, choose the size of the arrow head's length and
802
+ width. See `matplotlib.patches.FancyArrowPatch` for attribute
803
+ `mutation_scale` for more info.
804
+
805
+ connectionstyle : string or iterable of strings (default="arc3")
806
+ Pass the connectionstyle parameter to create curved arc of rounding
807
+ radius rad. For example, connectionstyle='arc3,rad=0.2'.
808
+ See `matplotlib.patches.ConnectionStyle` and
809
+ `matplotlib.patches.FancyArrowPatch` for more info.
810
+ If Iterable, index indicates i'th edge key of MultiGraph
811
+
812
+ node_size : scalar or array (default=300)
813
+ Size of nodes. Though the nodes are not drawn with this function, the
814
+ node size is used in determining edge positioning.
815
+
816
+ nodelist : list, optional (default=G.nodes())
817
+ This provides the node order for the `node_size` array (if it is an array).
818
+
819
+ node_shape : string (default='o')
820
+ The marker used for nodes, used in determining edge positioning.
821
+ Specification is as a `matplotlib.markers` marker, e.g. one of 'so^>v<dph8'.
822
+
823
+ label : None or string
824
+ Label for legend
825
+
826
+ min_source_margin : int or list of ints (default=0)
827
+ The minimum margin (gap) at the beginning of the edge at the source.
828
+
829
+ min_target_margin : int or list of ints (default=0)
830
+ The minimum margin (gap) at the end of the edge at the target.
831
+
832
+ hide_ticks : bool, optional
833
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
834
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
835
+ use ``hide_ticks=False``.
836
+
837
+ Returns
838
+ -------
839
+ matplotlib.collections.LineCollection or a list of matplotlib.patches.FancyArrowPatch
840
+ If ``arrows=True``, a list of FancyArrowPatches is returned.
841
+ If ``arrows=False``, a LineCollection is returned.
842
+ If ``arrows=None`` (the default), then a LineCollection is returned if
843
+ `G` is undirected, otherwise returns a list of FancyArrowPatches.
844
+
845
+ Notes
846
+ -----
847
+ For directed graphs, arrows are drawn at the head end. Arrows can be
848
+ turned off with keyword arrows=False or by passing an arrowstyle without
849
+ an arrow on the end.
850
+
851
+ Be sure to include `node_size` as a keyword argument; arrows are
852
+ drawn considering the size of nodes.
853
+
854
+ Self-loops are always drawn with `~matplotlib.patches.FancyArrowPatch`
855
+ regardless of the value of `arrows` or whether `G` is directed.
856
+ When ``arrows=False`` or ``arrows=None`` and `G` is undirected, the
857
+ FancyArrowPatches corresponding to the self-loops are not explicitly
858
+ returned. They should instead be accessed via the ``Axes.patches``
859
+ attribute (see examples).
860
+
861
+ Examples
862
+ --------
863
+ >>> G = nx.dodecahedral_graph()
864
+ >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
865
+
866
+ >>> G = nx.DiGraph()
867
+ >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)])
868
+ >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
869
+ >>> alphas = [0.3, 0.4, 0.5]
870
+ >>> for i, arc in enumerate(arcs): # change alpha values of arcs
871
+ ... arc.set_alpha(alphas[i])
872
+
873
+ The FancyArrowPatches corresponding to self-loops are not always
874
+ returned, but can always be accessed via the ``patches`` attribute of the
875
+ `matplotlib.Axes` object.
876
+
877
+ >>> import matplotlib.pyplot as plt
878
+ >>> fig, ax = plt.subplots()
879
+ >>> G = nx.Graph([(0, 1), (0, 0)]) # Self-loop at node 0
880
+ >>> edge_collection = nx.draw_networkx_edges(G, pos=nx.circular_layout(G), ax=ax)
881
+ >>> self_loop_fap = ax.patches[0]
882
+
883
+ Also see the NetworkX drawing examples at
884
+ https://networkx.org/documentation/latest/auto_examples/index.html
885
+
886
+ See Also
887
+ --------
888
+ draw
889
+ draw_networkx
890
+ draw_networkx_nodes
891
+ draw_networkx_labels
892
+ draw_networkx_edge_labels
893
+
894
+ """
895
+ import warnings
896
+
897
+ import matplotlib as mpl
898
+ import matplotlib.collections # call as mpl.collections
899
+ import matplotlib.colors # call as mpl.colors
900
+ import matplotlib.pyplot as plt
901
+ import numpy as np
902
+
903
+ # The default behavior is to use LineCollection to draw edges for
904
+ # undirected graphs (for performance reasons) and use FancyArrowPatches
905
+ # for directed graphs.
906
+ # The `arrows` keyword can be used to override the default behavior
907
+ if arrows is None:
908
+ use_linecollection = not (G.is_directed() or G.is_multigraph())
909
+ else:
910
+ if not isinstance(arrows, bool):
911
+ raise TypeError("Argument `arrows` must be of type bool or None")
912
+ use_linecollection = not arrows
913
+
914
+ if isinstance(connectionstyle, str):
915
+ connectionstyle = [connectionstyle]
916
+ elif np.iterable(connectionstyle):
917
+ connectionstyle = list(connectionstyle)
918
+ else:
919
+ msg = "draw_networkx_edges arg `connectionstyle` must be str or iterable"
920
+ raise nx.NetworkXError(msg)
921
+
922
+ # Some kwargs only apply to FancyArrowPatches. Warn users when they use
923
+ # non-default values for these kwargs when LineCollection is being used
924
+ # instead of silently ignoring the specified option
925
+ if use_linecollection:
926
+ msg = (
927
+ "\n\nThe {0} keyword argument is not applicable when drawing edges\n"
928
+ "with LineCollection.\n\n"
929
+ "To make this warning go away, either specify `arrows=True` to\n"
930
+ "force FancyArrowPatches or use the default values.\n"
931
+ "Note that using FancyArrowPatches may be slow for large graphs.\n"
932
+ )
933
+ if arrowstyle is not None:
934
+ warnings.warn(msg.format("arrowstyle"), category=UserWarning, stacklevel=2)
935
+ if arrowsize != 10:
936
+ warnings.warn(msg.format("arrowsize"), category=UserWarning, stacklevel=2)
937
+ if min_source_margin != 0:
938
+ warnings.warn(
939
+ msg.format("min_source_margin"), category=UserWarning, stacklevel=2
940
+ )
941
+ if min_target_margin != 0:
942
+ warnings.warn(
943
+ msg.format("min_target_margin"), category=UserWarning, stacklevel=2
944
+ )
945
+ if any(cs != "arc3" for cs in connectionstyle):
946
+ warnings.warn(
947
+ msg.format("connectionstyle"), category=UserWarning, stacklevel=2
948
+ )
949
+
950
+ # NOTE: Arrowstyle modification must occur after the warnings section
951
+ if arrowstyle is None:
952
+ arrowstyle = "-|>" if G.is_directed() else "-"
953
+
954
+ if ax is None:
955
+ ax = plt.gca()
956
+
957
+ if edgelist is None:
958
+ edgelist = list(G.edges) # (u, v, k) for multigraph (u, v) otherwise
959
+
960
+ if len(edgelist):
961
+ if G.is_multigraph():
962
+ key_count = collections.defaultdict(lambda: itertools.count(0))
963
+ edge_indices = [next(key_count[tuple(e[:2])]) for e in edgelist]
964
+ else:
965
+ edge_indices = [0] * len(edgelist)
966
+ else: # no edges!
967
+ return []
968
+
969
+ if nodelist is None:
970
+ nodelist = list(G.nodes())
971
+
972
+ # FancyArrowPatch handles color=None different from LineCollection
973
+ if edge_color is None:
974
+ edge_color = "k"
975
+
976
+ # set edge positions
977
+ edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
978
+
979
+ # Check if edge_color is an array of floats and map to edge_cmap.
980
+ # This is the only case handled differently from matplotlib
981
+ if (
982
+ np.iterable(edge_color)
983
+ and (len(edge_color) == len(edge_pos))
984
+ and np.all([isinstance(c, Number) for c in edge_color])
985
+ ):
986
+ if edge_cmap is not None:
987
+ assert isinstance(edge_cmap, mpl.colors.Colormap)
988
+ else:
989
+ edge_cmap = plt.get_cmap()
990
+ if edge_vmin is None:
991
+ edge_vmin = min(edge_color)
992
+ if edge_vmax is None:
993
+ edge_vmax = max(edge_color)
994
+ color_normal = mpl.colors.Normalize(vmin=edge_vmin, vmax=edge_vmax)
995
+ edge_color = [edge_cmap(color_normal(e)) for e in edge_color]
996
+
997
+ # compute initial view
998
+ minx = np.amin(np.ravel(edge_pos[:, :, 0]))
999
+ maxx = np.amax(np.ravel(edge_pos[:, :, 0]))
1000
+ miny = np.amin(np.ravel(edge_pos[:, :, 1]))
1001
+ maxy = np.amax(np.ravel(edge_pos[:, :, 1]))
1002
+ w = maxx - minx
1003
+ h = maxy - miny
1004
+
1005
+ # Self-loops are scaled by view extent, except in cases the extent
1006
+ # is 0, e.g. for a single node. In this case, fall back to scaling
1007
+ # by the maximum node size
1008
+ selfloop_height = h if h != 0 else 0.005 * np.array(node_size).max()
1009
+ fancy_arrow_factory = FancyArrowFactory(
1010
+ edge_pos,
1011
+ edgelist,
1012
+ nodelist,
1013
+ edge_indices,
1014
+ node_size,
1015
+ selfloop_height,
1016
+ connectionstyle,
1017
+ node_shape,
1018
+ arrowstyle,
1019
+ arrowsize,
1020
+ edge_color,
1021
+ alpha,
1022
+ width,
1023
+ style,
1024
+ min_source_margin,
1025
+ min_target_margin,
1026
+ ax=ax,
1027
+ )
1028
+
1029
+ # Draw the edges
1030
+ if use_linecollection:
1031
+ edge_collection = mpl.collections.LineCollection(
1032
+ edge_pos,
1033
+ colors=edge_color,
1034
+ linewidths=width,
1035
+ antialiaseds=(1,),
1036
+ linestyle=style,
1037
+ alpha=alpha,
1038
+ )
1039
+ edge_collection.set_cmap(edge_cmap)
1040
+ edge_collection.set_clim(edge_vmin, edge_vmax)
1041
+ edge_collection.set_zorder(1) # edges go behind nodes
1042
+ edge_collection.set_label(label)
1043
+ ax.add_collection(edge_collection)
1044
+ edge_viz_obj = edge_collection
1045
+
1046
+ # Make sure selfloop edges are also drawn
1047
+ # ---------------------------------------
1048
+ selfloops_to_draw = [loop for loop in nx.selfloop_edges(G) if loop in edgelist]
1049
+ if selfloops_to_draw:
1050
+ edgelist_tuple = list(map(tuple, edgelist))
1051
+ arrow_collection = []
1052
+ for loop in selfloops_to_draw:
1053
+ i = edgelist_tuple.index(loop)
1054
+ arrow = fancy_arrow_factory(i)
1055
+ arrow_collection.append(arrow)
1056
+ ax.add_patch(arrow)
1057
+ else:
1058
+ edge_viz_obj = []
1059
+ for i in range(len(edgelist)):
1060
+ arrow = fancy_arrow_factory(i)
1061
+ ax.add_patch(arrow)
1062
+ edge_viz_obj.append(arrow)
1063
+
1064
+ # update view after drawing
1065
+ padx, pady = 0.05 * w, 0.05 * h
1066
+ corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
1067
+ ax.update_datalim(corners)
1068
+ ax.autoscale_view()
1069
+
1070
+ if hide_ticks:
1071
+ ax.tick_params(
1072
+ axis="both",
1073
+ which="both",
1074
+ bottom=False,
1075
+ left=False,
1076
+ labelbottom=False,
1077
+ labelleft=False,
1078
+ )
1079
+
1080
+ return edge_viz_obj
1081
+
1082
+
1083
+ def draw_networkx_labels(
1084
+ G,
1085
+ pos,
1086
+ labels=None,
1087
+ font_size=12,
1088
+ font_color="k",
1089
+ font_family="sans-serif",
1090
+ font_weight="normal",
1091
+ alpha=None,
1092
+ bbox=None,
1093
+ horizontalalignment="center",
1094
+ verticalalignment="center",
1095
+ ax=None,
1096
+ clip_on=True,
1097
+ hide_ticks=True,
1098
+ ):
1099
+ """Draw node labels on the graph G.
1100
+
1101
+ Parameters
1102
+ ----------
1103
+ G : graph
1104
+ A networkx graph
1105
+
1106
+ pos : dictionary
1107
+ A dictionary with nodes as keys and positions as values.
1108
+ Positions should be sequences of length 2.
1109
+
1110
+ labels : dictionary (default={n: n for n in G})
1111
+ Node labels in a dictionary of text labels keyed by node.
1112
+ Node-keys in labels should appear as keys in `pos`.
1113
+ If needed use: `{n:lab for n,lab in labels.items() if n in pos}`
1114
+
1115
+ font_size : int or dictionary of nodes to ints (default=12)
1116
+ Font size for text labels.
1117
+
1118
+ font_color : color or dictionary of nodes to colors (default='k' black)
1119
+ Font color string. Color can be string or rgb (or rgba) tuple of
1120
+ floats from 0-1.
1121
+
1122
+ font_weight : string or dictionary of nodes to strings (default='normal')
1123
+ Font weight.
1124
+
1125
+ font_family : string or dictionary of nodes to strings (default='sans-serif')
1126
+ Font family.
1127
+
1128
+ alpha : float or None or dictionary of nodes to floats (default=None)
1129
+ The text transparency.
1130
+
1131
+ bbox : Matplotlib bbox, (default is Matplotlib's ax.text default)
1132
+ Specify text box properties (e.g. shape, color etc.) for node labels.
1133
+
1134
+ horizontalalignment : string or array of strings (default='center')
1135
+ Horizontal alignment {'center', 'right', 'left'}. If an array is
1136
+ specified it must be the same length as `nodelist`.
1137
+
1138
+ verticalalignment : string (default='center')
1139
+ Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}.
1140
+ If an array is specified it must be the same length as `nodelist`.
1141
+
1142
+ ax : Matplotlib Axes object, optional
1143
+ Draw the graph in the specified Matplotlib axes.
1144
+
1145
+ clip_on : bool (default=True)
1146
+ Turn on clipping of node labels at axis boundaries
1147
+
1148
+ hide_ticks : bool, optional
1149
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
1150
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
1151
+ use ``hide_ticks=False``.
1152
+
1153
+ Returns
1154
+ -------
1155
+ dict
1156
+ `dict` of labels keyed on the nodes
1157
+
1158
+ Examples
1159
+ --------
1160
+ >>> G = nx.dodecahedral_graph()
1161
+ >>> labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
1162
+
1163
+ Also see the NetworkX drawing examples at
1164
+ https://networkx.org/documentation/latest/auto_examples/index.html
1165
+
1166
+ See Also
1167
+ --------
1168
+ draw
1169
+ draw_networkx
1170
+ draw_networkx_nodes
1171
+ draw_networkx_edges
1172
+ draw_networkx_edge_labels
1173
+ """
1174
+ import matplotlib.pyplot as plt
1175
+
1176
+ if ax is None:
1177
+ ax = plt.gca()
1178
+
1179
+ if labels is None:
1180
+ labels = {n: n for n in G.nodes()}
1181
+
1182
+ individual_params = set()
1183
+
1184
+ def check_individual_params(p_value, p_name):
1185
+ if isinstance(p_value, dict):
1186
+ if len(p_value) != len(labels):
1187
+ raise ValueError(f"{p_name} must have the same length as labels.")
1188
+ individual_params.add(p_name)
1189
+
1190
+ def get_param_value(node, p_value, p_name):
1191
+ if p_name in individual_params:
1192
+ return p_value[node]
1193
+ return p_value
1194
+
1195
+ check_individual_params(font_size, "font_size")
1196
+ check_individual_params(font_color, "font_color")
1197
+ check_individual_params(font_weight, "font_weight")
1198
+ check_individual_params(font_family, "font_family")
1199
+ check_individual_params(alpha, "alpha")
1200
+
1201
+ text_items = {} # there is no text collection so we'll fake one
1202
+ for n, label in labels.items():
1203
+ (x, y) = pos[n]
1204
+ if not isinstance(label, str):
1205
+ label = str(label) # this makes "1" and 1 labeled the same
1206
+ t = ax.text(
1207
+ x,
1208
+ y,
1209
+ label,
1210
+ size=get_param_value(n, font_size, "font_size"),
1211
+ color=get_param_value(n, font_color, "font_color"),
1212
+ family=get_param_value(n, font_family, "font_family"),
1213
+ weight=get_param_value(n, font_weight, "font_weight"),
1214
+ alpha=get_param_value(n, alpha, "alpha"),
1215
+ horizontalalignment=horizontalalignment,
1216
+ verticalalignment=verticalalignment,
1217
+ transform=ax.transData,
1218
+ bbox=bbox,
1219
+ clip_on=clip_on,
1220
+ )
1221
+ text_items[n] = t
1222
+
1223
+ if hide_ticks:
1224
+ ax.tick_params(
1225
+ axis="both",
1226
+ which="both",
1227
+ bottom=False,
1228
+ left=False,
1229
+ labelbottom=False,
1230
+ labelleft=False,
1231
+ )
1232
+
1233
+ return text_items
1234
+
1235
+
1236
+ def draw_networkx_edge_labels(
1237
+ G,
1238
+ pos,
1239
+ edge_labels=None,
1240
+ label_pos=0.5,
1241
+ font_size=10,
1242
+ font_color="k",
1243
+ font_family="sans-serif",
1244
+ font_weight="normal",
1245
+ alpha=None,
1246
+ bbox=None,
1247
+ horizontalalignment="center",
1248
+ verticalalignment="center",
1249
+ ax=None,
1250
+ rotate=True,
1251
+ clip_on=True,
1252
+ node_size=300,
1253
+ nodelist=None,
1254
+ connectionstyle="arc3",
1255
+ hide_ticks=True,
1256
+ ):
1257
+ """Draw edge labels.
1258
+
1259
+ Parameters
1260
+ ----------
1261
+ G : graph
1262
+ A networkx graph
1263
+
1264
+ pos : dictionary
1265
+ A dictionary with nodes as keys and positions as values.
1266
+ Positions should be sequences of length 2.
1267
+
1268
+ edge_labels : dictionary (default=None)
1269
+ Edge labels in a dictionary of labels keyed by edge two-tuple.
1270
+ Only labels for the keys in the dictionary are drawn.
1271
+
1272
+ label_pos : float (default=0.5)
1273
+ Position of edge label along edge (0=head, 0.5=center, 1=tail)
1274
+
1275
+ font_size : int (default=10)
1276
+ Font size for text labels
1277
+
1278
+ font_color : color (default='k' black)
1279
+ Font color string. Color can be string or rgb (or rgba) tuple of
1280
+ floats from 0-1.
1281
+
1282
+ font_weight : string (default='normal')
1283
+ Font weight
1284
+
1285
+ font_family : string (default='sans-serif')
1286
+ Font family
1287
+
1288
+ alpha : float or None (default=None)
1289
+ The text transparency
1290
+
1291
+ bbox : Matplotlib bbox, optional
1292
+ Specify text box properties (e.g. shape, color etc.) for edge labels.
1293
+ Default is {boxstyle='round', ec=(1.0, 1.0, 1.0), fc=(1.0, 1.0, 1.0)}.
1294
+
1295
+ horizontalalignment : string (default='center')
1296
+ Horizontal alignment {'center', 'right', 'left'}
1297
+
1298
+ verticalalignment : string (default='center')
1299
+ Vertical alignment {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
1300
+
1301
+ ax : Matplotlib Axes object, optional
1302
+ Draw the graph in the specified Matplotlib axes.
1303
+
1304
+ rotate : bool (default=True)
1305
+ Rotate edge labels to lie parallel to edges
1306
+
1307
+ clip_on : bool (default=True)
1308
+ Turn on clipping of edge labels at axis boundaries
1309
+
1310
+ node_size : scalar or array (default=300)
1311
+ Size of nodes. If an array it must be the same length as nodelist.
1312
+
1313
+ nodelist : list, optional (default=G.nodes())
1314
+ This provides the node order for the `node_size` array (if it is an array).
1315
+
1316
+ connectionstyle : string or iterable of strings (default="arc3")
1317
+ Pass the connectionstyle parameter to create curved arc of rounding
1318
+ radius rad. For example, connectionstyle='arc3,rad=0.2'.
1319
+ See `matplotlib.patches.ConnectionStyle` and
1320
+ `matplotlib.patches.FancyArrowPatch` for more info.
1321
+ If Iterable, index indicates i'th edge key of MultiGraph
1322
+
1323
+ hide_ticks : bool, optional
1324
+ Hide ticks of axes. When `True` (the default), ticks and ticklabels
1325
+ are removed from the axes. To set ticks and tick labels to the pyplot default,
1326
+ use ``hide_ticks=False``.
1327
+
1328
+ Returns
1329
+ -------
1330
+ dict
1331
+ `dict` of labels keyed by edge
1332
+
1333
+ Examples
1334
+ --------
1335
+ >>> G = nx.dodecahedral_graph()
1336
+ >>> edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
1337
+
1338
+ Also see the NetworkX drawing examples at
1339
+ https://networkx.org/documentation/latest/auto_examples/index.html
1340
+
1341
+ See Also
1342
+ --------
1343
+ draw
1344
+ draw_networkx
1345
+ draw_networkx_nodes
1346
+ draw_networkx_edges
1347
+ draw_networkx_labels
1348
+ """
1349
+ import matplotlib as mpl
1350
+ import matplotlib.pyplot as plt
1351
+ import numpy as np
1352
+
1353
+ class CurvedArrowText(mpl.text.Text):
1354
+ def __init__(
1355
+ self,
1356
+ arrow,
1357
+ *args,
1358
+ label_pos=0.5,
1359
+ labels_horizontal=False,
1360
+ ax=None,
1361
+ **kwargs,
1362
+ ):
1363
+ # Bind to FancyArrowPatch
1364
+ self.arrow = arrow
1365
+ # how far along the text should be on the curve,
1366
+ # 0 is at start, 1 is at end etc.
1367
+ self.label_pos = label_pos
1368
+ self.labels_horizontal = labels_horizontal
1369
+ if ax is None:
1370
+ ax = plt.gca()
1371
+ self.ax = ax
1372
+ self.x, self.y, self.angle = self._update_text_pos_angle(arrow)
1373
+
1374
+ # Create text object
1375
+ super().__init__(self.x, self.y, *args, rotation=self.angle, **kwargs)
1376
+ # Bind to axis
1377
+ self.ax.add_artist(self)
1378
+
1379
+ def _get_arrow_path_disp(self, arrow):
1380
+ """
1381
+ This is part of FancyArrowPatch._get_path_in_displaycoord
1382
+ It omits the second part of the method where path is converted
1383
+ to polygon based on width
1384
+ The transform is taken from ax, not the object, as the object
1385
+ has not been added yet, and doesn't have transform
1386
+ """
1387
+ dpi_cor = arrow._dpi_cor
1388
+ # trans_data = arrow.get_transform()
1389
+ trans_data = self.ax.transData
1390
+ if arrow._posA_posB is not None:
1391
+ posA = arrow._convert_xy_units(arrow._posA_posB[0])
1392
+ posB = arrow._convert_xy_units(arrow._posA_posB[1])
1393
+ (posA, posB) = trans_data.transform((posA, posB))
1394
+ _path = arrow.get_connectionstyle()(
1395
+ posA,
1396
+ posB,
1397
+ patchA=arrow.patchA,
1398
+ patchB=arrow.patchB,
1399
+ shrinkA=arrow.shrinkA * dpi_cor,
1400
+ shrinkB=arrow.shrinkB * dpi_cor,
1401
+ )
1402
+ else:
1403
+ _path = trans_data.transform_path(arrow._path_original)
1404
+ # Return is in display coordinates
1405
+ return _path
1406
+
1407
+ def _update_text_pos_angle(self, arrow):
1408
+ # Fractional label position
1409
+ path_disp = self._get_arrow_path_disp(arrow)
1410
+ (x1, y1), (cx, cy), (x2, y2) = path_disp.vertices
1411
+ # Text position at a proportion t along the line in display coords
1412
+ # default is 0.5 so text appears at the halfway point
1413
+ t = self.label_pos
1414
+ tt = 1 - t
1415
+ x = tt**2 * x1 + 2 * t * tt * cx + t**2 * x2
1416
+ y = tt**2 * y1 + 2 * t * tt * cy + t**2 * y2
1417
+ if self.labels_horizontal:
1418
+ # Horizontal text labels
1419
+ angle = 0
1420
+ else:
1421
+ # Labels parallel to curve
1422
+ change_x = 2 * tt * (cx - x1) + 2 * t * (x2 - cx)
1423
+ change_y = 2 * tt * (cy - y1) + 2 * t * (y2 - cy)
1424
+ angle = (np.arctan2(change_y, change_x) / (2 * np.pi)) * 360
1425
+ # Text is "right way up"
1426
+ if angle > 90:
1427
+ angle -= 180
1428
+ if angle < -90:
1429
+ angle += 180
1430
+ (x, y) = self.ax.transData.inverted().transform((x, y))
1431
+ return x, y, angle
1432
+
1433
+ def draw(self, renderer):
1434
+ # recalculate the text position and angle
1435
+ self.x, self.y, self.angle = self._update_text_pos_angle(self.arrow)
1436
+ self.set_position((self.x, self.y))
1437
+ self.set_rotation(self.angle)
1438
+ # redraw text
1439
+ super().draw(renderer)
1440
+
1441
+ # use default box of white with white border
1442
+ if bbox is None:
1443
+ bbox = {"boxstyle": "round", "ec": (1.0, 1.0, 1.0), "fc": (1.0, 1.0, 1.0)}
1444
+
1445
+ if isinstance(connectionstyle, str):
1446
+ connectionstyle = [connectionstyle]
1447
+ elif np.iterable(connectionstyle):
1448
+ connectionstyle = list(connectionstyle)
1449
+ else:
1450
+ raise nx.NetworkXError(
1451
+ "draw_networkx_edges arg `connectionstyle` must be"
1452
+ "string or iterable of strings"
1453
+ )
1454
+
1455
+ if ax is None:
1456
+ ax = plt.gca()
1457
+
1458
+ if edge_labels is None:
1459
+ kwds = {"keys": True} if G.is_multigraph() else {}
1460
+ edge_labels = {tuple(edge): d for *edge, d in G.edges(data=True, **kwds)}
1461
+ # NOTHING TO PLOT
1462
+ if not edge_labels:
1463
+ return {}
1464
+ edgelist, labels = zip(*edge_labels.items())
1465
+
1466
+ if nodelist is None:
1467
+ nodelist = list(G.nodes())
1468
+
1469
+ # set edge positions
1470
+ edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])
1471
+
1472
+ if G.is_multigraph():
1473
+ key_count = collections.defaultdict(lambda: itertools.count(0))
1474
+ edge_indices = [next(key_count[tuple(e[:2])]) for e in edgelist]
1475
+ else:
1476
+ edge_indices = [0] * len(edgelist)
1477
+
1478
+ # Used to determine self loop mid-point
1479
+ # Note, that this will not be accurate,
1480
+ # if not drawing edge_labels for all edges drawn
1481
+ h = 0
1482
+ if edge_labels:
1483
+ miny = np.amin(np.ravel(edge_pos[:, :, 1]))
1484
+ maxy = np.amax(np.ravel(edge_pos[:, :, 1]))
1485
+ h = maxy - miny
1486
+ selfloop_height = h if h != 0 else 0.005 * np.array(node_size).max()
1487
+ fancy_arrow_factory = FancyArrowFactory(
1488
+ edge_pos,
1489
+ edgelist,
1490
+ nodelist,
1491
+ edge_indices,
1492
+ node_size,
1493
+ selfloop_height,
1494
+ connectionstyle,
1495
+ ax=ax,
1496
+ )
1497
+
1498
+ individual_params = {}
1499
+
1500
+ def check_individual_params(p_value, p_name):
1501
+ # TODO should this be list or array (as in a numpy array)?
1502
+ if isinstance(p_value, list):
1503
+ if len(p_value) != len(edgelist):
1504
+ raise ValueError(f"{p_name} must have the same length as edgelist.")
1505
+ individual_params[p_name] = p_value.iter()
1506
+
1507
+ # Don't need to pass in an edge because these are lists, not dicts
1508
+ def get_param_value(p_value, p_name):
1509
+ if p_name in individual_params:
1510
+ return next(individual_params[p_name])
1511
+ return p_value
1512
+
1513
+ check_individual_params(font_size, "font_size")
1514
+ check_individual_params(font_color, "font_color")
1515
+ check_individual_params(font_weight, "font_weight")
1516
+ check_individual_params(alpha, "alpha")
1517
+ check_individual_params(horizontalalignment, "horizontalalignment")
1518
+ check_individual_params(verticalalignment, "verticalalignment")
1519
+ check_individual_params(rotate, "rotate")
1520
+ check_individual_params(label_pos, "label_pos")
1521
+
1522
+ text_items = {}
1523
+ for i, (edge, label) in enumerate(zip(edgelist, labels)):
1524
+ if not isinstance(label, str):
1525
+ label = str(label) # this makes "1" and 1 labeled the same
1526
+
1527
+ n1, n2 = edge[:2]
1528
+ arrow = fancy_arrow_factory(i)
1529
+ if n1 == n2:
1530
+ connectionstyle_obj = arrow.get_connectionstyle()
1531
+ posA = ax.transData.transform(pos[n1])
1532
+ path_disp = connectionstyle_obj(posA, posA)
1533
+ path_data = ax.transData.inverted().transform_path(path_disp)
1534
+ x, y = path_data.vertices[0]
1535
+ text_items[edge] = ax.text(
1536
+ x,
1537
+ y,
1538
+ label,
1539
+ size=get_param_value(font_size, "font_size"),
1540
+ color=get_param_value(font_color, "font_color"),
1541
+ family=get_param_value(font_family, "font_family"),
1542
+ weight=get_param_value(font_weight, "font_weight"),
1543
+ alpha=get_param_value(alpha, "alpha"),
1544
+ horizontalalignment=get_param_value(
1545
+ horizontalalignment, "horizontalalignment"
1546
+ ),
1547
+ verticalalignment=get_param_value(
1548
+ verticalalignment, "verticalalignment"
1549
+ ),
1550
+ rotation=0,
1551
+ transform=ax.transData,
1552
+ bbox=bbox,
1553
+ zorder=1,
1554
+ clip_on=clip_on,
1555
+ )
1556
+ else:
1557
+ text_items[edge] = CurvedArrowText(
1558
+ arrow,
1559
+ label,
1560
+ size=get_param_value(font_size, "font_size"),
1561
+ color=get_param_value(font_color, "font_color"),
1562
+ family=get_param_value(font_family, "font_family"),
1563
+ weight=get_param_value(font_weight, "font_weight"),
1564
+ alpha=get_param_value(alpha, "alpha"),
1565
+ horizontalalignment=get_param_value(
1566
+ horizontalalignment, "horizontalalignment"
1567
+ ),
1568
+ verticalalignment=get_param_value(
1569
+ verticalalignment, "verticalalignment"
1570
+ ),
1571
+ transform=ax.transData,
1572
+ bbox=bbox,
1573
+ zorder=1,
1574
+ clip_on=clip_on,
1575
+ label_pos=get_param_value(label_pos, "label_pos"),
1576
+ labels_horizontal=not get_param_value(rotate, "rotate"),
1577
+ ax=ax,
1578
+ )
1579
+
1580
+ if hide_ticks:
1581
+ ax.tick_params(
1582
+ axis="both",
1583
+ which="both",
1584
+ bottom=False,
1585
+ left=False,
1586
+ labelbottom=False,
1587
+ labelleft=False,
1588
+ )
1589
+
1590
+ return text_items
1591
+
1592
+
1593
+ def draw_circular(G, **kwargs):
1594
+ """Draw the graph `G` with a circular layout.
1595
+
1596
+ This is a convenience function equivalent to::
1597
+
1598
+ nx.draw(G, pos=nx.circular_layout(G), **kwargs)
1599
+
1600
+ Parameters
1601
+ ----------
1602
+ G : graph
1603
+ A networkx graph
1604
+
1605
+ kwargs : optional keywords
1606
+ See `draw_networkx` for a description of optional keywords.
1607
+
1608
+ Notes
1609
+ -----
1610
+ The layout is computed each time this function is called. For
1611
+ repeated drawing it is much more efficient to call
1612
+ `~networkx.drawing.layout.circular_layout` directly and reuse the result::
1613
+
1614
+ >>> G = nx.complete_graph(5)
1615
+ >>> pos = nx.circular_layout(G)
1616
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1617
+ >>> # Draw a subgraph, reusing the same node positions
1618
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1619
+
1620
+ Examples
1621
+ --------
1622
+ >>> G = nx.path_graph(5)
1623
+ >>> nx.draw_circular(G)
1624
+
1625
+ See Also
1626
+ --------
1627
+ :func:`~networkx.drawing.layout.circular_layout`
1628
+ """
1629
+ draw(G, circular_layout(G), **kwargs)
1630
+
1631
+
1632
+ def draw_kamada_kawai(G, **kwargs):
1633
+ """Draw the graph `G` with a Kamada-Kawai force-directed layout.
1634
+
1635
+ This is a convenience function equivalent to::
1636
+
1637
+ nx.draw(G, pos=nx.kamada_kawai_layout(G), **kwargs)
1638
+
1639
+ Parameters
1640
+ ----------
1641
+ G : graph
1642
+ A networkx graph
1643
+
1644
+ kwargs : optional keywords
1645
+ See `draw_networkx` for a description of optional keywords.
1646
+
1647
+ Notes
1648
+ -----
1649
+ The layout is computed each time this function is called.
1650
+ For repeated drawing it is much more efficient to call
1651
+ `~networkx.drawing.layout.kamada_kawai_layout` directly and reuse the
1652
+ result::
1653
+
1654
+ >>> G = nx.complete_graph(5)
1655
+ >>> pos = nx.kamada_kawai_layout(G)
1656
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1657
+ >>> # Draw a subgraph, reusing the same node positions
1658
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1659
+
1660
+ Examples
1661
+ --------
1662
+ >>> G = nx.path_graph(5)
1663
+ >>> nx.draw_kamada_kawai(G)
1664
+
1665
+ See Also
1666
+ --------
1667
+ :func:`~networkx.drawing.layout.kamada_kawai_layout`
1668
+ """
1669
+ draw(G, kamada_kawai_layout(G), **kwargs)
1670
+
1671
+
1672
+ def draw_random(G, **kwargs):
1673
+ """Draw the graph `G` with a random layout.
1674
+
1675
+ This is a convenience function equivalent to::
1676
+
1677
+ nx.draw(G, pos=nx.random_layout(G), **kwargs)
1678
+
1679
+ Parameters
1680
+ ----------
1681
+ G : graph
1682
+ A networkx graph
1683
+
1684
+ kwargs : optional keywords
1685
+ See `draw_networkx` for a description of optional keywords.
1686
+
1687
+ Notes
1688
+ -----
1689
+ The layout is computed each time this function is called.
1690
+ For repeated drawing it is much more efficient to call
1691
+ `~networkx.drawing.layout.random_layout` directly and reuse the result::
1692
+
1693
+ >>> G = nx.complete_graph(5)
1694
+ >>> pos = nx.random_layout(G)
1695
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1696
+ >>> # Draw a subgraph, reusing the same node positions
1697
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1698
+
1699
+ Examples
1700
+ --------
1701
+ >>> G = nx.lollipop_graph(4, 3)
1702
+ >>> nx.draw_random(G)
1703
+
1704
+ See Also
1705
+ --------
1706
+ :func:`~networkx.drawing.layout.random_layout`
1707
+ """
1708
+ draw(G, random_layout(G), **kwargs)
1709
+
1710
+
1711
+ def draw_spectral(G, **kwargs):
1712
+ """Draw the graph `G` with a spectral 2D layout.
1713
+
1714
+ This is a convenience function equivalent to::
1715
+
1716
+ nx.draw(G, pos=nx.spectral_layout(G), **kwargs)
1717
+
1718
+ For more information about how node positions are determined, see
1719
+ `~networkx.drawing.layout.spectral_layout`.
1720
+
1721
+ Parameters
1722
+ ----------
1723
+ G : graph
1724
+ A networkx graph
1725
+
1726
+ kwargs : optional keywords
1727
+ See `draw_networkx` for a description of optional keywords.
1728
+
1729
+ Notes
1730
+ -----
1731
+ The layout is computed each time this function is called.
1732
+ For repeated drawing it is much more efficient to call
1733
+ `~networkx.drawing.layout.spectral_layout` directly and reuse the result::
1734
+
1735
+ >>> G = nx.complete_graph(5)
1736
+ >>> pos = nx.spectral_layout(G)
1737
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1738
+ >>> # Draw a subgraph, reusing the same node positions
1739
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1740
+
1741
+ Examples
1742
+ --------
1743
+ >>> G = nx.path_graph(5)
1744
+ >>> nx.draw_spectral(G)
1745
+
1746
+ See Also
1747
+ --------
1748
+ :func:`~networkx.drawing.layout.spectral_layout`
1749
+ """
1750
+ draw(G, spectral_layout(G), **kwargs)
1751
+
1752
+
1753
+ def draw_spring(G, **kwargs):
1754
+ """Draw the graph `G` with a spring layout.
1755
+
1756
+ This is a convenience function equivalent to::
1757
+
1758
+ nx.draw(G, pos=nx.spring_layout(G), **kwargs)
1759
+
1760
+ Parameters
1761
+ ----------
1762
+ G : graph
1763
+ A networkx graph
1764
+
1765
+ kwargs : optional keywords
1766
+ See `draw_networkx` for a description of optional keywords.
1767
+
1768
+ Notes
1769
+ -----
1770
+ `~networkx.drawing.layout.spring_layout` is also the default layout for
1771
+ `draw`, so this function is equivalent to `draw`.
1772
+
1773
+ The layout is computed each time this function is called.
1774
+ For repeated drawing it is much more efficient to call
1775
+ `~networkx.drawing.layout.spring_layout` directly and reuse the result::
1776
+
1777
+ >>> G = nx.complete_graph(5)
1778
+ >>> pos = nx.spring_layout(G)
1779
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1780
+ >>> # Draw a subgraph, reusing the same node positions
1781
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1782
+
1783
+ Examples
1784
+ --------
1785
+ >>> G = nx.path_graph(20)
1786
+ >>> nx.draw_spring(G)
1787
+
1788
+ See Also
1789
+ --------
1790
+ draw
1791
+ :func:`~networkx.drawing.layout.spring_layout`
1792
+ """
1793
+ draw(G, spring_layout(G), **kwargs)
1794
+
1795
+
1796
+ def draw_shell(G, nlist=None, **kwargs):
1797
+ """Draw networkx graph `G` with shell layout.
1798
+
1799
+ This is a convenience function equivalent to::
1800
+
1801
+ nx.draw(G, pos=nx.shell_layout(G, nlist=nlist), **kwargs)
1802
+
1803
+ Parameters
1804
+ ----------
1805
+ G : graph
1806
+ A networkx graph
1807
+
1808
+ nlist : list of list of nodes, optional
1809
+ A list containing lists of nodes representing the shells.
1810
+ Default is `None`, meaning all nodes are in a single shell.
1811
+ See `~networkx.drawing.layout.shell_layout` for details.
1812
+
1813
+ kwargs : optional keywords
1814
+ See `draw_networkx` for a description of optional keywords.
1815
+
1816
+ Notes
1817
+ -----
1818
+ The layout is computed each time this function is called.
1819
+ For repeated drawing it is much more efficient to call
1820
+ `~networkx.drawing.layout.shell_layout` directly and reuse the result::
1821
+
1822
+ >>> G = nx.complete_graph(5)
1823
+ >>> pos = nx.shell_layout(G)
1824
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1825
+ >>> # Draw a subgraph, reusing the same node positions
1826
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1827
+
1828
+ Examples
1829
+ --------
1830
+ >>> G = nx.path_graph(4)
1831
+ >>> shells = [[0], [1, 2, 3]]
1832
+ >>> nx.draw_shell(G, nlist=shells)
1833
+
1834
+ See Also
1835
+ --------
1836
+ :func:`~networkx.drawing.layout.shell_layout`
1837
+ """
1838
+ draw(G, shell_layout(G, nlist=nlist), **kwargs)
1839
+
1840
+
1841
+ def draw_planar(G, **kwargs):
1842
+ """Draw a planar networkx graph `G` with planar layout.
1843
+
1844
+ This is a convenience function equivalent to::
1845
+
1846
+ nx.draw(G, pos=nx.planar_layout(G), **kwargs)
1847
+
1848
+ Parameters
1849
+ ----------
1850
+ G : graph
1851
+ A planar networkx graph
1852
+
1853
+ kwargs : optional keywords
1854
+ See `draw_networkx` for a description of optional keywords.
1855
+
1856
+ Raises
1857
+ ------
1858
+ NetworkXException
1859
+ When `G` is not planar
1860
+
1861
+ Notes
1862
+ -----
1863
+ The layout is computed each time this function is called.
1864
+ For repeated drawing it is much more efficient to call
1865
+ `~networkx.drawing.layout.planar_layout` directly and reuse the result::
1866
+
1867
+ >>> G = nx.path_graph(5)
1868
+ >>> pos = nx.planar_layout(G)
1869
+ >>> nx.draw(G, pos=pos) # Draw the original graph
1870
+ >>> # Draw a subgraph, reusing the same node positions
1871
+ >>> nx.draw(G.subgraph([0, 1, 2]), pos=pos, node_color="red")
1872
+
1873
+ Examples
1874
+ --------
1875
+ >>> G = nx.path_graph(4)
1876
+ >>> nx.draw_planar(G)
1877
+
1878
+ See Also
1879
+ --------
1880
+ :func:`~networkx.drawing.layout.planar_layout`
1881
+ """
1882
+ draw(G, planar_layout(G), **kwargs)
1883
+
1884
+
1885
+ def draw_forceatlas2(G, **kwargs):
1886
+ """Draw a networkx graph with forceatlas2 layout.
1887
+
1888
+ This is a convenience function equivalent to::
1889
+
1890
+ nx.draw(G, pos=nx.forceatlas2_layout(G), **kwargs)
1891
+
1892
+ Parameters
1893
+ ----------
1894
+ G : graph
1895
+ A networkx graph
1896
+
1897
+ kwargs : optional keywords
1898
+ See networkx.draw_networkx() for a description of optional keywords,
1899
+ with the exception of the pos parameter which is not used by this
1900
+ function.
1901
+ """
1902
+ draw(G, forceatlas2_layout(G), **kwargs)
1903
+
1904
+
1905
+ def apply_alpha(colors, alpha, elem_list, cmap=None, vmin=None, vmax=None):
1906
+ """Apply an alpha (or list of alphas) to the colors provided.
1907
+
1908
+ Parameters
1909
+ ----------
1910
+
1911
+ colors : color string or array of floats (default='r')
1912
+ Color of element. Can be a single color format string,
1913
+ or a sequence of colors with the same length as nodelist.
1914
+ If numeric values are specified they will be mapped to
1915
+ colors using the cmap and vmin,vmax parameters. See
1916
+ matplotlib.scatter for more details.
1917
+
1918
+ alpha : float or array of floats
1919
+ Alpha values for elements. This can be a single alpha value, in
1920
+ which case it will be applied to all the elements of color. Otherwise,
1921
+ if it is an array, the elements of alpha will be applied to the colors
1922
+ in order (cycling through alpha multiple times if necessary).
1923
+
1924
+ elem_list : array of networkx objects
1925
+ The list of elements which are being colored. These could be nodes,
1926
+ edges or labels.
1927
+
1928
+ cmap : matplotlib colormap
1929
+ Color map for use if colors is a list of floats corresponding to points
1930
+ on a color mapping.
1931
+
1932
+ vmin, vmax : float
1933
+ Minimum and maximum values for normalizing colors if a colormap is used
1934
+
1935
+ Returns
1936
+ -------
1937
+
1938
+ rgba_colors : numpy ndarray
1939
+ Array containing RGBA format values for each of the node colours.
1940
+
1941
+ """
1942
+ from itertools import cycle, islice
1943
+
1944
+ import matplotlib as mpl
1945
+ import matplotlib.cm # call as mpl.cm
1946
+ import matplotlib.colors # call as mpl.colors
1947
+ import numpy as np
1948
+
1949
+ # If we have been provided with a list of numbers as long as elem_list,
1950
+ # apply the color mapping.
1951
+ if len(colors) == len(elem_list) and isinstance(colors[0], Number):
1952
+ mapper = mpl.cm.ScalarMappable(cmap=cmap)
1953
+ mapper.set_clim(vmin, vmax)
1954
+ rgba_colors = mapper.to_rgba(colors)
1955
+ # Otherwise, convert colors to matplotlib's RGB using the colorConverter
1956
+ # object. These are converted to numpy ndarrays to be consistent with the
1957
+ # to_rgba method of ScalarMappable.
1958
+ else:
1959
+ try:
1960
+ rgba_colors = np.array([mpl.colors.colorConverter.to_rgba(colors)])
1961
+ except ValueError:
1962
+ rgba_colors = np.array(
1963
+ [mpl.colors.colorConverter.to_rgba(color) for color in colors]
1964
+ )
1965
+ # Set the final column of the rgba_colors to have the relevant alpha values
1966
+ try:
1967
+ # If alpha is longer than the number of colors, resize to the number of
1968
+ # elements. Also, if rgba_colors.size (the number of elements of
1969
+ # rgba_colors) is the same as the number of elements, resize the array,
1970
+ # to avoid it being interpreted as a colormap by scatter()
1971
+ if len(alpha) > len(rgba_colors) or rgba_colors.size == len(elem_list):
1972
+ rgba_colors = np.resize(rgba_colors, (len(elem_list), 4))
1973
+ rgba_colors[1:, 0] = rgba_colors[0, 0]
1974
+ rgba_colors[1:, 1] = rgba_colors[0, 1]
1975
+ rgba_colors[1:, 2] = rgba_colors[0, 2]
1976
+ rgba_colors[:, 3] = list(islice(cycle(alpha), len(rgba_colors)))
1977
+ except TypeError:
1978
+ rgba_colors[:, -1] = alpha
1979
+ return rgba_colors
falcon/lib/python3.10/site-packages/networkx/drawing/tests/__init__.py ADDED
File without changes
falcon/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (174 Bytes). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_agraph.cpython-310.pyc ADDED
Binary file (9.74 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_latex.cpython-310.pyc ADDED
Binary file (7.37 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_layout.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pydot.cpython-310.pyc ADDED
Binary file (4.34 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/tests/__pycache__/test_pylab.cpython-310.pyc ADDED
Binary file (31 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/drawing/tests/test_agraph.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for PyGraphviz interface."""
2
+
3
+ import warnings
4
+
5
+ import pytest
6
+
7
+ pygraphviz = pytest.importorskip("pygraphviz")
8
+
9
+
10
+ import networkx as nx
11
+ from networkx.utils import edges_equal, graphs_equal, nodes_equal
12
+
13
+
14
+ class TestAGraph:
15
+ def build_graph(self, G):
16
+ edges = [("A", "B"), ("A", "C"), ("A", "C"), ("B", "C"), ("A", "D")]
17
+ G.add_edges_from(edges)
18
+ G.add_node("E")
19
+ G.graph["metal"] = "bronze"
20
+ return G
21
+
22
+ def assert_equal(self, G1, G2):
23
+ assert nodes_equal(G1.nodes(), G2.nodes())
24
+ assert edges_equal(G1.edges(), G2.edges())
25
+ assert G1.graph["metal"] == G2.graph["metal"]
26
+
27
+ @pytest.mark.parametrize(
28
+ "G", (nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph())
29
+ )
30
+ def test_agraph_roundtripping(self, G, tmp_path):
31
+ G = self.build_graph(G)
32
+ A = nx.nx_agraph.to_agraph(G)
33
+ H = nx.nx_agraph.from_agraph(A)
34
+ self.assert_equal(G, H)
35
+
36
+ fname = tmp_path / "test.dot"
37
+ nx.drawing.nx_agraph.write_dot(H, fname)
38
+ Hin = nx.nx_agraph.read_dot(fname)
39
+ self.assert_equal(H, Hin)
40
+
41
+ fname = tmp_path / "fh_test.dot"
42
+ with open(fname, "w") as fh:
43
+ nx.drawing.nx_agraph.write_dot(H, fh)
44
+
45
+ with open(fname) as fh:
46
+ Hin = nx.nx_agraph.read_dot(fh)
47
+ self.assert_equal(H, Hin)
48
+
49
+ def test_from_agraph_name(self):
50
+ G = nx.Graph(name="test")
51
+ A = nx.nx_agraph.to_agraph(G)
52
+ H = nx.nx_agraph.from_agraph(A)
53
+ assert G.name == "test"
54
+
55
+ @pytest.mark.parametrize(
56
+ "graph_class", (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
57
+ )
58
+ def test_from_agraph_create_using(self, graph_class):
59
+ G = nx.path_graph(3)
60
+ A = nx.nx_agraph.to_agraph(G)
61
+ H = nx.nx_agraph.from_agraph(A, create_using=graph_class)
62
+ assert isinstance(H, graph_class)
63
+
64
+ def test_from_agraph_named_edges(self):
65
+ # Create an AGraph from an existing (non-multi) Graph
66
+ G = nx.Graph()
67
+ G.add_nodes_from([0, 1])
68
+ A = nx.nx_agraph.to_agraph(G)
69
+ # Add edge (+ name, given by key) to the AGraph
70
+ A.add_edge(0, 1, key="foo")
71
+ # Verify a.name roundtrips out to 'key' in from_agraph
72
+ H = nx.nx_agraph.from_agraph(A)
73
+ assert isinstance(H, nx.Graph)
74
+ assert ("0", "1", {"key": "foo"}) in H.edges(data=True)
75
+
76
+ def test_to_agraph_with_nodedata(self):
77
+ G = nx.Graph()
78
+ G.add_node(1, color="red")
79
+ A = nx.nx_agraph.to_agraph(G)
80
+ assert dict(A.nodes()[0].attr) == {"color": "red"}
81
+
82
+ @pytest.mark.parametrize("graph_class", (nx.Graph, nx.MultiGraph))
83
+ def test_to_agraph_with_edgedata(self, graph_class):
84
+ G = graph_class()
85
+ G.add_nodes_from([0, 1])
86
+ G.add_edge(0, 1, color="yellow")
87
+ A = nx.nx_agraph.to_agraph(G)
88
+ assert dict(A.edges()[0].attr) == {"color": "yellow"}
89
+
90
+ def test_view_pygraphviz_path(self, tmp_path):
91
+ G = nx.complete_graph(3)
92
+ input_path = str(tmp_path / "graph.png")
93
+ out_path, A = nx.nx_agraph.view_pygraphviz(G, path=input_path, show=False)
94
+ assert out_path == input_path
95
+ # Ensure file is not empty
96
+ with open(input_path, "rb") as fh:
97
+ data = fh.read()
98
+ assert len(data) > 0
99
+
100
+ def test_view_pygraphviz_file_suffix(self, tmp_path):
101
+ G = nx.complete_graph(3)
102
+ path, A = nx.nx_agraph.view_pygraphviz(G, suffix=1, show=False)
103
+ assert path[-6:] == "_1.png"
104
+
105
+ def test_view_pygraphviz(self):
106
+ G = nx.Graph() # "An empty graph cannot be drawn."
107
+ pytest.raises(nx.NetworkXException, nx.nx_agraph.view_pygraphviz, G)
108
+ G = nx.barbell_graph(4, 6)
109
+ nx.nx_agraph.view_pygraphviz(G, show=False)
110
+
111
+ def test_view_pygraphviz_edgelabel(self):
112
+ G = nx.Graph()
113
+ G.add_edge(1, 2, weight=7)
114
+ G.add_edge(2, 3, weight=8)
115
+ path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="weight", show=False)
116
+ for edge in A.edges():
117
+ assert edge.attr["weight"] in ("7", "8")
118
+
119
+ def test_view_pygraphviz_callable_edgelabel(self):
120
+ G = nx.complete_graph(3)
121
+
122
+ def foo_label(data):
123
+ return "foo"
124
+
125
+ path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel=foo_label, show=False)
126
+ for edge in A.edges():
127
+ assert edge.attr["label"] == "foo"
128
+
129
+ def test_view_pygraphviz_multigraph_edgelabels(self):
130
+ G = nx.MultiGraph()
131
+ G.add_edge(0, 1, key=0, name="left_fork")
132
+ G.add_edge(0, 1, key=1, name="right_fork")
133
+ path, A = nx.nx_agraph.view_pygraphviz(G, edgelabel="name", show=False)
134
+ edges = A.edges()
135
+ assert len(edges) == 2
136
+ for edge in edges:
137
+ assert edge.attr["label"].strip() in ("left_fork", "right_fork")
138
+
139
+ def test_graph_with_reserved_keywords(self):
140
+ # test attribute/keyword clash case for #1582
141
+ # node: n
142
+ # edges: u,v
143
+ G = nx.Graph()
144
+ G = self.build_graph(G)
145
+ G.nodes["E"]["n"] = "keyword"
146
+ G.edges[("A", "B")]["u"] = "keyword"
147
+ G.edges[("A", "B")]["v"] = "keyword"
148
+ A = nx.nx_agraph.to_agraph(G)
149
+
150
+ def test_view_pygraphviz_no_added_attrs_to_input(self):
151
+ G = nx.complete_graph(2)
152
+ path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
153
+ assert G.graph == {}
154
+
155
+ @pytest.mark.xfail(reason="known bug in clean_attrs")
156
+ def test_view_pygraphviz_leaves_input_graph_unmodified(self):
157
+ G = nx.complete_graph(2)
158
+ # Add entries to graph dict that to_agraph handles specially
159
+ G.graph["node"] = {"width": "0.80"}
160
+ G.graph["edge"] = {"fontsize": "14"}
161
+ path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
162
+ assert G.graph == {"node": {"width": "0.80"}, "edge": {"fontsize": "14"}}
163
+
164
+ def test_graph_with_AGraph_attrs(self):
165
+ G = nx.complete_graph(2)
166
+ # Add entries to graph dict that to_agraph handles specially
167
+ G.graph["node"] = {"width": "0.80"}
168
+ G.graph["edge"] = {"fontsize": "14"}
169
+ path, A = nx.nx_agraph.view_pygraphviz(G, show=False)
170
+ # Ensure user-specified values are not lost
171
+ assert dict(A.node_attr)["width"] == "0.80"
172
+ assert dict(A.edge_attr)["fontsize"] == "14"
173
+
174
+ def test_round_trip_empty_graph(self):
175
+ G = nx.Graph()
176
+ A = nx.nx_agraph.to_agraph(G)
177
+ H = nx.nx_agraph.from_agraph(A)
178
+ # assert graphs_equal(G, H)
179
+ AA = nx.nx_agraph.to_agraph(H)
180
+ HH = nx.nx_agraph.from_agraph(AA)
181
+ assert graphs_equal(H, HH)
182
+ G.graph["graph"] = {}
183
+ G.graph["node"] = {}
184
+ G.graph["edge"] = {}
185
+ assert graphs_equal(G, HH)
186
+
187
+ @pytest.mark.xfail(reason="integer->string node conversion in round trip")
188
+ def test_round_trip_integer_nodes(self):
189
+ G = nx.complete_graph(3)
190
+ A = nx.nx_agraph.to_agraph(G)
191
+ H = nx.nx_agraph.from_agraph(A)
192
+ assert graphs_equal(G, H)
193
+
194
+ def test_graphviz_alias(self):
195
+ G = self.build_graph(nx.Graph())
196
+ pos_graphviz = nx.nx_agraph.graphviz_layout(G)
197
+ pos_pygraphviz = nx.nx_agraph.pygraphviz_layout(G)
198
+ assert pos_graphviz == pos_pygraphviz
199
+
200
+ @pytest.mark.parametrize("root", range(5))
201
+ def test_pygraphviz_layout_root(self, root):
202
+ # NOTE: test depends on layout prog being deterministic
203
+ G = nx.complete_graph(5)
204
+ A = nx.nx_agraph.to_agraph(G)
205
+ # Get layout with root arg is not None
206
+ pygv_layout = nx.nx_agraph.pygraphviz_layout(G, prog="circo", root=root)
207
+ # Equivalent layout directly on AGraph
208
+ A.layout(args=f"-Groot={root}", prog="circo")
209
+ # Parse AGraph layout
210
+ a1_pos = tuple(float(v) for v in dict(A.get_node("1").attr)["pos"].split(","))
211
+ assert pygv_layout[1] == a1_pos
212
+
213
+ def test_2d_layout(self):
214
+ G = nx.Graph()
215
+ G = self.build_graph(G)
216
+ G.graph["dimen"] = 2
217
+ pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato")
218
+ pos = list(pos.values())
219
+ assert len(pos) == 5
220
+ assert len(pos[0]) == 2
221
+
222
+ def test_3d_layout(self):
223
+ G = nx.Graph()
224
+ G = self.build_graph(G)
225
+ G.graph["dimen"] = 3
226
+ pos = nx.nx_agraph.pygraphviz_layout(G, prog="neato")
227
+ pos = list(pos.values())
228
+ assert len(pos) == 5
229
+ assert len(pos[0]) == 3
230
+
231
+ def test_no_warnings_raised(self):
232
+ # Test that no warnings are raised when Networkx graph
233
+ # is converted to Pygraphviz graph and 'pos'
234
+ # attribute is given
235
+ G = nx.Graph()
236
+ G.add_node(0, pos=(0, 0))
237
+ G.add_node(1, pos=(1, 1))
238
+ A = nx.nx_agraph.to_agraph(G)
239
+ with warnings.catch_warnings(record=True) as record:
240
+ A.layout()
241
+ assert len(record) == 0
falcon/lib/python3.10/site-packages/networkx/drawing/tests/test_latex.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ def test_tikz_attributes():
7
+ G = nx.path_graph(4, create_using=nx.DiGraph)
8
+ pos = {n: (n, n) for n in G}
9
+
10
+ G.add_edge(0, 0)
11
+ G.edges[(0, 0)]["label"] = "Loop"
12
+ G.edges[(0, 0)]["label_options"] = "midway"
13
+
14
+ G.nodes[0]["style"] = "blue"
15
+ G.nodes[1]["style"] = "line width=3,draw"
16
+ G.nodes[2]["style"] = "circle,draw,blue!50"
17
+ G.nodes[3]["label"] = "Stop"
18
+ G.edges[(0, 1)]["label"] = "1st Step"
19
+ G.edges[(0, 1)]["label_options"] = "near end"
20
+ G.edges[(2, 3)]["label"] = "3rd Step"
21
+ G.edges[(2, 3)]["label_options"] = "near start"
22
+ G.edges[(2, 3)]["style"] = "bend left,green"
23
+ G.edges[(1, 2)]["label"] = "2nd"
24
+ G.edges[(1, 2)]["label_options"] = "pos=0.5"
25
+ G.edges[(1, 2)]["style"] = ">->,bend right,line width=3,green!90"
26
+
27
+ output_tex = nx.to_latex(
28
+ G,
29
+ pos=pos,
30
+ as_document=False,
31
+ tikz_options="[scale=3]",
32
+ node_options="style",
33
+ edge_options="style",
34
+ node_label="label",
35
+ edge_label="label",
36
+ edge_label_options="label_options",
37
+ )
38
+ expected_tex = r"""\begin{figure}
39
+ \begin{tikzpicture}[scale=3]
40
+ \draw
41
+ (0, 0) node[blue] (0){0}
42
+ (1, 1) node[line width=3,draw] (1){1}
43
+ (2, 2) node[circle,draw,blue!50] (2){2}
44
+ (3, 3) node (3){Stop};
45
+ \begin{scope}[->]
46
+ \draw (0) to node[near end] {1st Step} (1);
47
+ \draw[loop,] (0) to node[midway] {Loop} (0);
48
+ \draw[>->,bend right,line width=3,green!90] (1) to node[pos=0.5] {2nd} (2);
49
+ \draw[bend left,green] (2) to node[near start] {3rd Step} (3);
50
+ \end{scope}
51
+ \end{tikzpicture}
52
+ \end{figure}"""
53
+
54
+ assert output_tex == expected_tex
55
+ # print(output_tex)
56
+ # # Pretty way to assert that A.to_document() == expected_tex
57
+ # content_same = True
58
+ # for aa, bb in zip(expected_tex.split("\n"), output_tex.split("\n")):
59
+ # if aa != bb:
60
+ # content_same = False
61
+ # print(f"-{aa}|\n+{bb}|")
62
+ # assert content_same
63
+
64
+
65
+ def test_basic_multiple_graphs():
66
+ H1 = nx.path_graph(4)
67
+ H2 = nx.complete_graph(4)
68
+ H3 = nx.path_graph(8)
69
+ H4 = nx.complete_graph(8)
70
+ captions = [
71
+ "Path on 4 nodes",
72
+ "Complete graph on 4 nodes",
73
+ "Path on 8 nodes",
74
+ "Complete graph on 8 nodes",
75
+ ]
76
+ labels = ["fig2a", "fig2b", "fig2c", "fig2d"]
77
+ latex_code = nx.to_latex(
78
+ [H1, H2, H3, H4],
79
+ n_rows=2,
80
+ sub_captions=captions,
81
+ sub_labels=labels,
82
+ )
83
+ # print(latex_code)
84
+ assert "begin{document}" in latex_code
85
+ assert "begin{figure}" in latex_code
86
+ assert latex_code.count("begin{subfigure}") == 4
87
+ assert latex_code.count("tikzpicture") == 8
88
+ assert latex_code.count("[-]") == 4
89
+
90
+
91
+ def test_basic_tikz():
92
+ expected_tex = r"""\documentclass{report}
93
+ \usepackage{tikz}
94
+ \usepackage{subcaption}
95
+
96
+ \begin{document}
97
+ \begin{figure}
98
+ \begin{subfigure}{0.5\textwidth}
99
+ \begin{tikzpicture}[scale=2]
100
+ \draw[gray!90]
101
+ (0.749, 0.702) node[red!90] (0){0}
102
+ (1.0, -0.014) node[red!90] (1){1}
103
+ (-0.777, -0.705) node (2){2}
104
+ (-0.984, 0.042) node (3){3}
105
+ (-0.028, 0.375) node[cyan!90] (4){4}
106
+ (-0.412, 0.888) node (5){5}
107
+ (0.448, -0.856) node (6){6}
108
+ (0.003, -0.431) node[cyan!90] (7){7};
109
+ \begin{scope}[->,gray!90]
110
+ \draw (0) to (4);
111
+ \draw (0) to (5);
112
+ \draw (0) to (6);
113
+ \draw (0) to (7);
114
+ \draw (1) to (4);
115
+ \draw (1) to (5);
116
+ \draw (1) to (6);
117
+ \draw (1) to (7);
118
+ \draw (2) to (4);
119
+ \draw (2) to (5);
120
+ \draw (2) to (6);
121
+ \draw (2) to (7);
122
+ \draw (3) to (4);
123
+ \draw (3) to (5);
124
+ \draw (3) to (6);
125
+ \draw (3) to (7);
126
+ \end{scope}
127
+ \end{tikzpicture}
128
+ \caption{My tikz number 1 of 2}\label{tikz_1_2}
129
+ \end{subfigure}
130
+ \begin{subfigure}{0.5\textwidth}
131
+ \begin{tikzpicture}[scale=2]
132
+ \draw[gray!90]
133
+ (0.749, 0.702) node[green!90] (0){0}
134
+ (1.0, -0.014) node[green!90] (1){1}
135
+ (-0.777, -0.705) node (2){2}
136
+ (-0.984, 0.042) node (3){3}
137
+ (-0.028, 0.375) node[purple!90] (4){4}
138
+ (-0.412, 0.888) node (5){5}
139
+ (0.448, -0.856) node (6){6}
140
+ (0.003, -0.431) node[purple!90] (7){7};
141
+ \begin{scope}[->,gray!90]
142
+ \draw (0) to (4);
143
+ \draw (0) to (5);
144
+ \draw (0) to (6);
145
+ \draw (0) to (7);
146
+ \draw (1) to (4);
147
+ \draw (1) to (5);
148
+ \draw (1) to (6);
149
+ \draw (1) to (7);
150
+ \draw (2) to (4);
151
+ \draw (2) to (5);
152
+ \draw (2) to (6);
153
+ \draw (2) to (7);
154
+ \draw (3) to (4);
155
+ \draw (3) to (5);
156
+ \draw (3) to (6);
157
+ \draw (3) to (7);
158
+ \end{scope}
159
+ \end{tikzpicture}
160
+ \caption{My tikz number 2 of 2}\label{tikz_2_2}
161
+ \end{subfigure}
162
+ \caption{A graph generated with python and latex.}
163
+ \end{figure}
164
+ \end{document}"""
165
+
166
+ edges = [
167
+ (0, 4),
168
+ (0, 5),
169
+ (0, 6),
170
+ (0, 7),
171
+ (1, 4),
172
+ (1, 5),
173
+ (1, 6),
174
+ (1, 7),
175
+ (2, 4),
176
+ (2, 5),
177
+ (2, 6),
178
+ (2, 7),
179
+ (3, 4),
180
+ (3, 5),
181
+ (3, 6),
182
+ (3, 7),
183
+ ]
184
+ G = nx.DiGraph()
185
+ G.add_nodes_from(range(8))
186
+ G.add_edges_from(edges)
187
+ pos = {
188
+ 0: (0.7490296171687696, 0.702353520257394),
189
+ 1: (1.0, -0.014221357723796535),
190
+ 2: (-0.7765783344161441, -0.7054170966808919),
191
+ 3: (-0.9842690223417624, 0.04177547602465483),
192
+ 4: (-0.02768523817180917, 0.3745724439551441),
193
+ 5: (-0.41154855146767433, 0.8880106515525136),
194
+ 6: (0.44780153389148264, -0.8561492709269164),
195
+ 7: (0.0032499953371383505, -0.43092436645809945),
196
+ }
197
+
198
+ rc_node_color = {0: "red!90", 1: "red!90", 4: "cyan!90", 7: "cyan!90"}
199
+ gp_node_color = {0: "green!90", 1: "green!90", 4: "purple!90", 7: "purple!90"}
200
+
201
+ H = G.copy()
202
+ nx.set_node_attributes(G, rc_node_color, "color")
203
+ nx.set_node_attributes(H, gp_node_color, "color")
204
+
205
+ sub_captions = ["My tikz number 1 of 2", "My tikz number 2 of 2"]
206
+ sub_labels = ["tikz_1_2", "tikz_2_2"]
207
+
208
+ output_tex = nx.to_latex(
209
+ [G, H],
210
+ [pos, pos],
211
+ tikz_options="[scale=2]",
212
+ default_node_options="gray!90",
213
+ default_edge_options="gray!90",
214
+ node_options="color",
215
+ sub_captions=sub_captions,
216
+ sub_labels=sub_labels,
217
+ caption="A graph generated with python and latex.",
218
+ n_rows=2,
219
+ as_document=True,
220
+ )
221
+
222
+ assert output_tex == expected_tex
223
+ # print(output_tex)
224
+ # # Pretty way to assert that A.to_document() == expected_tex
225
+ # content_same = True
226
+ # for aa, bb in zip(expected_tex.split("\n"), output_tex.split("\n")):
227
+ # if aa != bb:
228
+ # content_same = False
229
+ # print(f"-{aa}|\n+{bb}|")
230
+ # assert content_same
231
+
232
+
233
+ def test_exception_pos_single_graph(to_latex=nx.to_latex):
234
+ # smoke test that pos can be a string
235
+ G = nx.path_graph(4)
236
+ to_latex(G, pos="pos")
237
+
238
+ # must include all nodes
239
+ pos = {0: (1, 2), 1: (0, 1), 2: (2, 1)}
240
+ with pytest.raises(nx.NetworkXError):
241
+ to_latex(G, pos)
242
+
243
+ # must have 2 values
244
+ pos[3] = (1, 2, 3)
245
+ with pytest.raises(nx.NetworkXError):
246
+ to_latex(G, pos)
247
+ pos[3] = 2
248
+ with pytest.raises(nx.NetworkXError):
249
+ to_latex(G, pos)
250
+
251
+ # check that passes with 2 values
252
+ pos[3] = (3, 2)
253
+ to_latex(G, pos)
254
+
255
+
256
+ def test_exception_multiple_graphs(to_latex=nx.to_latex):
257
+ G = nx.path_graph(3)
258
+ pos_bad = {0: (1, 2), 1: (0, 1)}
259
+ pos_OK = {0: (1, 2), 1: (0, 1), 2: (2, 1)}
260
+ fourG = [G, G, G, G]
261
+ fourpos = [pos_OK, pos_OK, pos_OK, pos_OK]
262
+
263
+ # input single dict to use for all graphs
264
+ to_latex(fourG, pos_OK)
265
+ with pytest.raises(nx.NetworkXError):
266
+ to_latex(fourG, pos_bad)
267
+
268
+ # input list of dicts to use for all graphs
269
+ to_latex(fourG, fourpos)
270
+ with pytest.raises(nx.NetworkXError):
271
+ to_latex(fourG, [pos_bad, pos_bad, pos_bad, pos_bad])
272
+
273
+ # every pos dict must include all nodes
274
+ with pytest.raises(nx.NetworkXError):
275
+ to_latex(fourG, [pos_OK, pos_OK, pos_bad, pos_OK])
276
+
277
+ # test sub_captions and sub_labels (len must match Gbunch)
278
+ with pytest.raises(nx.NetworkXError):
279
+ to_latex(fourG, fourpos, sub_captions=["hi", "hi"])
280
+
281
+ with pytest.raises(nx.NetworkXError):
282
+ to_latex(fourG, fourpos, sub_labels=["hi", "hi"])
283
+
284
+ # all pass
285
+ to_latex(fourG, fourpos, sub_captions=["hi"] * 4, sub_labels=["lbl"] * 4)
286
+
287
+
288
+ def test_exception_multigraph():
289
+ G = nx.path_graph(4, create_using=nx.MultiGraph)
290
+ G.add_edge(1, 2)
291
+ with pytest.raises(nx.NetworkXNotImplemented):
292
+ nx.to_latex(G)
falcon/lib/python3.10/site-packages/networkx/drawing/tests/test_layout.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for layout functions."""
2
+
3
+ import pytest
4
+
5
+ import networkx as nx
6
+
7
+ np = pytest.importorskip("numpy")
8
+ pytest.importorskip("scipy")
9
+
10
+
11
+ class TestLayout:
12
+ @classmethod
13
+ def setup_class(cls):
14
+ cls.Gi = nx.grid_2d_graph(5, 5)
15
+ cls.Gs = nx.Graph()
16
+ nx.add_path(cls.Gs, "abcdef")
17
+ cls.bigG = nx.grid_2d_graph(25, 25) # > 500 nodes for sparse
18
+
19
+ def test_spring_fixed_without_pos(self):
20
+ G = nx.path_graph(4)
21
+ pytest.raises(ValueError, nx.spring_layout, G, fixed=[0])
22
+ pos = {0: (1, 1), 2: (0, 0)}
23
+ pytest.raises(ValueError, nx.spring_layout, G, fixed=[0, 1], pos=pos)
24
+ nx.spring_layout(G, fixed=[0, 2], pos=pos) # No ValueError
25
+
26
+ def test_spring_init_pos(self):
27
+ # Tests GH #2448
28
+ import math
29
+
30
+ G = nx.Graph()
31
+ G.add_edges_from([(0, 1), (1, 2), (2, 0), (2, 3)])
32
+
33
+ init_pos = {0: (0.0, 0.0)}
34
+ fixed_pos = [0]
35
+ pos = nx.fruchterman_reingold_layout(G, pos=init_pos, fixed=fixed_pos)
36
+ has_nan = any(math.isnan(c) for coords in pos.values() for c in coords)
37
+ assert not has_nan, "values should not be nan"
38
+
39
+ def test_smoke_empty_graph(self):
40
+ G = []
41
+ nx.random_layout(G)
42
+ nx.circular_layout(G)
43
+ nx.planar_layout(G)
44
+ nx.spring_layout(G)
45
+ nx.fruchterman_reingold_layout(G)
46
+ nx.spectral_layout(G)
47
+ nx.shell_layout(G)
48
+ nx.bipartite_layout(G, G)
49
+ nx.spiral_layout(G)
50
+ nx.multipartite_layout(G)
51
+ nx.kamada_kawai_layout(G)
52
+
53
+ def test_smoke_int(self):
54
+ G = self.Gi
55
+ nx.random_layout(G)
56
+ nx.circular_layout(G)
57
+ nx.planar_layout(G)
58
+ nx.spring_layout(G)
59
+ nx.forceatlas2_layout(G)
60
+ nx.fruchterman_reingold_layout(G)
61
+ nx.fruchterman_reingold_layout(self.bigG)
62
+ nx.spectral_layout(G)
63
+ nx.spectral_layout(G.to_directed())
64
+ nx.spectral_layout(self.bigG)
65
+ nx.spectral_layout(self.bigG.to_directed())
66
+ nx.shell_layout(G)
67
+ nx.spiral_layout(G)
68
+ nx.kamada_kawai_layout(G)
69
+ nx.kamada_kawai_layout(G, dim=1)
70
+ nx.kamada_kawai_layout(G, dim=3)
71
+ nx.arf_layout(G)
72
+
73
+ def test_smoke_string(self):
74
+ G = self.Gs
75
+ nx.random_layout(G)
76
+ nx.circular_layout(G)
77
+ nx.planar_layout(G)
78
+ nx.spring_layout(G)
79
+ nx.forceatlas2_layout(G)
80
+ nx.fruchterman_reingold_layout(G)
81
+ nx.spectral_layout(G)
82
+ nx.shell_layout(G)
83
+ nx.spiral_layout(G)
84
+ nx.kamada_kawai_layout(G)
85
+ nx.kamada_kawai_layout(G, dim=1)
86
+ nx.kamada_kawai_layout(G, dim=3)
87
+ nx.arf_layout(G)
88
+
89
+ def check_scale_and_center(self, pos, scale, center):
90
+ center = np.array(center)
91
+ low = center - scale
92
+ hi = center + scale
93
+ vpos = np.array(list(pos.values()))
94
+ length = vpos.max(0) - vpos.min(0)
95
+ assert (length <= 2 * scale).all()
96
+ assert (vpos >= low).all()
97
+ assert (vpos <= hi).all()
98
+
99
+ def test_scale_and_center_arg(self):
100
+ sc = self.check_scale_and_center
101
+ c = (4, 5)
102
+ G = nx.complete_graph(9)
103
+ G.add_node(9)
104
+ sc(nx.random_layout(G, center=c), scale=0.5, center=(4.5, 5.5))
105
+ # rest can have 2*scale length: [-scale, scale]
106
+ sc(nx.spring_layout(G, scale=2, center=c), scale=2, center=c)
107
+ sc(nx.spectral_layout(G, scale=2, center=c), scale=2, center=c)
108
+ sc(nx.circular_layout(G, scale=2, center=c), scale=2, center=c)
109
+ sc(nx.shell_layout(G, scale=2, center=c), scale=2, center=c)
110
+ sc(nx.spiral_layout(G, scale=2, center=c), scale=2, center=c)
111
+ sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c)
112
+
113
+ c = (2, 3, 5)
114
+ sc(nx.kamada_kawai_layout(G, dim=3, scale=2, center=c), scale=2, center=c)
115
+
116
+ def test_planar_layout_non_planar_input(self):
117
+ G = nx.complete_graph(9)
118
+ pytest.raises(nx.NetworkXException, nx.planar_layout, G)
119
+
120
+ def test_smoke_planar_layout_embedding_input(self):
121
+ embedding = nx.PlanarEmbedding()
122
+ embedding.set_data({0: [1, 2], 1: [0, 2], 2: [0, 1]})
123
+ nx.planar_layout(embedding)
124
+
125
+ def test_default_scale_and_center(self):
126
+ sc = self.check_scale_and_center
127
+ c = (0, 0)
128
+ G = nx.complete_graph(9)
129
+ G.add_node(9)
130
+ sc(nx.random_layout(G), scale=0.5, center=(0.5, 0.5))
131
+ sc(nx.spring_layout(G), scale=1, center=c)
132
+ sc(nx.spectral_layout(G), scale=1, center=c)
133
+ sc(nx.circular_layout(G), scale=1, center=c)
134
+ sc(nx.shell_layout(G), scale=1, center=c)
135
+ sc(nx.spiral_layout(G), scale=1, center=c)
136
+ sc(nx.kamada_kawai_layout(G), scale=1, center=c)
137
+
138
+ c = (0, 0, 0)
139
+ sc(nx.kamada_kawai_layout(G, dim=3), scale=1, center=c)
140
+
141
+ def test_circular_planar_and_shell_dim_error(self):
142
+ G = nx.path_graph(4)
143
+ pytest.raises(ValueError, nx.circular_layout, G, dim=1)
144
+ pytest.raises(ValueError, nx.shell_layout, G, dim=1)
145
+ pytest.raises(ValueError, nx.shell_layout, G, dim=3)
146
+ pytest.raises(ValueError, nx.planar_layout, G, dim=1)
147
+ pytest.raises(ValueError, nx.planar_layout, G, dim=3)
148
+
149
+ def test_adjacency_interface_numpy(self):
150
+ A = nx.to_numpy_array(self.Gs)
151
+ pos = nx.drawing.layout._fruchterman_reingold(A)
152
+ assert pos.shape == (6, 2)
153
+ pos = nx.drawing.layout._fruchterman_reingold(A, dim=3)
154
+ assert pos.shape == (6, 3)
155
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
156
+ assert pos.shape == (6, 2)
157
+
158
+ def test_adjacency_interface_scipy(self):
159
+ A = nx.to_scipy_sparse_array(self.Gs, dtype="d")
160
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A)
161
+ assert pos.shape == (6, 2)
162
+ pos = nx.drawing.layout._sparse_spectral(A)
163
+ assert pos.shape == (6, 2)
164
+ pos = nx.drawing.layout._sparse_fruchterman_reingold(A, dim=3)
165
+ assert pos.shape == (6, 3)
166
+
167
+ def test_single_nodes(self):
168
+ G = nx.path_graph(1)
169
+ vpos = nx.shell_layout(G)
170
+ assert not vpos[0].any()
171
+ G = nx.path_graph(4)
172
+ vpos = nx.shell_layout(G, [[0], [1, 2], [3]])
173
+ assert not vpos[0].any()
174
+ assert vpos[3].any() # ensure node 3 not at origin (#3188)
175
+ assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753)
176
+ vpos = nx.shell_layout(G, [[0], [1, 2], [3]], rotate=0)
177
+ assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753)
178
+
179
+ def test_smoke_initial_pos_forceatlas2(self):
180
+ pos = nx.circular_layout(self.Gi)
181
+ npos = nx.forceatlas2_layout(self.Gi, pos=pos)
182
+
183
+ def test_smoke_initial_pos_fruchterman_reingold(self):
184
+ pos = nx.circular_layout(self.Gi)
185
+ npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos)
186
+
187
+ def test_smoke_initial_pos_arf(self):
188
+ pos = nx.circular_layout(self.Gi)
189
+ npos = nx.arf_layout(self.Gi, pos=pos)
190
+
191
+ def test_fixed_node_fruchterman_reingold(self):
192
+ # Dense version (numpy based)
193
+ pos = nx.circular_layout(self.Gi)
194
+ npos = nx.spring_layout(self.Gi, pos=pos, fixed=[(0, 0)])
195
+ assert tuple(pos[(0, 0)]) == tuple(npos[(0, 0)])
196
+ # Sparse version (scipy based)
197
+ pos = nx.circular_layout(self.bigG)
198
+ npos = nx.spring_layout(self.bigG, pos=pos, fixed=[(0, 0)])
199
+ for axis in range(2):
200
+ assert pos[(0, 0)][axis] == pytest.approx(npos[(0, 0)][axis], abs=1e-7)
201
+
202
+ def test_center_parameter(self):
203
+ G = nx.path_graph(1)
204
+ nx.random_layout(G, center=(1, 1))
205
+ vpos = nx.circular_layout(G, center=(1, 1))
206
+ assert tuple(vpos[0]) == (1, 1)
207
+ vpos = nx.planar_layout(G, center=(1, 1))
208
+ assert tuple(vpos[0]) == (1, 1)
209
+ vpos = nx.spring_layout(G, center=(1, 1))
210
+ assert tuple(vpos[0]) == (1, 1)
211
+ vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
212
+ assert tuple(vpos[0]) == (1, 1)
213
+ vpos = nx.spectral_layout(G, center=(1, 1))
214
+ assert tuple(vpos[0]) == (1, 1)
215
+ vpos = nx.shell_layout(G, center=(1, 1))
216
+ assert tuple(vpos[0]) == (1, 1)
217
+ vpos = nx.spiral_layout(G, center=(1, 1))
218
+ assert tuple(vpos[0]) == (1, 1)
219
+
220
+ def test_center_wrong_dimensions(self):
221
+ G = nx.path_graph(1)
222
+ assert id(nx.spring_layout) == id(nx.fruchterman_reingold_layout)
223
+ pytest.raises(ValueError, nx.random_layout, G, center=(1, 1, 1))
224
+ pytest.raises(ValueError, nx.circular_layout, G, center=(1, 1, 1))
225
+ pytest.raises(ValueError, nx.planar_layout, G, center=(1, 1, 1))
226
+ pytest.raises(ValueError, nx.spring_layout, G, center=(1, 1, 1))
227
+ pytest.raises(ValueError, nx.spring_layout, G, dim=3, center=(1, 1))
228
+ pytest.raises(ValueError, nx.spectral_layout, G, center=(1, 1, 1))
229
+ pytest.raises(ValueError, nx.spectral_layout, G, dim=3, center=(1, 1))
230
+ pytest.raises(ValueError, nx.shell_layout, G, center=(1, 1, 1))
231
+ pytest.raises(ValueError, nx.spiral_layout, G, center=(1, 1, 1))
232
+ pytest.raises(ValueError, nx.kamada_kawai_layout, G, center=(1, 1, 1))
233
+
234
+ def test_empty_graph(self):
235
+ G = nx.empty_graph()
236
+ vpos = nx.random_layout(G, center=(1, 1))
237
+ assert vpos == {}
238
+ vpos = nx.circular_layout(G, center=(1, 1))
239
+ assert vpos == {}
240
+ vpos = nx.planar_layout(G, center=(1, 1))
241
+ assert vpos == {}
242
+ vpos = nx.bipartite_layout(G, G)
243
+ assert vpos == {}
244
+ vpos = nx.spring_layout(G, center=(1, 1))
245
+ assert vpos == {}
246
+ vpos = nx.fruchterman_reingold_layout(G, center=(1, 1))
247
+ assert vpos == {}
248
+ vpos = nx.spectral_layout(G, center=(1, 1))
249
+ assert vpos == {}
250
+ vpos = nx.shell_layout(G, center=(1, 1))
251
+ assert vpos == {}
252
+ vpos = nx.spiral_layout(G, center=(1, 1))
253
+ assert vpos == {}
254
+ vpos = nx.multipartite_layout(G, center=(1, 1))
255
+ assert vpos == {}
256
+ vpos = nx.kamada_kawai_layout(G, center=(1, 1))
257
+ assert vpos == {}
258
+ vpos = nx.forceatlas2_layout(G)
259
+ assert vpos == {}
260
+ vpos = nx.arf_layout(G)
261
+ assert vpos == {}
262
+
263
+ def test_bipartite_layout(self):
264
+ G = nx.complete_bipartite_graph(3, 5)
265
+ top, bottom = nx.bipartite.sets(G)
266
+
267
+ vpos = nx.bipartite_layout(G, top)
268
+ assert len(vpos) == len(G)
269
+
270
+ top_x = vpos[list(top)[0]][0]
271
+ bottom_x = vpos[list(bottom)[0]][0]
272
+ for node in top:
273
+ assert vpos[node][0] == top_x
274
+ for node in bottom:
275
+ assert vpos[node][0] == bottom_x
276
+
277
+ vpos = nx.bipartite_layout(
278
+ G, top, align="horizontal", center=(2, 2), scale=2, aspect_ratio=1
279
+ )
280
+ assert len(vpos) == len(G)
281
+
282
+ top_y = vpos[list(top)[0]][1]
283
+ bottom_y = vpos[list(bottom)[0]][1]
284
+ for node in top:
285
+ assert vpos[node][1] == top_y
286
+ for node in bottom:
287
+ assert vpos[node][1] == bottom_y
288
+
289
+ pytest.raises(ValueError, nx.bipartite_layout, G, top, align="foo")
290
+
291
+ def test_multipartite_layout(self):
292
+ sizes = (0, 5, 7, 2, 8)
293
+ G = nx.complete_multipartite_graph(*sizes)
294
+
295
+ vpos = nx.multipartite_layout(G)
296
+ assert len(vpos) == len(G)
297
+
298
+ start = 0
299
+ for n in sizes:
300
+ end = start + n
301
+ assert all(vpos[start][0] == vpos[i][0] for i in range(start + 1, end))
302
+ start += n
303
+
304
+ vpos = nx.multipartite_layout(G, align="horizontal", scale=2, center=(2, 2))
305
+ assert len(vpos) == len(G)
306
+
307
+ start = 0
308
+ for n in sizes:
309
+ end = start + n
310
+ assert all(vpos[start][1] == vpos[i][1] for i in range(start + 1, end))
311
+ start += n
312
+
313
+ pytest.raises(ValueError, nx.multipartite_layout, G, align="foo")
314
+
315
+ def test_kamada_kawai_costfn_1d(self):
316
+ costfn = nx.drawing.layout._kamada_kawai_costfn
317
+
318
+ pos = np.array([4.0, 7.0])
319
+ invdist = 1 / np.array([[0.1, 2.0], [2.0, 0.3]])
320
+
321
+ cost, grad = costfn(pos, np, invdist, meanweight=0, dim=1)
322
+
323
+ assert cost == pytest.approx(((3 / 2.0 - 1) ** 2), abs=1e-7)
324
+ assert grad[0] == pytest.approx((-0.5), abs=1e-7)
325
+ assert grad[1] == pytest.approx(0.5, abs=1e-7)
326
+
327
+ def check_kamada_kawai_costfn(self, pos, invdist, meanwt, dim):
328
+ costfn = nx.drawing.layout._kamada_kawai_costfn
329
+
330
+ cost, grad = costfn(pos.ravel(), np, invdist, meanweight=meanwt, dim=dim)
331
+
332
+ expected_cost = 0.5 * meanwt * np.sum(np.sum(pos, axis=0) ** 2)
333
+ for i in range(pos.shape[0]):
334
+ for j in range(i + 1, pos.shape[0]):
335
+ diff = np.linalg.norm(pos[i] - pos[j])
336
+ expected_cost += (diff * invdist[i][j] - 1.0) ** 2
337
+
338
+ assert cost == pytest.approx(expected_cost, abs=1e-7)
339
+
340
+ dx = 1e-4
341
+ for nd in range(pos.shape[0]):
342
+ for dm in range(pos.shape[1]):
343
+ idx = nd * pos.shape[1] + dm
344
+ ps = pos.flatten()
345
+
346
+ ps[idx] += dx
347
+ cplus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0]
348
+
349
+ ps[idx] -= 2 * dx
350
+ cminus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0]
351
+
352
+ assert grad[idx] == pytest.approx((cplus - cminus) / (2 * dx), abs=1e-5)
353
+
354
+ def test_kamada_kawai_costfn(self):
355
+ invdist = 1 / np.array([[0.1, 2.1, 1.7], [2.1, 0.2, 0.6], [1.7, 0.6, 0.3]])
356
+ meanwt = 0.3
357
+
358
+ # 2d
359
+ pos = np.array([[1.3, -3.2], [2.7, -0.3], [5.1, 2.5]])
360
+
361
+ self.check_kamada_kawai_costfn(pos, invdist, meanwt, 2)
362
+
363
+ # 3d
364
+ pos = np.array([[0.9, 8.6, -8.7], [-10, -0.5, -7.1], [9.1, -8.1, 1.6]])
365
+
366
+ self.check_kamada_kawai_costfn(pos, invdist, meanwt, 3)
367
+
368
+ def test_spiral_layout(self):
369
+ G = self.Gs
370
+
371
+ # a lower value of resolution should result in a more compact layout
372
+ # intuitively, the total distance from the start and end nodes
373
+ # via each node in between (transiting through each) will be less,
374
+ # assuming rescaling does not occur on the computed node positions
375
+ pos_standard = np.array(list(nx.spiral_layout(G, resolution=0.35).values()))
376
+ pos_tighter = np.array(list(nx.spiral_layout(G, resolution=0.34).values()))
377
+ distances = np.linalg.norm(pos_standard[:-1] - pos_standard[1:], axis=1)
378
+ distances_tighter = np.linalg.norm(pos_tighter[:-1] - pos_tighter[1:], axis=1)
379
+ assert sum(distances) > sum(distances_tighter)
380
+
381
+ # return near-equidistant points after the first value if set to true
382
+ pos_equidistant = np.array(list(nx.spiral_layout(G, equidistant=True).values()))
383
+ distances_equidistant = np.linalg.norm(
384
+ pos_equidistant[:-1] - pos_equidistant[1:], axis=1
385
+ )
386
+ assert np.allclose(
387
+ distances_equidistant[1:], distances_equidistant[-1], atol=0.01
388
+ )
389
+
390
+ def test_spiral_layout_equidistant(self):
391
+ G = nx.path_graph(10)
392
+ pos = nx.spiral_layout(G, equidistant=True)
393
+ # Extract individual node positions as an array
394
+ p = np.array(list(pos.values()))
395
+ # Elementwise-distance between node positions
396
+ dist = np.linalg.norm(p[1:] - p[:-1], axis=1)
397
+ assert np.allclose(np.diff(dist), 0, atol=1e-3)
398
+
399
+ def test_forceatlas2_layout_partial_input_test(self):
400
+ # check whether partial pos input still returns a full proper position
401
+ G = self.Gs
402
+ node = nx.utils.arbitrary_element(G)
403
+ pos = nx.circular_layout(G)
404
+ del pos[node]
405
+ pos = nx.forceatlas2_layout(G, pos=pos)
406
+ assert len(pos) == len(G)
407
+
408
+ def test_rescale_layout_dict(self):
409
+ G = nx.empty_graph()
410
+ vpos = nx.random_layout(G, center=(1, 1))
411
+ assert nx.rescale_layout_dict(vpos) == {}
412
+
413
+ G = nx.empty_graph(2)
414
+ vpos = {0: (0.0, 0.0), 1: (1.0, 1.0)}
415
+ s_vpos = nx.rescale_layout_dict(vpos)
416
+ assert np.linalg.norm([sum(x) for x in zip(*s_vpos.values())]) < 1e-6
417
+
418
+ G = nx.empty_graph(3)
419
+ vpos = {0: (0, 0), 1: (1, 1), 2: (0.5, 0.5)}
420
+ s_vpos = nx.rescale_layout_dict(vpos)
421
+
422
+ expectation = {
423
+ 0: np.array((-1, -1)),
424
+ 1: np.array((1, 1)),
425
+ 2: np.array((0, 0)),
426
+ }
427
+ for k, v in expectation.items():
428
+ assert (s_vpos[k] == v).all()
429
+ s_vpos = nx.rescale_layout_dict(vpos, scale=2)
430
+ expectation = {
431
+ 0: np.array((-2, -2)),
432
+ 1: np.array((2, 2)),
433
+ 2: np.array((0, 0)),
434
+ }
435
+ for k, v in expectation.items():
436
+ assert (s_vpos[k] == v).all()
437
+
438
+ def test_arf_layout_partial_input_test(self):
439
+ # Checks whether partial pos input still returns a proper position.
440
+ G = self.Gs
441
+ node = nx.utils.arbitrary_element(G)
442
+ pos = nx.circular_layout(G)
443
+ del pos[node]
444
+ pos = nx.arf_layout(G, pos=pos)
445
+ assert len(pos) == len(G)
446
+
447
+ def test_arf_layout_negative_a_check(self):
448
+ """
449
+ Checks input parameters correctly raises errors. For example, `a` should be larger than 1
450
+ """
451
+ G = self.Gs
452
+ pytest.raises(ValueError, nx.arf_layout, G=G, a=-1)
453
+
454
+ def test_smoke_seed_input(self):
455
+ G = self.Gs
456
+ nx.random_layout(G, seed=42)
457
+ nx.spring_layout(G, seed=42)
458
+ nx.arf_layout(G, seed=42)
459
+ nx.forceatlas2_layout(G, seed=42)
460
+
461
+
462
+ def test_multipartite_layout_nonnumeric_partition_labels():
463
+ """See gh-5123."""
464
+ G = nx.Graph()
465
+ G.add_node(0, subset="s0")
466
+ G.add_node(1, subset="s0")
467
+ G.add_node(2, subset="s1")
468
+ G.add_node(3, subset="s1")
469
+ G.add_edges_from([(0, 2), (0, 3), (1, 2)])
470
+ pos = nx.multipartite_layout(G)
471
+ assert len(pos) == len(G)
472
+
473
+
474
+ def test_multipartite_layout_layer_order():
475
+ """Return the layers in sorted order if the layers of the multipartite
476
+ graph are sortable. See gh-5691"""
477
+ G = nx.Graph()
478
+ node_group = dict(zip(("a", "b", "c", "d", "e"), (2, 3, 1, 2, 4)))
479
+ for node, layer in node_group.items():
480
+ G.add_node(node, subset=layer)
481
+
482
+ # Horizontal alignment, therefore y-coord determines layers
483
+ pos = nx.multipartite_layout(G, align="horizontal")
484
+
485
+ layers = nx.utils.groups(node_group)
486
+ pos_from_layers = nx.multipartite_layout(G, align="horizontal", subset_key=layers)
487
+ for (n1, p1), (n2, p2) in zip(pos.items(), pos_from_layers.items()):
488
+ assert n1 == n2 and (p1 == p2).all()
489
+
490
+ # Nodes "a" and "d" are in the same layer
491
+ assert pos["a"][-1] == pos["d"][-1]
492
+ # positions should be sorted according to layer
493
+ assert pos["c"][-1] < pos["a"][-1] < pos["b"][-1] < pos["e"][-1]
494
+
495
+ # Make sure that multipartite_layout still works when layers are not sortable
496
+ G.nodes["a"]["subset"] = "layer_0" # Can't sort mixed strs/ints
497
+ pos_nosort = nx.multipartite_layout(G) # smoke test: this should not raise
498
+ assert pos_nosort.keys() == pos.keys()
499
+
500
+
501
+ def _num_nodes_per_bfs_layer(pos):
502
+ """Helper function to extract the number of nodes in each layer of bfs_layout"""
503
+ x = np.array(list(pos.values()))[:, 0] # node positions in layered dimension
504
+ _, layer_count = np.unique(x, return_counts=True)
505
+ return layer_count
506
+
507
+
508
+ @pytest.mark.parametrize("n", range(2, 7))
509
+ def test_bfs_layout_complete_graph(n):
510
+ """The complete graph should result in two layers: the starting node and
511
+ a second layer containing all neighbors."""
512
+ G = nx.complete_graph(n)
513
+ pos = nx.bfs_layout(G, start=0)
514
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), [1, n - 1])
515
+
516
+
517
+ def test_bfs_layout_barbell():
518
+ G = nx.barbell_graph(5, 3)
519
+ # Start in one of the "bells"
520
+ pos = nx.bfs_layout(G, start=0)
521
+ # start, bell-1, [1] * len(bar)+1, bell-1
522
+ expected_nodes_per_layer = [1, 4, 1, 1, 1, 1, 4]
523
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
524
+ # Start in the other "bell" - expect same layer pattern
525
+ pos = nx.bfs_layout(G, start=12)
526
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
527
+ # Starting in the center of the bar, expect layers to be symmetric
528
+ pos = nx.bfs_layout(G, start=6)
529
+ # Expected layers: {6 (start)}, {5, 7}, {4, 8}, {8 nodes from remainder of bells}
530
+ expected_nodes_per_layer = [1, 2, 2, 8]
531
+ assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer)
532
+
533
+
534
+ def test_bfs_layout_disconnected():
535
+ G = nx.complete_graph(5)
536
+ G.add_edges_from([(10, 11), (11, 12)])
537
+ with pytest.raises(nx.NetworkXError, match="bfs_layout didn't include all nodes"):
538
+ nx.bfs_layout(G, start=0)
falcon/lib/python3.10/site-packages/networkx/drawing/tests/test_pydot.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for pydot drawing functions."""
2
+
3
+ from io import StringIO
4
+
5
+ import pytest
6
+
7
+ import networkx as nx
8
+ from networkx.utils import graphs_equal
9
+
10
+ pydot = pytest.importorskip("pydot")
11
+
12
+
13
+ class TestPydot:
14
+ @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
15
+ @pytest.mark.parametrize("prog", ("neato", "dot"))
16
+ def test_pydot(self, G, prog, tmp_path):
17
+ """
18
+ Validate :mod:`pydot`-based usage of the passed NetworkX graph with the
19
+ passed basename of an external GraphViz command (e.g., `dot`, `neato`).
20
+ """
21
+
22
+ # Set the name of this graph to... "G". Failing to do so will
23
+ # subsequently trip an assertion expecting this name.
24
+ G.graph["name"] = "G"
25
+
26
+ # Add arbitrary nodes and edges to the passed empty graph.
27
+ G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("A", "D")])
28
+ G.add_node("E")
29
+
30
+ # Validate layout of this graph with the passed GraphViz command.
31
+ graph_layout = nx.nx_pydot.pydot_layout(G, prog=prog)
32
+ assert isinstance(graph_layout, dict)
33
+
34
+ # Convert this graph into a "pydot.Dot" instance.
35
+ P = nx.nx_pydot.to_pydot(G)
36
+
37
+ # Convert this "pydot.Dot" instance back into a graph of the same type.
38
+ G2 = G.__class__(nx.nx_pydot.from_pydot(P))
39
+
40
+ # Validate the original and resulting graphs to be the same.
41
+ assert graphs_equal(G, G2)
42
+
43
+ fname = tmp_path / "out.dot"
44
+
45
+ # Serialize this "pydot.Dot" instance to a temporary file in dot format
46
+ P.write_raw(fname)
47
+
48
+ # Deserialize a list of new "pydot.Dot" instances back from this file.
49
+ Pin_list = pydot.graph_from_dot_file(path=fname, encoding="utf-8")
50
+
51
+ # Validate this file to contain only one graph.
52
+ assert len(Pin_list) == 1
53
+
54
+ # The single "pydot.Dot" instance deserialized from this file.
55
+ Pin = Pin_list[0]
56
+
57
+ # Sorted list of all nodes in the original "pydot.Dot" instance.
58
+ n1 = sorted(p.get_name() for p in P.get_node_list())
59
+
60
+ # Sorted list of all nodes in the deserialized "pydot.Dot" instance.
61
+ n2 = sorted(p.get_name() for p in Pin.get_node_list())
62
+
63
+ # Validate these instances to contain the same nodes.
64
+ assert n1 == n2
65
+
66
+ # Sorted list of all edges in the original "pydot.Dot" instance.
67
+ e1 = sorted((e.get_source(), e.get_destination()) for e in P.get_edge_list())
68
+
69
+ # Sorted list of all edges in the original "pydot.Dot" instance.
70
+ e2 = sorted((e.get_source(), e.get_destination()) for e in Pin.get_edge_list())
71
+
72
+ # Validate these instances to contain the same edges.
73
+ assert e1 == e2
74
+
75
+ # Deserialize a new graph of the same type back from this file.
76
+ Hin = nx.nx_pydot.read_dot(fname)
77
+ Hin = G.__class__(Hin)
78
+
79
+ # Validate the original and resulting graphs to be the same.
80
+ assert graphs_equal(G, Hin)
81
+
82
+ def test_read_write(self):
83
+ G = nx.MultiGraph()
84
+ G.graph["name"] = "G"
85
+ G.add_edge("1", "2", key="0") # read assumes strings
86
+ fh = StringIO()
87
+ nx.nx_pydot.write_dot(G, fh)
88
+ fh.seek(0)
89
+ H = nx.nx_pydot.read_dot(fh)
90
+ assert graphs_equal(G, H)
91
+
92
+
93
+ def test_pydot_issue_7581(tmp_path):
94
+ """Validate that `nx_pydot.pydot_layout` handles nodes
95
+ with characters like "\n", " ".
96
+
97
+ Those characters cause `pydot` to escape and quote them on output,
98
+ which caused #7581.
99
+ """
100
+ G = nx.Graph()
101
+ G.add_edges_from([("A\nbig test", "B"), ("A\nbig test", "C"), ("B", "C")])
102
+
103
+ graph_layout = nx.nx_pydot.pydot_layout(G, prog="dot")
104
+ assert isinstance(graph_layout, dict)
105
+
106
+ # Convert the graph to pydot and back into a graph. There should be no difference.
107
+ P = nx.nx_pydot.to_pydot(G)
108
+ G2 = nx.Graph(nx.nx_pydot.from_pydot(P))
109
+ assert graphs_equal(G, G2)
110
+
111
+
112
+ @pytest.mark.parametrize(
113
+ "graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
114
+ )
115
+ def test_hashable_pydot(graph_type):
116
+ # gh-5790
117
+ G = graph_type()
118
+ G.add_edge("5", frozenset([1]), t='"Example:A"', l=False)
119
+ G.add_edge("1", 2, w=True, t=("node1",), l=frozenset(["node1"]))
120
+ G.add_edge("node", (3, 3), w="string")
121
+
122
+ assert [
123
+ {"t": '"Example:A"', "l": "False"},
124
+ {"w": "True", "t": "('node1',)", "l": "frozenset({'node1'})"},
125
+ {"w": "string"},
126
+ ] == [
127
+ attr
128
+ for _, _, attr in nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).edges.data()
129
+ ]
130
+
131
+ assert {str(i) for i in G.nodes()} == set(
132
+ nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).nodes
133
+ )
134
+
135
+
136
+ def test_pydot_numerical_name():
137
+ G = nx.Graph()
138
+ G.add_edges_from([("A", "B"), (0, 1)])
139
+ graph_layout = nx.nx_pydot.pydot_layout(G, prog="dot")
140
+ assert isinstance(graph_layout, dict)
141
+ assert "0" not in graph_layout
142
+ assert 0 in graph_layout
143
+ assert "1" not in graph_layout
144
+ assert 1 in graph_layout
145
+ assert "A" in graph_layout
146
+ assert "B" in graph_layout
falcon/lib/python3.10/site-packages/networkx/drawing/tests/test_pylab.py ADDED
@@ -0,0 +1,1029 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for matplotlib drawing functions."""
2
+
3
+ import itertools
4
+ import os
5
+ import warnings
6
+
7
+ import pytest
8
+
9
+ mpl = pytest.importorskip("matplotlib")
10
+ np = pytest.importorskip("numpy")
11
+ mpl.use("PS")
12
+ plt = pytest.importorskip("matplotlib.pyplot")
13
+ plt.rcParams["text.usetex"] = False
14
+
15
+
16
+ import networkx as nx
17
+
18
+ barbell = nx.barbell_graph(4, 6)
19
+
20
+
21
+ def test_draw():
22
+ try:
23
+ functions = [
24
+ nx.draw_circular,
25
+ nx.draw_kamada_kawai,
26
+ nx.draw_planar,
27
+ nx.draw_random,
28
+ nx.draw_spectral,
29
+ nx.draw_spring,
30
+ nx.draw_shell,
31
+ ]
32
+ options = [{"node_color": "black", "node_size": 100, "width": 3}]
33
+ for function, option in itertools.product(functions, options):
34
+ function(barbell, **option)
35
+ plt.savefig("test.ps")
36
+ except ModuleNotFoundError: # draw_kamada_kawai requires scipy
37
+ pass
38
+ finally:
39
+ try:
40
+ os.unlink("test.ps")
41
+ except OSError:
42
+ pass
43
+
44
+
45
+ def test_draw_shell_nlist():
46
+ try:
47
+ nlist = [list(range(4)), list(range(4, 10)), list(range(10, 14))]
48
+ nx.draw_shell(barbell, nlist=nlist)
49
+ plt.savefig("test.ps")
50
+ finally:
51
+ try:
52
+ os.unlink("test.ps")
53
+ except OSError:
54
+ pass
55
+
56
+
57
+ def test_edge_colormap():
58
+ colors = range(barbell.number_of_edges())
59
+ nx.draw_spring(
60
+ barbell, edge_color=colors, width=4, edge_cmap=plt.cm.Blues, with_labels=True
61
+ )
62
+ # plt.show()
63
+
64
+
65
+ def test_arrows():
66
+ nx.draw_spring(barbell.to_directed())
67
+ # plt.show()
68
+
69
+
70
+ @pytest.mark.parametrize(
71
+ ("edge_color", "expected"),
72
+ (
73
+ (None, "black"), # Default
74
+ ("r", "red"), # Non-default color string
75
+ (["r"], "red"), # Single non-default color in a list
76
+ ((1.0, 1.0, 0.0), "yellow"), # single color as rgb tuple
77
+ ([(1.0, 1.0, 0.0)], "yellow"), # single color as rgb tuple in list
78
+ ((0, 1, 0, 1), "lime"), # single color as rgba tuple
79
+ ([(0, 1, 0, 1)], "lime"), # single color as rgba tuple in list
80
+ ("#0000ff", "blue"), # single color hex code
81
+ (["#0000ff"], "blue"), # hex code in list
82
+ ),
83
+ )
84
+ @pytest.mark.parametrize("edgelist", (None, [(0, 1)]))
85
+ def test_single_edge_color_undirected(edge_color, expected, edgelist):
86
+ """Tests ways of specifying all edges have a single color for edges
87
+ drawn with a LineCollection"""
88
+
89
+ G = nx.path_graph(3)
90
+ drawn_edges = nx.draw_networkx_edges(
91
+ G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color
92
+ )
93
+ assert mpl.colors.same_color(drawn_edges.get_color(), expected)
94
+
95
+
96
+ @pytest.mark.parametrize(
97
+ ("edge_color", "expected"),
98
+ (
99
+ (None, "black"), # Default
100
+ ("r", "red"), # Non-default color string
101
+ (["r"], "red"), # Single non-default color in a list
102
+ ((1.0, 1.0, 0.0), "yellow"), # single color as rgb tuple
103
+ ([(1.0, 1.0, 0.0)], "yellow"), # single color as rgb tuple in list
104
+ ((0, 1, 0, 1), "lime"), # single color as rgba tuple
105
+ ([(0, 1, 0, 1)], "lime"), # single color as rgba tuple in list
106
+ ("#0000ff", "blue"), # single color hex code
107
+ (["#0000ff"], "blue"), # hex code in list
108
+ ),
109
+ )
110
+ @pytest.mark.parametrize("edgelist", (None, [(0, 1)]))
111
+ def test_single_edge_color_directed(edge_color, expected, edgelist):
112
+ """Tests ways of specifying all edges have a single color for edges drawn
113
+ with FancyArrowPatches"""
114
+
115
+ G = nx.path_graph(3, create_using=nx.DiGraph)
116
+ drawn_edges = nx.draw_networkx_edges(
117
+ G, pos=nx.random_layout(G), edgelist=edgelist, edge_color=edge_color
118
+ )
119
+ for fap in drawn_edges:
120
+ assert mpl.colors.same_color(fap.get_edgecolor(), expected)
121
+
122
+
123
+ def test_edge_color_tuple_interpretation():
124
+ """If edge_color is a sequence with the same length as edgelist, then each
125
+ value in edge_color is mapped onto each edge via colormap."""
126
+ G = nx.path_graph(6, create_using=nx.DiGraph)
127
+ pos = {n: (n, n) for n in range(len(G))}
128
+
129
+ # num edges != 3 or 4 --> edge_color interpreted as rgb(a)
130
+ for ec in ((0, 0, 1), (0, 0, 1, 1)):
131
+ # More than 4 edges
132
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=ec)
133
+ for fap in drawn_edges:
134
+ assert mpl.colors.same_color(fap.get_edgecolor(), ec)
135
+ # Fewer than 3 edges
136
+ drawn_edges = nx.draw_networkx_edges(
137
+ G, pos, edgelist=[(0, 1), (1, 2)], edge_color=ec
138
+ )
139
+ for fap in drawn_edges:
140
+ assert mpl.colors.same_color(fap.get_edgecolor(), ec)
141
+
142
+ # num edges == 3, len(edge_color) == 4: interpreted as rgba
143
+ drawn_edges = nx.draw_networkx_edges(
144
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3)], edge_color=(0, 0, 1, 1)
145
+ )
146
+ for fap in drawn_edges:
147
+ assert mpl.colors.same_color(fap.get_edgecolor(), "blue")
148
+
149
+ # num edges == 4, len(edge_color) == 3: interpreted as rgb
150
+ drawn_edges = nx.draw_networkx_edges(
151
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 4)], edge_color=(0, 0, 1)
152
+ )
153
+ for fap in drawn_edges:
154
+ assert mpl.colors.same_color(fap.get_edgecolor(), "blue")
155
+
156
+ # num edges == len(edge_color) == 3: interpreted with cmap, *not* as rgb
157
+ drawn_edges = nx.draw_networkx_edges(
158
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3)], edge_color=(0, 0, 1)
159
+ )
160
+ assert mpl.colors.same_color(
161
+ drawn_edges[0].get_edgecolor(), drawn_edges[1].get_edgecolor()
162
+ )
163
+ for fap in drawn_edges:
164
+ assert not mpl.colors.same_color(fap.get_edgecolor(), "blue")
165
+
166
+ # num edges == len(edge_color) == 4: interpreted with cmap, *not* as rgba
167
+ drawn_edges = nx.draw_networkx_edges(
168
+ G, pos, edgelist=[(0, 1), (1, 2), (2, 3), (3, 4)], edge_color=(0, 0, 1, 1)
169
+ )
170
+ assert mpl.colors.same_color(
171
+ drawn_edges[0].get_edgecolor(), drawn_edges[1].get_edgecolor()
172
+ )
173
+ assert mpl.colors.same_color(
174
+ drawn_edges[2].get_edgecolor(), drawn_edges[3].get_edgecolor()
175
+ )
176
+ for fap in drawn_edges:
177
+ assert not mpl.colors.same_color(fap.get_edgecolor(), "blue")
178
+
179
+
180
+ def test_fewer_edge_colors_than_num_edges_directed():
181
+ """Test that the edge colors are cycled when there are fewer specified
182
+ colors than edges."""
183
+ G = barbell.to_directed()
184
+ pos = nx.random_layout(barbell)
185
+ edgecolors = ("r", "g", "b")
186
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=edgecolors)
187
+ for fap, expected in zip(drawn_edges, itertools.cycle(edgecolors)):
188
+ assert mpl.colors.same_color(fap.get_edgecolor(), expected)
189
+
190
+
191
+ def test_more_edge_colors_than_num_edges_directed():
192
+ """Test that extra edge colors are ignored when there are more specified
193
+ colors than edges."""
194
+ G = nx.path_graph(4, create_using=nx.DiGraph) # 3 edges
195
+ pos = nx.random_layout(barbell)
196
+ edgecolors = ("r", "g", "b", "c") # 4 edge colors
197
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=edgecolors)
198
+ for fap, expected in zip(drawn_edges, edgecolors[:-1]):
199
+ assert mpl.colors.same_color(fap.get_edgecolor(), expected)
200
+
201
+
202
+ def test_edge_color_string_with_global_alpha_undirected():
203
+ edge_collection = nx.draw_networkx_edges(
204
+ barbell,
205
+ pos=nx.random_layout(barbell),
206
+ edgelist=[(0, 1), (1, 2)],
207
+ edge_color="purple",
208
+ alpha=0.2,
209
+ )
210
+ ec = edge_collection.get_color().squeeze() # as rgba tuple
211
+ assert len(edge_collection.get_paths()) == 2
212
+ assert mpl.colors.same_color(ec[:-1], "purple")
213
+ assert ec[-1] == 0.2
214
+
215
+
216
+ def test_edge_color_string_with_global_alpha_directed():
217
+ drawn_edges = nx.draw_networkx_edges(
218
+ barbell.to_directed(),
219
+ pos=nx.random_layout(barbell),
220
+ edgelist=[(0, 1), (1, 2)],
221
+ edge_color="purple",
222
+ alpha=0.2,
223
+ )
224
+ assert len(drawn_edges) == 2
225
+ for fap in drawn_edges:
226
+ ec = fap.get_edgecolor() # As rgba tuple
227
+ assert mpl.colors.same_color(ec[:-1], "purple")
228
+ assert ec[-1] == 0.2
229
+
230
+
231
+ @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
232
+ def test_edge_width_default_value(graph_type):
233
+ """Test the default linewidth for edges drawn either via LineCollection or
234
+ FancyArrowPatches."""
235
+ G = nx.path_graph(2, create_using=graph_type)
236
+ pos = {n: (n, n) for n in range(len(G))}
237
+ drawn_edges = nx.draw_networkx_edges(G, pos)
238
+ if isinstance(drawn_edges, list): # directed case: list of FancyArrowPatch
239
+ drawn_edges = drawn_edges[0]
240
+ assert drawn_edges.get_linewidth() == 1
241
+
242
+
243
+ @pytest.mark.parametrize(
244
+ ("edgewidth", "expected"),
245
+ (
246
+ (3, 3), # single-value, non-default
247
+ ([3], 3), # Single value as a list
248
+ ),
249
+ )
250
+ def test_edge_width_single_value_undirected(edgewidth, expected):
251
+ G = nx.path_graph(4)
252
+ pos = {n: (n, n) for n in range(len(G))}
253
+ drawn_edges = nx.draw_networkx_edges(G, pos, width=edgewidth)
254
+ assert len(drawn_edges.get_paths()) == 3
255
+ assert drawn_edges.get_linewidth() == expected
256
+
257
+
258
+ @pytest.mark.parametrize(
259
+ ("edgewidth", "expected"),
260
+ (
261
+ (3, 3), # single-value, non-default
262
+ ([3], 3), # Single value as a list
263
+ ),
264
+ )
265
+ def test_edge_width_single_value_directed(edgewidth, expected):
266
+ G = nx.path_graph(4, create_using=nx.DiGraph)
267
+ pos = {n: (n, n) for n in range(len(G))}
268
+ drawn_edges = nx.draw_networkx_edges(G, pos, width=edgewidth)
269
+ assert len(drawn_edges) == 3
270
+ for fap in drawn_edges:
271
+ assert fap.get_linewidth() == expected
272
+
273
+
274
+ @pytest.mark.parametrize(
275
+ "edgelist",
276
+ (
277
+ [(0, 1), (1, 2), (2, 3)], # one width specification per edge
278
+ None, # fewer widths than edges - widths cycle
279
+ [(0, 1), (1, 2)], # More widths than edges - unused widths ignored
280
+ ),
281
+ )
282
+ def test_edge_width_sequence(edgelist):
283
+ G = barbell.to_directed()
284
+ pos = nx.random_layout(G)
285
+ widths = (0.5, 2.0, 12.0)
286
+ drawn_edges = nx.draw_networkx_edges(G, pos, edgelist=edgelist, width=widths)
287
+ for fap, expected_width in zip(drawn_edges, itertools.cycle(widths)):
288
+ assert fap.get_linewidth() == expected_width
289
+
290
+
291
+ def test_edge_color_with_edge_vmin_vmax():
292
+ """Test that edge_vmin and edge_vmax properly set the dynamic range of the
293
+ color map when num edges == len(edge_colors)."""
294
+ G = nx.path_graph(3, create_using=nx.DiGraph)
295
+ pos = nx.random_layout(G)
296
+ # Extract colors from the original (unscaled) colormap
297
+ drawn_edges = nx.draw_networkx_edges(G, pos, edge_color=[0, 1.0])
298
+ orig_colors = [e.get_edgecolor() for e in drawn_edges]
299
+ # Colors from scaled colormap
300
+ drawn_edges = nx.draw_networkx_edges(
301
+ G, pos, edge_color=[0.2, 0.8], edge_vmin=0.2, edge_vmax=0.8
302
+ )
303
+ scaled_colors = [e.get_edgecolor() for e in drawn_edges]
304
+ assert mpl.colors.same_color(orig_colors, scaled_colors)
305
+
306
+
307
+ def test_directed_edges_linestyle_default():
308
+ """Test default linestyle for edges drawn with FancyArrowPatches."""
309
+ G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
310
+ pos = {n: (n, n) for n in range(len(G))}
311
+
312
+ # edge with default style
313
+ drawn_edges = nx.draw_networkx_edges(G, pos)
314
+ assert len(drawn_edges) == 3
315
+ for fap in drawn_edges:
316
+ assert fap.get_linestyle() == "solid"
317
+
318
+
319
+ @pytest.mark.parametrize(
320
+ "style",
321
+ (
322
+ "dashed", # edge with string style
323
+ "--", # edge with simplified string style
324
+ (1, (1, 1)), # edge with (offset, onoffseq) style
325
+ ),
326
+ )
327
+ def test_directed_edges_linestyle_single_value(style):
328
+ """Tests support for specifying linestyles with a single value to be applied to
329
+ all edges in ``draw_networkx_edges`` for FancyArrowPatch outputs
330
+ (e.g. directed edges)."""
331
+
332
+ G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
333
+ pos = {n: (n, n) for n in range(len(G))}
334
+
335
+ drawn_edges = nx.draw_networkx_edges(G, pos, style=style)
336
+ assert len(drawn_edges) == 3
337
+ for fap in drawn_edges:
338
+ assert fap.get_linestyle() == style
339
+
340
+
341
+ @pytest.mark.parametrize(
342
+ "style_seq",
343
+ (
344
+ ["dashed"], # edge with string style in list
345
+ ["--"], # edge with simplified string style in list
346
+ [(1, (1, 1))], # edge with (offset, onoffseq) style in list
347
+ ["--", "-", ":"], # edges with styles for each edge
348
+ ["--", "-"], # edges with fewer styles than edges (styles cycle)
349
+ ["--", "-", ":", "-."], # edges with more styles than edges (extra unused)
350
+ ),
351
+ )
352
+ def test_directed_edges_linestyle_sequence(style_seq):
353
+ """Tests support for specifying linestyles with sequences in
354
+ ``draw_networkx_edges`` for FancyArrowPatch outputs (e.g. directed edges)."""
355
+
356
+ G = nx.path_graph(4, create_using=nx.DiGraph) # Graph with 3 edges
357
+ pos = {n: (n, n) for n in range(len(G))}
358
+
359
+ drawn_edges = nx.draw_networkx_edges(G, pos, style=style_seq)
360
+ assert len(drawn_edges) == 3
361
+ for fap, style in zip(drawn_edges, itertools.cycle(style_seq)):
362
+ assert fap.get_linestyle() == style
363
+
364
+
365
+ def test_return_types():
366
+ from matplotlib.collections import LineCollection, PathCollection
367
+ from matplotlib.patches import FancyArrowPatch
368
+
369
+ G = nx.cubical_graph(nx.Graph)
370
+ dG = nx.cubical_graph(nx.DiGraph)
371
+ pos = nx.spring_layout(G)
372
+ dpos = nx.spring_layout(dG)
373
+ # nodes
374
+ nodes = nx.draw_networkx_nodes(G, pos)
375
+ assert isinstance(nodes, PathCollection)
376
+ # edges
377
+ edges = nx.draw_networkx_edges(dG, dpos, arrows=True)
378
+ assert isinstance(edges, list)
379
+ if len(edges) > 0:
380
+ assert isinstance(edges[0], FancyArrowPatch)
381
+ edges = nx.draw_networkx_edges(dG, dpos, arrows=False)
382
+ assert isinstance(edges, LineCollection)
383
+ edges = nx.draw_networkx_edges(G, dpos, arrows=None)
384
+ assert isinstance(edges, LineCollection)
385
+ edges = nx.draw_networkx_edges(dG, pos, arrows=None)
386
+ assert isinstance(edges, list)
387
+ if len(edges) > 0:
388
+ assert isinstance(edges[0], FancyArrowPatch)
389
+
390
+
391
+ def test_labels_and_colors():
392
+ G = nx.cubical_graph()
393
+ pos = nx.spring_layout(G) # positions for all nodes
394
+ # nodes
395
+ nx.draw_networkx_nodes(
396
+ G, pos, nodelist=[0, 1, 2, 3], node_color="r", node_size=500, alpha=0.75
397
+ )
398
+ nx.draw_networkx_nodes(
399
+ G,
400
+ pos,
401
+ nodelist=[4, 5, 6, 7],
402
+ node_color="b",
403
+ node_size=500,
404
+ alpha=[0.25, 0.5, 0.75, 1.0],
405
+ )
406
+ # edges
407
+ nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
408
+ nx.draw_networkx_edges(
409
+ G,
410
+ pos,
411
+ edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
412
+ width=8,
413
+ alpha=0.5,
414
+ edge_color="r",
415
+ )
416
+ nx.draw_networkx_edges(
417
+ G,
418
+ pos,
419
+ edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
420
+ width=8,
421
+ alpha=0.5,
422
+ edge_color="b",
423
+ )
424
+ nx.draw_networkx_edges(
425
+ G,
426
+ pos,
427
+ edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
428
+ arrows=True,
429
+ min_source_margin=0.5,
430
+ min_target_margin=0.75,
431
+ width=8,
432
+ edge_color="b",
433
+ )
434
+ # some math labels
435
+ labels = {}
436
+ labels[0] = r"$a$"
437
+ labels[1] = r"$b$"
438
+ labels[2] = r"$c$"
439
+ labels[3] = r"$d$"
440
+ labels[4] = r"$\alpha$"
441
+ labels[5] = r"$\beta$"
442
+ labels[6] = r"$\gamma$"
443
+ labels[7] = r"$\delta$"
444
+ colors = {n: "k" if n % 2 == 0 else "r" for n in range(8)}
445
+ nx.draw_networkx_labels(G, pos, labels, font_size=16)
446
+ nx.draw_networkx_labels(G, pos, labels, font_size=16, font_color=colors)
447
+ nx.draw_networkx_edge_labels(G, pos, edge_labels=None, rotate=False)
448
+ nx.draw_networkx_edge_labels(G, pos, edge_labels={(4, 5): "4-5"})
449
+ # plt.show()
450
+
451
+
452
+ @pytest.mark.mpl_image_compare
453
+ def test_house_with_colors():
454
+ G = nx.house_graph()
455
+ # explicitly set positions
456
+ fig, ax = plt.subplots()
457
+ pos = {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)}
458
+
459
+ # Plot nodes with different properties for the "wall" and "roof" nodes
460
+ nx.draw_networkx_nodes(
461
+ G,
462
+ pos,
463
+ node_size=3000,
464
+ nodelist=[0, 1, 2, 3],
465
+ node_color="tab:blue",
466
+ )
467
+ nx.draw_networkx_nodes(
468
+ G, pos, node_size=2000, nodelist=[4], node_color="tab:orange"
469
+ )
470
+ nx.draw_networkx_edges(G, pos, alpha=0.5, width=6)
471
+ # Customize axes
472
+ ax.margins(0.11)
473
+ plt.tight_layout()
474
+ plt.axis("off")
475
+ return fig
476
+
477
+
478
+ def test_axes():
479
+ fig, ax = plt.subplots()
480
+ nx.draw(barbell, ax=ax)
481
+ nx.draw_networkx_edge_labels(barbell, nx.circular_layout(barbell), ax=ax)
482
+
483
+
484
+ def test_empty_graph():
485
+ G = nx.Graph()
486
+ nx.draw(G)
487
+
488
+
489
+ def test_draw_empty_nodes_return_values():
490
+ # See Issue #3833
491
+ import matplotlib.collections # call as mpl.collections
492
+
493
+ G = nx.Graph([(1, 2), (2, 3)])
494
+ DG = nx.DiGraph([(1, 2), (2, 3)])
495
+ pos = nx.circular_layout(G)
496
+ assert isinstance(
497
+ nx.draw_networkx_nodes(G, pos, nodelist=[]), mpl.collections.PathCollection
498
+ )
499
+ assert isinstance(
500
+ nx.draw_networkx_nodes(DG, pos, nodelist=[]), mpl.collections.PathCollection
501
+ )
502
+
503
+ # drawing empty edges used to return an empty LineCollection or empty list.
504
+ # Now it is always an empty list (because edges are now lists of FancyArrows)
505
+ assert nx.draw_networkx_edges(G, pos, edgelist=[], arrows=True) == []
506
+ assert nx.draw_networkx_edges(G, pos, edgelist=[], arrows=False) == []
507
+ assert nx.draw_networkx_edges(DG, pos, edgelist=[], arrows=False) == []
508
+ assert nx.draw_networkx_edges(DG, pos, edgelist=[], arrows=True) == []
509
+
510
+
511
+ def test_multigraph_edgelist_tuples():
512
+ # See Issue #3295
513
+ G = nx.path_graph(3, create_using=nx.MultiDiGraph)
514
+ nx.draw_networkx(G, edgelist=[(0, 1, 0)])
515
+ nx.draw_networkx(G, edgelist=[(0, 1, 0)], node_size=[10, 20, 0])
516
+
517
+
518
+ def test_alpha_iter():
519
+ pos = nx.random_layout(barbell)
520
+ fig = plt.figure()
521
+ # with fewer alpha elements than nodes
522
+ fig.add_subplot(131) # Each test in a new axis object
523
+ nx.draw_networkx_nodes(barbell, pos, alpha=[0.1, 0.2])
524
+ # with equal alpha elements and nodes
525
+ num_nodes = len(barbell.nodes)
526
+ alpha = [x / num_nodes for x in range(num_nodes)]
527
+ colors = range(num_nodes)
528
+ fig.add_subplot(132)
529
+ nx.draw_networkx_nodes(barbell, pos, node_color=colors, alpha=alpha)
530
+ # with more alpha elements than nodes
531
+ alpha.append(1)
532
+ fig.add_subplot(133)
533
+ nx.draw_networkx_nodes(barbell, pos, alpha=alpha)
534
+
535
+
536
+ def test_multiple_node_shapes():
537
+ G = nx.path_graph(4)
538
+ ax = plt.figure().add_subplot(111)
539
+ nx.draw(G, node_shape=["o", "h", "s", "^"], ax=ax)
540
+ scatters = [
541
+ s for s in ax.get_children() if isinstance(s, mpl.collections.PathCollection)
542
+ ]
543
+ assert len(scatters) == 4
544
+
545
+
546
+ def test_individualized_font_attributes():
547
+ G = nx.karate_club_graph()
548
+ ax = plt.figure().add_subplot(111)
549
+ nx.draw(
550
+ G,
551
+ ax=ax,
552
+ font_color={n: "k" if n % 2 else "r" for n in G.nodes()},
553
+ font_size={n: int(n / (34 / 15) + 5) for n in G.nodes()},
554
+ )
555
+ for n, t in zip(
556
+ G.nodes(),
557
+ [
558
+ t
559
+ for t in ax.get_children()
560
+ if isinstance(t, mpl.text.Text) and len(t.get_text()) > 0
561
+ ],
562
+ ):
563
+ expected = "black" if n % 2 else "red"
564
+
565
+ assert mpl.colors.same_color(t.get_color(), expected)
566
+ assert int(n / (34 / 15) + 5) == t.get_size()
567
+
568
+
569
+ def test_individualized_edge_attributes():
570
+ G = nx.karate_club_graph()
571
+ ax = plt.figure().add_subplot(111)
572
+ arrowstyles = ["-|>" if (u + v) % 2 == 0 else "-[" for u, v in G.edges()]
573
+ arrowsizes = [10 * (u % 2 + v % 2) + 10 for u, v in G.edges()]
574
+ nx.draw(G, ax=ax, arrows=True, arrowstyle=arrowstyles, arrowsize=arrowsizes)
575
+ arrows = [
576
+ f for f in ax.get_children() if isinstance(f, mpl.patches.FancyArrowPatch)
577
+ ]
578
+ for e, a in zip(G.edges(), arrows):
579
+ assert a.get_mutation_scale() == 10 * (e[0] % 2 + e[1] % 2) + 10
580
+ expected = (
581
+ mpl.patches.ArrowStyle.BracketB
582
+ if sum(e) % 2
583
+ else mpl.patches.ArrowStyle.CurveFilledB
584
+ )
585
+ assert isinstance(a.get_arrowstyle(), expected)
586
+
587
+
588
+ def test_error_invalid_kwds():
589
+ with pytest.raises(ValueError, match="Received invalid argument"):
590
+ nx.draw(barbell, foo="bar")
591
+
592
+
593
+ def test_draw_networkx_arrowsize_incorrect_size():
594
+ G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 3)])
595
+ arrowsize = [1, 2, 3]
596
+ with pytest.raises(
597
+ ValueError, match="arrowsize should have the same length as edgelist"
598
+ ):
599
+ nx.draw(G, arrowsize=arrowsize)
600
+
601
+
602
+ @pytest.mark.parametrize("arrowsize", (30, [10, 20, 30]))
603
+ def test_draw_edges_arrowsize(arrowsize):
604
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
605
+ pos = {0: (0, 0), 1: (0, 1), 2: (1, 0)}
606
+ edges = nx.draw_networkx_edges(G, pos=pos, arrowsize=arrowsize)
607
+
608
+ arrowsize = itertools.repeat(arrowsize) if isinstance(arrowsize, int) else arrowsize
609
+
610
+ for fap, expected in zip(edges, arrowsize):
611
+ assert isinstance(fap, mpl.patches.FancyArrowPatch)
612
+ assert fap.get_mutation_scale() == expected
613
+
614
+
615
+ @pytest.mark.parametrize("arrowstyle", ("-|>", ["-|>", "-[", "<|-|>"]))
616
+ def test_draw_edges_arrowstyle(arrowstyle):
617
+ G = nx.DiGraph([(0, 1), (0, 2), (1, 2)])
618
+ pos = {0: (0, 0), 1: (0, 1), 2: (1, 0)}
619
+ edges = nx.draw_networkx_edges(G, pos=pos, arrowstyle=arrowstyle)
620
+
621
+ arrowstyle = (
622
+ itertools.repeat(arrowstyle) if isinstance(arrowstyle, str) else arrowstyle
623
+ )
624
+
625
+ arrow_objects = {
626
+ "-|>": mpl.patches.ArrowStyle.CurveFilledB,
627
+ "-[": mpl.patches.ArrowStyle.BracketB,
628
+ "<|-|>": mpl.patches.ArrowStyle.CurveFilledAB,
629
+ }
630
+
631
+ for fap, expected in zip(edges, arrowstyle):
632
+ assert isinstance(fap, mpl.patches.FancyArrowPatch)
633
+ assert isinstance(fap.get_arrowstyle(), arrow_objects[expected])
634
+
635
+
636
+ def test_np_edgelist():
637
+ # see issue #4129
638
+ nx.draw_networkx(barbell, edgelist=np.array([(0, 2), (0, 3)]))
639
+
640
+
641
+ def test_draw_nodes_missing_node_from_position():
642
+ G = nx.path_graph(3)
643
+ pos = {0: (0, 0), 1: (1, 1)} # No position for node 2
644
+ with pytest.raises(nx.NetworkXError, match="has no position"):
645
+ nx.draw_networkx_nodes(G, pos)
646
+
647
+
648
+ # NOTE: parametrizing on marker to test both branches of internal
649
+ # nx.draw_networkx_edges.to_marker_edge function
650
+ @pytest.mark.parametrize("node_shape", ("o", "s"))
651
+ def test_draw_edges_min_source_target_margins(node_shape):
652
+ """Test that there is a wider gap between the node and the start of an
653
+ incident edge when min_source_margin is specified.
654
+
655
+ This test checks that the use of min_{source/target}_margin kwargs result
656
+ in shorter (more padding) between the edges and source and target nodes.
657
+ As a crude visual example, let 's' and 't' represent source and target
658
+ nodes, respectively:
659
+
660
+ Default:
661
+ s-----------------------------t
662
+
663
+ With margins:
664
+ s ----------------------- t
665
+
666
+ """
667
+ # Create a single axis object to get consistent pixel coords across
668
+ # multiple draws
669
+ fig, ax = plt.subplots()
670
+ G = nx.DiGraph([(0, 1)])
671
+ pos = {0: (0, 0), 1: (1, 0)} # horizontal layout
672
+ # Get leftmost and rightmost points of the FancyArrowPatch object
673
+ # representing the edge between nodes 0 and 1 (in pixel coordinates)
674
+ default_patch = nx.draw_networkx_edges(G, pos, ax=ax, node_shape=node_shape)[0]
675
+ default_extent = default_patch.get_extents().corners()[::2, 0]
676
+ # Now, do the same but with "padding" for the source and target via the
677
+ # min_{source/target}_margin kwargs
678
+ padded_patch = nx.draw_networkx_edges(
679
+ G,
680
+ pos,
681
+ ax=ax,
682
+ node_shape=node_shape,
683
+ min_source_margin=100,
684
+ min_target_margin=100,
685
+ )[0]
686
+ padded_extent = padded_patch.get_extents().corners()[::2, 0]
687
+
688
+ # With padding, the left-most extent of the edge should be further to the
689
+ # right
690
+ assert padded_extent[0] > default_extent[0]
691
+ # And the rightmost extent of the edge, further to the left
692
+ assert padded_extent[1] < default_extent[1]
693
+
694
+
695
+ # NOTE: parametrizing on marker to test both branches of internal
696
+ # nx.draw_networkx_edges.to_marker_edge function
697
+ @pytest.mark.parametrize("node_shape", ("o", "s"))
698
+ def test_draw_edges_min_source_target_margins_individual(node_shape):
699
+ """Test that there is a wider gap between the node and the start of an
700
+ incident edge when min_source_margin is specified.
701
+
702
+ This test checks that the use of min_{source/target}_margin kwargs result
703
+ in shorter (more padding) between the edges and source and target nodes.
704
+ As a crude visual example, let 's' and 't' represent source and target
705
+ nodes, respectively:
706
+
707
+ Default:
708
+ s-----------------------------t
709
+
710
+ With margins:
711
+ s ----------------------- t
712
+
713
+ """
714
+ # Create a single axis object to get consistent pixel coords across
715
+ # multiple draws
716
+ fig, ax = plt.subplots()
717
+ G = nx.DiGraph([(0, 1), (1, 2)])
718
+ pos = {0: (0, 0), 1: (1, 0), 2: (2, 0)} # horizontal layout
719
+ # Get leftmost and rightmost points of the FancyArrowPatch object
720
+ # representing the edge between nodes 0 and 1 (in pixel coordinates)
721
+ default_patch = nx.draw_networkx_edges(G, pos, ax=ax, node_shape=node_shape)
722
+ default_extent = [d.get_extents().corners()[::2, 0] for d in default_patch]
723
+ # Now, do the same but with "padding" for the source and target via the
724
+ # min_{source/target}_margin kwargs
725
+ padded_patch = nx.draw_networkx_edges(
726
+ G,
727
+ pos,
728
+ ax=ax,
729
+ node_shape=node_shape,
730
+ min_source_margin=[98, 102],
731
+ min_target_margin=[98, 102],
732
+ )
733
+ padded_extent = [p.get_extents().corners()[::2, 0] for p in padded_patch]
734
+ for d, p in zip(default_extent, padded_extent):
735
+ print(f"{p=}, {d=}")
736
+ # With padding, the left-most extent of the edge should be further to the
737
+ # right
738
+ assert p[0] > d[0]
739
+ # And the rightmost extent of the edge, further to the left
740
+ assert p[1] < d[1]
741
+
742
+
743
+ def test_nonzero_selfloop_with_single_node():
744
+ """Ensure that selfloop extent is non-zero when there is only one node."""
745
+ # Create explicit axis object for test
746
+ fig, ax = plt.subplots()
747
+ # Graph with single node + self loop
748
+ G = nx.DiGraph()
749
+ G.add_node(0)
750
+ G.add_edge(0, 0)
751
+ # Draw
752
+ patch = nx.draw_networkx_edges(G, {0: (0, 0)})[0]
753
+ # The resulting patch must have non-zero extent
754
+ bbox = patch.get_extents()
755
+ assert bbox.width > 0 and bbox.height > 0
756
+ # Cleanup
757
+ plt.delaxes(ax)
758
+ plt.close()
759
+
760
+
761
+ def test_nonzero_selfloop_with_single_edge_in_edgelist():
762
+ """Ensure that selfloop extent is non-zero when only a single edge is
763
+ specified in the edgelist.
764
+ """
765
+ # Create explicit axis object for test
766
+ fig, ax = plt.subplots()
767
+ # Graph with selfloop
768
+ G = nx.path_graph(2, create_using=nx.DiGraph)
769
+ G.add_edge(1, 1)
770
+ pos = {n: (n, n) for n in G.nodes}
771
+ # Draw only the selfloop edge via the `edgelist` kwarg
772
+ patch = nx.draw_networkx_edges(G, pos, edgelist=[(1, 1)])[0]
773
+ # The resulting patch must have non-zero extent
774
+ bbox = patch.get_extents()
775
+ assert bbox.width > 0 and bbox.height > 0
776
+ # Cleanup
777
+ plt.delaxes(ax)
778
+ plt.close()
779
+
780
+
781
+ def test_apply_alpha():
782
+ """Test apply_alpha when there is a mismatch between the number of
783
+ supplied colors and elements.
784
+ """
785
+ nodelist = [0, 1, 2]
786
+ colorlist = ["r", "g", "b"]
787
+ alpha = 0.5
788
+ rgba_colors = nx.drawing.nx_pylab.apply_alpha(colorlist, alpha, nodelist)
789
+ assert all(rgba_colors[:, -1] == alpha)
790
+
791
+
792
+ def test_draw_edges_toggling_with_arrows_kwarg():
793
+ """
794
+ The `arrows` keyword argument is used as a 3-way switch to select which
795
+ type of object to use for drawing edges:
796
+ - ``arrows=None`` -> default (FancyArrowPatches for directed, else LineCollection)
797
+ - ``arrows=True`` -> FancyArrowPatches
798
+ - ``arrows=False`` -> LineCollection
799
+ """
800
+ import matplotlib.collections
801
+ import matplotlib.patches
802
+
803
+ UG = nx.path_graph(3)
804
+ DG = nx.path_graph(3, create_using=nx.DiGraph)
805
+ pos = {n: (n, n) for n in UG}
806
+
807
+ # Use FancyArrowPatches when arrows=True, regardless of graph type
808
+ for G in (UG, DG):
809
+ edges = nx.draw_networkx_edges(G, pos, arrows=True)
810
+ assert len(edges) == len(G.edges)
811
+ assert isinstance(edges[0], mpl.patches.FancyArrowPatch)
812
+
813
+ # Use LineCollection when arrows=False, regardless of graph type
814
+ for G in (UG, DG):
815
+ edges = nx.draw_networkx_edges(G, pos, arrows=False)
816
+ assert isinstance(edges, mpl.collections.LineCollection)
817
+
818
+ # Default behavior when arrows=None: FAPs for directed, LC's for undirected
819
+ edges = nx.draw_networkx_edges(UG, pos)
820
+ assert isinstance(edges, mpl.collections.LineCollection)
821
+ edges = nx.draw_networkx_edges(DG, pos)
822
+ assert len(edges) == len(G.edges)
823
+ assert isinstance(edges[0], mpl.patches.FancyArrowPatch)
824
+
825
+
826
+ @pytest.mark.parametrize("drawing_func", (nx.draw, nx.draw_networkx))
827
+ def test_draw_networkx_arrows_default_undirected(drawing_func):
828
+ import matplotlib.collections
829
+
830
+ G = nx.path_graph(3)
831
+ fig, ax = plt.subplots()
832
+ drawing_func(G, ax=ax)
833
+ assert any(isinstance(c, mpl.collections.LineCollection) for c in ax.collections)
834
+ assert not ax.patches
835
+ plt.delaxes(ax)
836
+ plt.close()
837
+
838
+
839
+ @pytest.mark.parametrize("drawing_func", (nx.draw, nx.draw_networkx))
840
+ def test_draw_networkx_arrows_default_directed(drawing_func):
841
+ import matplotlib.collections
842
+
843
+ G = nx.path_graph(3, create_using=nx.DiGraph)
844
+ fig, ax = plt.subplots()
845
+ drawing_func(G, ax=ax)
846
+ assert not any(
847
+ isinstance(c, mpl.collections.LineCollection) for c in ax.collections
848
+ )
849
+ assert ax.patches
850
+ plt.delaxes(ax)
851
+ plt.close()
852
+
853
+
854
+ def test_edgelist_kwarg_not_ignored():
855
+ # See gh-4994
856
+ G = nx.path_graph(3)
857
+ G.add_edge(0, 0)
858
+ fig, ax = plt.subplots()
859
+ nx.draw(G, edgelist=[(0, 1), (1, 2)], ax=ax) # Exclude self-loop from edgelist
860
+ assert not ax.patches
861
+ plt.delaxes(ax)
862
+ plt.close()
863
+
864
+
865
+ @pytest.mark.parametrize(
866
+ ("G", "expected_n_edges"),
867
+ ([nx.DiGraph(), 2], [nx.MultiGraph(), 4], [nx.MultiDiGraph(), 4]),
868
+ )
869
+ def test_draw_networkx_edges_multiedge_connectionstyle(G, expected_n_edges):
870
+ """Draws edges correctly for 3 types of graphs and checks for valid length"""
871
+ for i, (u, v) in enumerate([(0, 1), (0, 1), (0, 1), (0, 2)]):
872
+ G.add_edge(u, v, weight=round(i / 3, 2))
873
+ pos = {n: (n, n) for n in G}
874
+ # Raises on insufficient connectionstyle length
875
+ for conn_style in [
876
+ "arc3,rad=0.1",
877
+ ["arc3,rad=0.1", "arc3,rad=0.1"],
878
+ ["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.2"],
879
+ ]:
880
+ nx.draw_networkx_edges(G, pos, connectionstyle=conn_style)
881
+ arrows = nx.draw_networkx_edges(G, pos, connectionstyle=conn_style)
882
+ assert len(arrows) == expected_n_edges
883
+
884
+
885
+ @pytest.mark.parametrize(
886
+ ("G", "expected_n_edges"),
887
+ ([nx.DiGraph(), 2], [nx.MultiGraph(), 4], [nx.MultiDiGraph(), 4]),
888
+ )
889
+ def test_draw_networkx_edge_labels_multiedge_connectionstyle(G, expected_n_edges):
890
+ """Draws labels correctly for 3 types of graphs and checks for valid length and class names"""
891
+ for i, (u, v) in enumerate([(0, 1), (0, 1), (0, 1), (0, 2)]):
892
+ G.add_edge(u, v, weight=round(i / 3, 2))
893
+ pos = {n: (n, n) for n in G}
894
+ # Raises on insufficient connectionstyle length
895
+ arrows = nx.draw_networkx_edges(
896
+ G, pos, connectionstyle=["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.1"]
897
+ )
898
+ for conn_style in [
899
+ "arc3,rad=0.1",
900
+ ["arc3,rad=0.1", "arc3,rad=0.2"],
901
+ ["arc3,rad=0.1", "arc3,rad=0.1", "arc3,rad=0.1"],
902
+ ]:
903
+ text_items = nx.draw_networkx_edge_labels(G, pos, connectionstyle=conn_style)
904
+ assert len(text_items) == expected_n_edges
905
+ for ti in text_items.values():
906
+ assert ti.__class__.__name__ == "CurvedArrowText"
907
+
908
+
909
+ def test_draw_networkx_edge_label_multiedge():
910
+ G = nx.MultiGraph()
911
+ G.add_edge(0, 1, weight=10)
912
+ G.add_edge(0, 1, weight=20)
913
+ edge_labels = nx.get_edge_attributes(G, "weight") # Includes edge keys
914
+ pos = {n: (n, n) for n in G}
915
+ text_items = nx.draw_networkx_edge_labels(
916
+ G,
917
+ pos,
918
+ edge_labels=edge_labels,
919
+ connectionstyle=["arc3,rad=0.1", "arc3,rad=0.2"],
920
+ )
921
+ assert len(text_items) == 2
922
+
923
+
924
+ def test_draw_networkx_edge_label_empty_dict():
925
+ """Regression test for draw_networkx_edge_labels with empty dict. See
926
+ gh-5372."""
927
+ G = nx.path_graph(3)
928
+ pos = {n: (n, n) for n in G.nodes}
929
+ assert nx.draw_networkx_edge_labels(G, pos, edge_labels={}) == {}
930
+
931
+
932
+ def test_draw_networkx_edges_undirected_selfloop_colors():
933
+ """When an edgelist is supplied along with a sequence of colors, check that
934
+ the self-loops have the correct colors."""
935
+ fig, ax = plt.subplots()
936
+ # Edge list and corresponding colors
937
+ edgelist = [(1, 3), (1, 2), (2, 3), (1, 1), (3, 3), (2, 2)]
938
+ edge_colors = ["pink", "cyan", "black", "red", "blue", "green"]
939
+
940
+ G = nx.Graph(edgelist)
941
+ pos = {n: (n, n) for n in G.nodes}
942
+ nx.draw_networkx_edges(G, pos, ax=ax, edgelist=edgelist, edge_color=edge_colors)
943
+
944
+ # Verify that there are three fancy arrow patches (1 per self loop)
945
+ assert len(ax.patches) == 3
946
+
947
+ # These are points that should be contained in the self loops. For example,
948
+ # sl_points[0] will be (1, 1.1), which is inside the "path" of the first
949
+ # self-loop but outside the others
950
+ sl_points = np.array(edgelist[-3:]) + np.array([0, 0.1])
951
+
952
+ # Check that the mapping between self-loop locations and their colors is
953
+ # correct
954
+ for fap, clr, slp in zip(ax.patches, edge_colors[-3:], sl_points):
955
+ assert fap.get_path().contains_point(slp)
956
+ assert mpl.colors.same_color(fap.get_edgecolor(), clr)
957
+ plt.delaxes(ax)
958
+ plt.close()
959
+
960
+
961
+ @pytest.mark.parametrize(
962
+ "fap_only_kwarg", # Non-default values for kwargs that only apply to FAPs
963
+ (
964
+ {"arrowstyle": "-"},
965
+ {"arrowsize": 20},
966
+ {"connectionstyle": "arc3,rad=0.2"},
967
+ {"min_source_margin": 10},
968
+ {"min_target_margin": 10},
969
+ ),
970
+ )
971
+ def test_user_warnings_for_unused_edge_drawing_kwargs(fap_only_kwarg):
972
+ """Users should get a warning when they specify a non-default value for
973
+ one of the kwargs that applies only to edges drawn with FancyArrowPatches,
974
+ but FancyArrowPatches aren't being used under the hood."""
975
+ G = nx.path_graph(3)
976
+ pos = {n: (n, n) for n in G}
977
+ fig, ax = plt.subplots()
978
+ # By default, an undirected graph will use LineCollection to represent
979
+ # the edges
980
+ kwarg_name = list(fap_only_kwarg.keys())[0]
981
+ with pytest.warns(
982
+ UserWarning, match=f"\n\nThe {kwarg_name} keyword argument is not applicable"
983
+ ):
984
+ nx.draw_networkx_edges(G, pos, ax=ax, **fap_only_kwarg)
985
+ # FancyArrowPatches are always used when `arrows=True` is specified.
986
+ # Check that warnings are *not* raised in this case
987
+ with warnings.catch_warnings():
988
+ # Escalate warnings -> errors so tests fail if warnings are raised
989
+ warnings.simplefilter("error")
990
+ nx.draw_networkx_edges(G, pos, ax=ax, arrows=True, **fap_only_kwarg)
991
+
992
+ plt.delaxes(ax)
993
+ plt.close()
994
+
995
+
996
+ @pytest.mark.parametrize("draw_fn", (nx.draw, nx.draw_circular))
997
+ def test_no_warning_on_default_draw_arrowstyle(draw_fn):
998
+ # See gh-7284
999
+ fig, ax = plt.subplots()
1000
+ G = nx.cycle_graph(5)
1001
+ with warnings.catch_warnings(record=True) as w:
1002
+ draw_fn(G, ax=ax)
1003
+ assert len(w) == 0
1004
+
1005
+ plt.delaxes(ax)
1006
+ plt.close()
1007
+
1008
+
1009
+ @pytest.mark.parametrize("hide_ticks", [False, True])
1010
+ @pytest.mark.parametrize(
1011
+ "method",
1012
+ [
1013
+ nx.draw_networkx,
1014
+ nx.draw_networkx_edge_labels,
1015
+ nx.draw_networkx_edges,
1016
+ nx.draw_networkx_labels,
1017
+ nx.draw_networkx_nodes,
1018
+ ],
1019
+ )
1020
+ def test_hide_ticks(method, hide_ticks):
1021
+ G = nx.path_graph(3)
1022
+ pos = {n: (n, n) for n in G.nodes}
1023
+ _, ax = plt.subplots()
1024
+ method(G, pos=pos, ax=ax, hide_ticks=hide_ticks)
1025
+ for axis in [ax.xaxis, ax.yaxis]:
1026
+ assert bool(axis.get_ticklabels()) != hide_ticks
1027
+
1028
+ plt.delaxes(ax)
1029
+ plt.close()
falcon/lib/python3.10/site-packages/networkx/tests/__init__.py ADDED
File without changes
falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (166 Bytes). View file
 
falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_all_random_functions.cpython-310.pyc ADDED
Binary file (7.18 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert_numpy.cpython-310.pyc ADDED
Binary file (18.4 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert_pandas.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_convert_scipy.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_exceptions.cpython-310.pyc ADDED
Binary file (1.33 kB). View file
 
falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_import.cpython-310.pyc ADDED
Binary file (611 Bytes). View file
 
falcon/lib/python3.10/site-packages/networkx/tests/__pycache__/test_lazy_imports.cpython-310.pyc ADDED
Binary file (2.14 kB). View file