Spaces:
Running
Running
File size: 8,349 Bytes
83b1026 c032595 e7eaaf3 83b1026 0280171 83b1026 c032595 5eed07a 83b1026 e7eaaf3 0280171 e7eaaf3 0280171 19946be 0280171 e7eaaf3 19946be e7eaaf3 19946be 0280171 19946be 0280171 19946be 0280171 19946be e7eaaf3 19946be e7eaaf3 19946be e7eaaf3 19946be e7eaaf3 19946be e7eaaf3 19946be 0280171 19946be 0280171 19946be 0280171 19946be 0280171 19946be e7eaaf3 19946be e7eaaf3 19946be e7eaaf3 19946be 0280171 19946be e7eaaf3 19946be 0280171 19946be e7eaaf3 19946be e7eaaf3 19946be 0280171 e7eaaf3 19946be 0280171 e7eaaf3 19946be e7eaaf3 19946be e7eaaf3 19946be e7eaaf3 19946be 0280171 19946be 0280171 19946be 0280171 19946be 0280171 19946be 0280171 19946be e7eaaf3 0280171 e7eaaf3 0280171 83b1026 c032595 e7eaaf3 c032595 e7eaaf3 c032595 83b1026 e7eaaf3 83b1026 5eed07a 0280171 83b1026 0280171 e7eaaf3 0280171 83b1026 c032595 e7eaaf3 83b1026 0280171 83b1026 da1ea6b 83b1026 0280171 83b1026 5eed07a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
"""Automatically wraps all NetworkX functions as LynxKite operations."""
import collections
import types
from lynxkite.core import ops
import functools
import inspect
import networkx as nx
import re
import pandas as pd
ENV = "LynxKite Graph Analytics"
class UnsupportedParameterType(Exception):
pass
_UNSUPPORTED = object()
_SKIP = object()
def doc_to_type(name: str, type_hint: str) -> type:
type_hint = type_hint.lower()
type_hint = re.sub("[(][^)]+[)]", "", type_hint).strip().strip(".")
if " " in name or "http" in name:
return _UNSUPPORTED # Not a parameter type.
if type_hint.endswith(", optional"):
w = doc_to_type(name, type_hint.removesuffix(", optional").strip())
if w is _UNSUPPORTED:
return _SKIP
return w if w is _SKIP else w | None
if type_hint in [
"a digraph or multidigraph",
"a graph g",
"graph",
"graphs",
"networkx graph instance",
"networkx graph",
"networkx undirected graph",
"nx.graph",
"undirected graph",
"undirected networkx graph",
] or type_hint.startswith("networkx graph"):
return nx.Graph
elif type_hint in [
"digraph-like",
"digraph",
"directed graph",
"networkx digraph",
"networkx directed graph",
"nx.digraph",
]:
return nx.DiGraph
elif type_hint == "node":
return _UNSUPPORTED
elif type_hint == '"node (optional)"':
return _SKIP
elif type_hint == '"edge"':
return _UNSUPPORTED
elif type_hint == '"edge (optional)"':
return _SKIP
elif type_hint in ["class", "data type"]:
return _UNSUPPORTED
elif type_hint in ["string", "str", "node label"]:
return str
elif type_hint in ["string or none", "none or string", "string, or none"]:
return str | None
elif type_hint in ["int", "integer"]:
return int
elif type_hint in ["bool", "boolean"]:
return bool
elif type_hint == "tuple":
return _UNSUPPORTED
elif type_hint == "set":
return _UNSUPPORTED
elif type_hint == "list of floats":
return _UNSUPPORTED
elif type_hint == "list of floats or float":
return float
elif type_hint in ["dict", "dictionary"]:
return _UNSUPPORTED
elif type_hint == "scalar or dictionary":
return float
elif type_hint == "none or dict":
return _SKIP
elif type_hint in ["function", "callable"]:
return _UNSUPPORTED
elif type_hint in [
"collection",
"container of nodes",
"list of nodes",
]:
return _UNSUPPORTED
elif type_hint in [
"container",
"generator",
"iterable",
"iterator",
"list or iterable container",
"list or iterable",
"list or set",
"list or tuple",
"list",
]:
return _UNSUPPORTED
elif type_hint == "generator of sets":
return _UNSUPPORTED
elif type_hint == "dict or a set of 2 or 3 tuples":
return _UNSUPPORTED
elif type_hint == "set of 2 or 3 tuples":
return _UNSUPPORTED
elif type_hint == "none, string or function":
return str | None
elif type_hint == "string or function" and name == "weight":
return str
elif type_hint == "integer, float, or none":
return float | None
elif type_hint in [
"float",
"int or float",
"integer or float",
"integer, float",
"number",
"numeric",
"real",
"scalar",
]:
return float
elif type_hint in ["integer or none", "int or none"]:
return int | None
elif name == "seed":
return int | None
elif name == "weight":
return str
elif type_hint == "object":
return _UNSUPPORTED
return _SKIP
def types_from_doc(doc: str) -> dict[str, type]:
types = {}
for line in doc.splitlines():
if ":" in line:
a, b = line.split(":", 1)
for a in a.split(","):
a = a.strip()
types[a] = doc_to_type(a, b)
return types
def wrapped(name: str, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for k, v in kwargs.items():
if v == "None":
kwargs[k] = None
res = func(*args, **kwargs)
# Figure out what the returned value is.
if isinstance(res, nx.Graph):
return res
if isinstance(res, types.GeneratorType):
res = list(res)
if name in ["articulation_points"]:
graph = args[0].copy()
nx.set_node_attributes(graph, 0, name=name)
nx.set_node_attributes(graph, {r: 1 for r in res}, name=name)
return graph
if isinstance(res, collections.abc.Sized):
if len(res) == 0:
return pd.DataFrame()
for a in args:
if isinstance(a, nx.Graph):
if a.number_of_nodes() == len(res):
graph = a.copy()
nx.set_node_attributes(graph, values=res, name=name)
return graph
if a.number_of_edges() == len(res):
graph = a.copy()
nx.set_edge_attributes(graph, values=res, name=name)
return graph
return pd.DataFrame({name: res})
return pd.DataFrame({name: [res]})
return wrapper
def _get_params(func) -> dict | None:
sig = inspect.signature(func)
# Get types from docstring.
types = types_from_doc(func.__doc__)
# Always hide these.
for k in ["backend", "backend_kwargs", "create_using"]:
types[k] = _SKIP
# Add in types based on signature.
for k, param in sig.parameters.items():
if k in types:
continue
if param.annotation is not param.empty:
types[k] = param.annotation
if k in ["i", "j", "n"]:
types[k] = int
params = {}
for name, param in sig.parameters.items():
_type = types.get(name, _UNSUPPORTED)
if _type is _UNSUPPORTED:
raise UnsupportedParameterType(name)
if _type is _SKIP or _type in [nx.Graph, nx.DiGraph]:
continue
params[name] = ops.Parameter.basic(
name=name,
default=str(param.default)
if type(param.default) in [str, int, float]
else None,
type=_type,
)
return params
_REPLACEMENTS = [
("Barabasi Albert", "Barabasi–Albert"),
("Bellman Ford", "Bellman–Ford"),
("Bethe Hessian", "Bethe–Hessian"),
("Bfs", "BFS"),
("Dag ", "DAG "),
("Dfs", "DFS"),
("Dorogovtsev Goltsev Mendes", "Dorogovtsev–Goltsev–Mendes"),
("Erdos Renyi", "Erdos–Renyi"),
("Floyd Warshall", "Floyd–Warshall"),
("Gnc", "G(n,c)"),
("Gnm", "G(n,m)"),
("Gnp", "G(n,p)"),
("Gnr", "G(n,r)"),
("Havel Hakimi", "Havel–Hakimi"),
("Hkn", "H(k,n)"),
("Hnm", "H(n,m)"),
("Kl ", "KL "),
("Moebius Kantor", "Moebius–Kantor"),
("Pagerank", "PageRank"),
("Scale Free", "Scale-Free"),
("Vf2Pp", "VF2++"),
("Watts Strogatz", "Watts–Strogatz"),
("Weisfeiler Lehman", "Weisfeiler–Lehman"),
]
def register_networkx(env: str):
cat = ops.CATALOGS.setdefault(env, {})
counter = 0
for name, func in nx.__dict__.items():
if hasattr(func, "graphs"):
try:
params = _get_params(func)
except UnsupportedParameterType:
continue
inputs = {k: ops.Input(name=k, type=nx.Graph) for k in func.graphs}
nicename = "NX › " + name.replace("_", " ").title()
for a, b in _REPLACEMENTS:
nicename = nicename.replace(a, b)
op = ops.Op(
func=wrapped(name, func),
name=nicename,
params=params,
inputs=inputs,
outputs={"output": ops.Output(name="output", type=nx.Graph)},
type="basic",
)
cat[nicename] = op
counter += 1
print(f"Registered {counter} NetworkX operations.")
register_networkx(ENV)
|