neo4j-viz 0.3.1__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/PKG-INFO +1 -1
  2. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/pyproject.toml +1 -1
  3. neo4j_viz-0.4.0/src/neo4j_viz/__init__.py +25 -0
  4. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/gds.py +71 -13
  5. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/gql_create.py +46 -12
  6. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/neo4j.py +44 -9
  7. neo4j_viz-0.4.0/src/neo4j_viz/options.py +183 -0
  8. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/pandas.py +57 -13
  9. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/visualization_graph.py +22 -2
  10. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz.egg-info/PKG-INFO +1 -1
  11. neo4j_viz-0.4.0/tests/test_gds.py +260 -0
  12. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/tests/test_gql_create.py +27 -0
  13. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/tests/test_neo4j.py +40 -0
  14. neo4j_viz-0.4.0/tests/test_options.py +24 -0
  15. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/tests/test_pandas.py +86 -0
  16. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/tests/test_render.py +22 -0
  17. neo4j_viz-0.3.1/src/neo4j_viz/__init__.py +0 -6
  18. neo4j_viz-0.3.1/src/neo4j_viz/options.py +0 -88
  19. neo4j_viz-0.3.1/tests/test_gds.py +0 -134
  20. neo4j_viz-0.3.1/tests/test_options.py +0 -7
  21. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/README.md +0 -0
  22. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/setup.cfg +0 -0
  23. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/colors.py +0 -0
  24. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/node.py +0 -0
  25. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/node_size.py +0 -0
  26. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/nvl.py +0 -0
  27. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/py.typed +0 -0
  28. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/relationship.py +0 -0
  29. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/resources/icons/screenshot.svg +0 -0
  30. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/resources/icons/zoom-in.svg +0 -0
  31. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/resources/icons/zoom-out.svg +0 -0
  32. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/resources/nvl_entrypoint/base.js +0 -0
  33. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz/resources/nvl_entrypoint/styles.css +0 -0
  34. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz.egg-info/SOURCES.txt +0 -0
  35. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz.egg-info/dependency_links.txt +0 -0
  36. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz.egg-info/requires.txt +0 -0
  37. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/src/neo4j_viz.egg-info/top_level.txt +0 -0
  38. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/tests/test_colors.py +0 -0
  39. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/tests/test_node.py +0 -0
  40. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/tests/test_notebooks.py +0 -0
  41. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/tests/test_pinned.py +0 -0
  42. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/tests/test_relationship.py +0 -0
  43. {neo4j_viz-0.3.1 → neo4j_viz-0.4.0}/tests/test_sizes.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: neo4j-viz
3
- Version: 0.3.1
3
+ Version: 0.4.0
4
4
  Summary: A simple graph visualization tool
5
5
  Author-email: Neo4j <team-gds@neo4j.org>
6
6
  Project-URL: Homepage, https://neo4j.com/
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "neo4j-viz"
7
- version = "0.3.1"
7
+ version = "0.4.0"
8
8
  description = "A simple graph visualization tool"
9
9
  readme = "README.md"
10
10
  authors = [{ name = "Neo4j", email = "team-gds@neo4j.org" }]
@@ -0,0 +1,25 @@
1
+ from .node import Node
2
+ from .options import (
3
+ CaptionAlignment,
4
+ Direction,
5
+ ForceDirectedLayoutOptions,
6
+ HierarchicalLayoutOptions,
7
+ Layout,
8
+ Packing,
9
+ Renderer,
10
+ )
11
+ from .relationship import Relationship
12
+ from .visualization_graph import VisualizationGraph
13
+
14
+ __all__ = [
15
+ "VisualizationGraph",
16
+ "Node",
17
+ "Relationship",
18
+ "CaptionAlignment",
19
+ "Layout",
20
+ "Renderer",
21
+ "ForceDirectedLayoutOptions",
22
+ "HierarchicalLayoutOptions",
23
+ "Direction",
24
+ "Packing",
25
+ ]
@@ -2,15 +2,17 @@ from __future__ import annotations
2
2
 
3
3
  from itertools import chain
4
4
  from typing import Optional
5
+ from uuid import uuid4
5
6
 
6
7
  import pandas as pd
7
8
  from graphdatascience import Graph, GraphDataScience
9
+ from pandas import Series
8
10
 
9
11
  from .pandas import _from_dfs
10
12
  from .visualization_graph import VisualizationGraph
11
13
 
12
14
 
13
- def _node_dfs(
15
+ def _fetch_node_dfs(
14
16
  gds: GraphDataScience, G: Graph, node_properties: list[str], node_labels: list[str]
15
17
  ) -> dict[str, pd.DataFrame]:
16
18
  return {
@@ -21,7 +23,21 @@ def _node_dfs(
21
23
  }
22
24
 
23
25
 
24
- def _rel_df(gds: GraphDataScience, G: Graph) -> pd.DataFrame:
26
+ def _fetch_rel_df(gds: GraphDataScience, G: Graph) -> pd.DataFrame:
27
+ relationship_properties = G.relationship_properties()
28
+ assert isinstance(relationship_properties, Series)
29
+
30
+ relationship_properties_per_type = relationship_properties.tolist()
31
+ property_set: set[str] = set()
32
+ for props in relationship_properties_per_type:
33
+ if props:
34
+ property_set.update(props)
35
+
36
+ if len(property_set) > 0:
37
+ return gds.graph.relationshipProperties.stream(
38
+ G, relationship_properties=list(property_set), separate_property_columns=True
39
+ )
40
+
25
41
  return gds.graph.relationships.stream(G)
26
42
 
27
43
 
@@ -31,6 +47,7 @@ def from_gds(
31
47
  size_property: Optional[str] = None,
32
48
  additional_node_properties: Optional[list[str]] = None,
33
49
  node_radius_min_max: Optional[tuple[float, float]] = (3, 60),
50
+ max_node_count: int = 10_000,
34
51
  ) -> VisualizationGraph:
35
52
  """
36
53
  Create a VisualizationGraph from a GraphDataScience object and a Graph object.
@@ -49,10 +66,14 @@ def from_gds(
49
66
  size_property : str, optional
50
67
  Property to use for node size, by default None.
51
68
  additional_node_properties : list[str], optional
52
- Additional properties to include in the visualization node, by default None. They can be used later for modifying the node appearance.
69
+ Additional properties to include in the visualization node, by default None which means that all node
70
+ properties will be fetched.
53
71
  node_radius_min_max : tuple[float, float], optional
54
72
  Minimum and maximum node radius, by default (3, 60).
55
73
  To avoid tiny or huge nodes in the visualization, the node sizes are scaled to fit in the given range.
74
+ max_node_count : int, optional
75
+ The maximum number of nodes to fetch from the graph. The graph will be sampled using random walk with restarts
76
+ if its node count exceeds this number.
56
77
  """
57
78
  node_properties_from_gds = G.node_properties()
58
79
  assert isinstance(node_properties_from_gds, pd.Series)
@@ -61,7 +82,9 @@ def from_gds(
61
82
  if size_property is not None and size_property not in actual_node_properties:
62
83
  raise ValueError(f"There is no node property '{size_property}' in graph '{G.name()}'")
63
84
 
64
- if additional_node_properties is not None:
85
+ if additional_node_properties is None:
86
+ additional_node_properties = actual_node_properties
87
+ else:
65
88
  for prop in additional_node_properties:
66
89
  if prop not in actual_node_properties:
67
90
  raise ValueError(f"There is no node property '{prop}' in graph '{G.name()}'")
@@ -69,14 +92,40 @@ def from_gds(
69
92
  node_properties = set()
70
93
  if additional_node_properties is not None:
71
94
  node_properties.update(additional_node_properties)
72
-
73
95
  if size_property is not None:
74
96
  node_properties.add(size_property)
75
-
76
97
  node_properties = list(node_properties)
77
- node_dfs = _node_dfs(gds, G, node_properties, G.node_labels())
98
+
99
+ node_count = G.node_count()
100
+ if node_count > max_node_count:
101
+ sampling_ratio = float(max_node_count) / node_count
102
+ sample_name = f"neo4j-viz_sample_{uuid4()}"
103
+ G_fetched, _ = gds.graph.sample.rwr(sample_name, G, samplingRatio=sampling_ratio, nodeLabelStratification=True)
104
+ else:
105
+ G_fetched = G
106
+
107
+ property_name = None
108
+ try:
109
+ # Since GDS does not allow us to only fetch node IDs, we add the degree property
110
+ # as a temporary property to ensure that we have at least one property to fetch
111
+ if len(actual_node_properties) == 0:
112
+ property_name = f"neo4j-viz_property_{uuid4()}"
113
+ gds.degree.mutate(G_fetched, mutateProperty=property_name)
114
+ node_properties = [property_name]
115
+
116
+ node_dfs = _fetch_node_dfs(gds, G_fetched, node_properties, G_fetched.node_labels())
117
+ rel_df = _fetch_rel_df(gds, G_fetched)
118
+ finally:
119
+ if G_fetched.name() != G.name():
120
+ G_fetched.drop()
121
+ elif property_name is not None:
122
+ gds.graph.nodeProperties.drop(G_fetched, node_properties=[property_name])
123
+
78
124
  for df in node_dfs.values():
79
125
  df.rename(columns={"nodeId": "id"}, inplace=True)
126
+ if property_name is not None and property_name in df.columns:
127
+ df.drop(columns=[property_name], inplace=True)
128
+ rel_df.rename(columns={"sourceNodeId": "source", "targetNodeId": "target"}, inplace=True)
80
129
 
81
130
  node_props_df = pd.concat(node_dfs.values(), ignore_index=True, axis=0).drop_duplicates()
82
131
  if size_property is not None:
@@ -89,12 +138,21 @@ def from_gds(
89
138
  df.rename(columns={"labels": "__labels"}, inplace=True)
90
139
  df["labels"] = lbl
91
140
 
92
- node_lbls_df = pd.concat([df[["id", "labels"]] for df in node_dfs.values()], ignore_index=True, axis=0)
93
- node_lbls_df = node_lbls_df.groupby("id").agg({"labels": list})
141
+ node_labels_df = pd.concat([df[["id", "labels"]] for df in node_dfs.values()], ignore_index=True, axis=0)
142
+ node_labels_df = node_labels_df.groupby("id").agg({"labels": list})
94
143
 
95
- node_df = node_props_df.merge(node_lbls_df, on="id")
144
+ node_df = node_props_df.merge(node_labels_df, on="id")
96
145
 
97
- rel_df = _rel_df(gds, G)
98
- rel_df.rename(columns={"sourceNodeId": "source", "targetNodeId": "target"}, inplace=True)
146
+ if "caption" not in actual_node_properties:
147
+ node_df["caption"] = node_df["labels"].astype(str)
99
148
 
100
- return _from_dfs(node_df, rel_df, node_radius_min_max=node_radius_min_max, rename_properties={"__size": "size"})
149
+ try:
150
+ return _from_dfs(node_df, rel_df, node_radius_min_max=node_radius_min_max, rename_properties={"__size": "size"})
151
+ except ValueError as e:
152
+ err_msg = str(e)
153
+ if "column" in err_msg:
154
+ err_msg = err_msg.replace("column", "property")
155
+ if ("'size'" in err_msg) and (size_property is not None):
156
+ err_msg = err_msg.replace("'size'", f"'{size_property}'")
157
+ raise ValueError(err_msg)
158
+ raise e
@@ -2,6 +2,8 @@ import re
2
2
  import uuid
3
3
  from typing import Any, Optional
4
4
 
5
+ from pydantic import BaseModel, ValidationError
6
+
5
7
  from neo4j_viz import Node, Relationship, VisualizationGraph
6
8
 
7
9
 
@@ -252,6 +254,20 @@ def from_gql_create(
252
254
  node_top_level_keys = Node.all_validation_aliases(exempted_fields=["id"])
253
255
  rel_top_level_keys = Relationship.all_validation_aliases(exempted_fields=["id", "source", "target"])
254
256
 
257
+ def _parse_validation_error(e: ValidationError, entity_type: type[BaseModel]) -> None:
258
+ for err in e.errors():
259
+ loc = err["loc"][0]
260
+ if (loc == "size") and size_property is not None:
261
+ loc = size_property
262
+ if loc == "caption":
263
+ if (entity_type == Node) and (node_caption is not None):
264
+ loc = node_caption
265
+ elif (entity_type == Relationship) and (relationship_caption is not None):
266
+ loc = relationship_caption
267
+ raise ValueError(
268
+ f"Error for {entity_type.__name__.lower()} property '{loc}' with provided input '{err['input']}'. Reason: {err['msg']}"
269
+ )
270
+
255
271
  nodes = []
256
272
  relationships = []
257
273
  alias_to_id = {}
@@ -267,7 +283,10 @@ def from_gql_create(
267
283
  anonymous_count += 1
268
284
  if alias not in alias_to_id:
269
285
  alias_to_id[alias] = str(uuid.uuid4())
270
- nodes.append(Node(id=alias_to_id[alias], **top_level, properties=props))
286
+ try:
287
+ nodes.append(Node(id=alias_to_id[alias], **top_level, properties=props))
288
+ except ValidationError as e:
289
+ _parse_validation_error(e, Node)
271
290
 
272
291
  continue
273
292
 
@@ -283,7 +302,10 @@ def from_gql_create(
283
302
  anonymous_count += 1
284
303
  if left_alias not in alias_to_id:
285
304
  alias_to_id[left_alias] = str(uuid.uuid4())
286
- nodes.append(Node(id=alias_to_id[left_alias], **left_top_level, properties=left_props))
305
+ try:
306
+ nodes.append(Node(id=alias_to_id[left_alias], **left_top_level, properties=left_props))
307
+ except ValidationError as e:
308
+ _parse_validation_error(e, Node)
287
309
  elif left_alias not in alias_to_id:
288
310
  snippet = _get_snippet(query, query.index(left_node))
289
311
  raise ValueError(f"Relationship references unknown node alias: '{left_alias}' near: `{snippet}`.")
@@ -295,7 +317,10 @@ def from_gql_create(
295
317
  anonymous_count += 1
296
318
  if right_alias not in alias_to_id:
297
319
  alias_to_id[right_alias] = str(uuid.uuid4())
298
- nodes.append(Node(id=alias_to_id[right_alias], **right_top_level, properties=right_props))
320
+ try:
321
+ nodes.append(Node(id=alias_to_id[right_alias], **right_top_level, properties=right_props))
322
+ except ValidationError as e:
323
+ _parse_validation_error(e, Node)
299
324
  elif right_alias not in alias_to_id:
300
325
  snippet = _get_snippet(query, query.index(right_node))
301
326
  raise ValueError(f"Relationship references unknown node alias: '{right_alias}' near: `{snippet}`.")
@@ -313,15 +338,20 @@ def from_gql_create(
313
338
  if "type" in props:
314
339
  props["__type"] = props["type"]
315
340
  props["type"] = rel_type
316
- relationships.append(
317
- Relationship(
318
- id=rel_id,
319
- source=alias_to_id[left_alias],
320
- target=alias_to_id[right_alias],
321
- **top_level,
322
- properties=props,
341
+
342
+ try:
343
+ relationships.append(
344
+ Relationship(
345
+ id=rel_id,
346
+ source=alias_to_id[left_alias],
347
+ target=alias_to_id[right_alias],
348
+ **top_level,
349
+ properties=props,
350
+ )
323
351
  )
324
- )
352
+ except ValidationError as e:
353
+ _parse_validation_error(e, Relationship)
354
+
325
355
  continue
326
356
 
327
357
  snippet = part[:30]
@@ -346,6 +376,10 @@ def from_gql_create(
346
376
 
347
377
  VG = VisualizationGraph(nodes=nodes, relationships=relationships)
348
378
  if (node_radius_min_max is not None) and (size_property is not None):
349
- VG.resize_nodes(node_radius_min_max=node_radius_min_max)
379
+ try:
380
+ VG.resize_nodes(node_radius_min_max=node_radius_min_max)
381
+ except TypeError:
382
+ loc = "size" if size_property is None else size_property
383
+ raise ValueError(f"Error for node property '{loc}'. Reason: must be a numerical value")
350
384
 
351
385
  return VG
@@ -4,12 +4,21 @@ from typing import Optional, Union
4
4
 
5
5
  import neo4j.graph
6
6
  from neo4j import Result
7
+ from pydantic import BaseModel, ValidationError
7
8
 
8
9
  from neo4j_viz.node import Node
9
10
  from neo4j_viz.relationship import Relationship
10
11
  from neo4j_viz.visualization_graph import VisualizationGraph
11
12
 
12
13
 
14
+ def _parse_validation_error(e: ValidationError, entity_type: type[BaseModel]) -> None:
15
+ for err in e.errors():
16
+ loc = err["loc"][0]
17
+ raise ValueError(
18
+ f"Error for {entity_type.__name__.lower()} property '{loc}' with provided input '{err['input']}'. Reason: {err['msg']}"
19
+ )
20
+
21
+
13
22
  def from_neo4j(
14
23
  result: Union[neo4j.graph.Graph, Result],
15
24
  size_property: Optional[str] = None,
@@ -50,14 +59,30 @@ def from_neo4j(
50
59
  all_node_field_aliases = Node.all_validation_aliases()
51
60
  all_rel_field_aliases = Relationship.all_validation_aliases()
52
61
 
53
- nodes = [
54
- _map_node(node, all_node_field_aliases, size_property, caption_property=node_caption) for node in graph.nodes
55
- ]
62
+ try:
63
+ nodes = [
64
+ _map_node(node, all_node_field_aliases, size_property, caption_property=node_caption)
65
+ for node in graph.nodes
66
+ ]
67
+ except ValueError as e:
68
+ err_msg = str(e)
69
+ if ("'size'" in err_msg) and (size_property is not None):
70
+ err_msg = err_msg.replace("'size'", f"'{size_property}'")
71
+ elif ("'caption'" in err_msg) and (node_caption is not None):
72
+ err_msg = err_msg.replace("'caption'", f"'{node_caption}'")
73
+ raise ValueError(err_msg)
74
+
56
75
  relationships = []
57
- for rel in graph.relationships:
58
- mapped_rel = _map_relationship(rel, all_rel_field_aliases, caption_property=relationship_caption)
59
- if mapped_rel:
60
- relationships.append(mapped_rel)
76
+ try:
77
+ for rel in graph.relationships:
78
+ mapped_rel = _map_relationship(rel, all_rel_field_aliases, caption_property=relationship_caption)
79
+ if mapped_rel:
80
+ relationships.append(mapped_rel)
81
+ except ValueError as e:
82
+ err_msg = str(e)
83
+ if ("'caption'" in err_msg) and (relationship_caption is not None):
84
+ err_msg = err_msg.replace("'caption'", f"'{relationship_caption}'")
85
+ raise ValueError(err_msg)
61
86
 
62
87
  VG = VisualizationGraph(nodes, relationships)
63
88
 
@@ -102,7 +127,12 @@ def _map_node(
102
127
  properties["__labels"] = properties["labels"]
103
128
  properties["labels"] = labels
104
129
 
105
- return Node(**top_level_fields, properties=properties)
130
+ try:
131
+ viz_node = Node(**top_level_fields, properties=properties)
132
+ except ValidationError as e:
133
+ _parse_validation_error(e, Node)
134
+
135
+ return viz_node
106
136
 
107
137
 
108
138
  def _map_relationship(
@@ -135,4 +165,9 @@ def _map_relationship(
135
165
  properties["__type"] = properties["type"]
136
166
  properties["type"] = rel.type
137
167
 
138
- return Relationship(**top_level_fields, properties=properties)
168
+ try:
169
+ viz_rel = Relationship(**top_level_fields, properties=properties)
170
+ except ValidationError as e:
171
+ _parse_validation_error(e, Relationship)
172
+
173
+ return viz_rel
@@ -0,0 +1,183 @@
1
+ from __future__ import annotations
2
+
3
+ import warnings
4
+ from enum import Enum
5
+ from typing import Any, Optional, Union
6
+
7
+ import enum_tools.documentation
8
+ from pydantic import BaseModel, Field, ValidationError, model_validator
9
+
10
+
11
+ @enum_tools.documentation.document_enum
12
+ class CaptionAlignment(str, Enum):
13
+ """
14
+ The alignment of the caption text for nodes and relationships.
15
+ """
16
+
17
+ TOP = "top"
18
+ CENTER = "center"
19
+ BOTTOM = "bottom"
20
+
21
+
22
+ @enum_tools.documentation.document_enum
23
+ class Layout(str, Enum):
24
+ FORCE_DIRECTED = "forcedirected"
25
+ HIERARCHICAL = "hierarchical"
26
+ """
27
+ The nodes are then arranged by the directionality of their relationships
28
+ """
29
+ COORDINATE = "free"
30
+ """
31
+ The coordinate layout sets the position of each node based on the `x` and `y` properties of the node.
32
+ """
33
+ GRID = "grid"
34
+
35
+
36
+ @enum_tools.documentation.document_enum
37
+ class Direction(str, Enum):
38
+ """
39
+ The direction in which the layout should be oriented
40
+ """
41
+
42
+ LEFT = "left"
43
+ RIGHT = "right"
44
+ UP = "up"
45
+ DOWN = "down"
46
+
47
+
48
+ @enum_tools.documentation.document_enum
49
+ class Packing(str, Enum):
50
+ """
51
+ The packing method to be used
52
+ """
53
+
54
+ BIN = "bin"
55
+ STACK = "stack"
56
+
57
+
58
+ class HierarchicalLayoutOptions(BaseModel, extra="forbid"):
59
+ """
60
+ The options for the hierarchical layout.
61
+ """
62
+
63
+ direction: Optional[Direction] = None
64
+ packaging: Optional[Packing] = None
65
+
66
+
67
+ class ForceDirectedLayoutOptions(BaseModel, extra="forbid"):
68
+ """
69
+ The options for the force-directed layout.
70
+ """
71
+
72
+ gravity: Optional[float] = None
73
+ simulationStopVelocity: Optional[float] = None
74
+
75
+
76
+ LayoutOptions = Union[HierarchicalLayoutOptions, ForceDirectedLayoutOptions]
77
+
78
+
79
+ def construct_layout_options(layout: Layout, options: dict[str, Any]) -> Optional[LayoutOptions]:
80
+ if not options:
81
+ return None
82
+
83
+ if layout == Layout.FORCE_DIRECTED:
84
+ try:
85
+ return ForceDirectedLayoutOptions(**options)
86
+ except ValidationError as e:
87
+ _parse_validation_error(e, ForceDirectedLayoutOptions)
88
+ elif layout == Layout.HIERARCHICAL:
89
+ try:
90
+ return HierarchicalLayoutOptions(**options)
91
+ except ValidationError as e:
92
+ _parse_validation_error(e, ForceDirectedLayoutOptions)
93
+
94
+ raise ValueError(
95
+ f"Layout options only supported for layouts `{Layout.FORCE_DIRECTED}` and `{Layout.HIERARCHICAL}`, but was `{layout}`"
96
+ )
97
+
98
+
99
+ @enum_tools.documentation.document_enum
100
+ class Renderer(str, Enum):
101
+ """
102
+ The renderer used to render the visualization.
103
+ """
104
+
105
+ WEB_GL = "webgl"
106
+ """
107
+ The WebGL renderer is optimized for performance and handles large graphs better.
108
+ However, it does not render text, icons, and arrowheads on relationships.
109
+ """
110
+ CANVAS = "canvas"
111
+ """
112
+ The canvas renderer has worse performance than the WebGL renderer, so is less well suited to render large graphs.
113
+ However, it can render text, icons, and arrowheads on relationships.
114
+ """
115
+
116
+ @classmethod
117
+ def check(self, renderer: Renderer, num_nodes: int) -> None:
118
+ if renderer == Renderer.CANVAS and num_nodes > 10_000:
119
+ warnings.warn(
120
+ "To visualize more than 10.000 nodes, we recommend using the WebGL renderer "
121
+ "instead of the canvas renderer for better performance. You can set the renderer "
122
+ "using the `renderer` parameter"
123
+ )
124
+ if renderer == Renderer.WEB_GL:
125
+ warnings.warn(
126
+ "Although better for performance, the WebGL renderer cannot render text, icons "
127
+ "and arrowheads on relationships. If you need these features, use the canvas renderer "
128
+ "by setting the `renderer` parameter"
129
+ )
130
+
131
+
132
+ class RenderOptions(BaseModel, extra="allow"):
133
+ """
134
+ Options as documented at https://neo4j.com/docs/nvl/current/base-library/#_options
135
+ """
136
+
137
+ layout: Optional[Layout] = None
138
+ layout_options: Optional[Union[HierarchicalLayoutOptions, ForceDirectedLayoutOptions]] = Field(
139
+ None, serialization_alias="layoutOptions"
140
+ )
141
+ renderer: Optional[Renderer] = None
142
+
143
+ pan_X: Optional[float] = Field(None, serialization_alias="panX")
144
+ pan_Y: Optional[float] = Field(None, serialization_alias="panY")
145
+
146
+ initial_zoom: Optional[float] = Field(None, serialization_alias="initialZoom", description="The initial zoom level")
147
+ max_zoom: Optional[float] = Field(
148
+ None, serialization_alias="maxZoom", description="The maximum zoom level allowed."
149
+ )
150
+ min_zoom: Optional[float] = Field(None, serialization_alias="minZoom", description="The minimum zoom level allowed")
151
+ allow_dynamic_min_zoom: Optional[bool] = Field(None, serialization_alias="allowDynamicMinZoom")
152
+
153
+ @model_validator(mode="after")
154
+ def check_layout_options_match(self) -> RenderOptions:
155
+ if self.layout_options is None:
156
+ return self
157
+
158
+ if self.layout == Layout.HIERARCHICAL and not isinstance(self.layout_options, HierarchicalLayoutOptions):
159
+ raise ValueError("layout_options must be of type HierarchicalLayoutOptions for hierarchical layout")
160
+ if self.layout == Layout.FORCE_DIRECTED and not isinstance(self.layout_options, ForceDirectedLayoutOptions):
161
+ raise ValueError("layout_options must be of type ForceDirectedLayoutOptions for force-directed layout")
162
+ return self
163
+
164
+ def to_dict(self) -> dict[str, Any]:
165
+ return self.model_dump(exclude_none=True, by_alias=True)
166
+
167
+
168
+ def _parse_validation_error(e: ValidationError, entity_type: type[BaseModel]) -> None:
169
+ for err in e.errors():
170
+ loc = err["loc"][0]
171
+ if err["type"] == "missing":
172
+ raise ValueError(
173
+ f"Mandatory `{entity_type.__name__}` parameter '{loc}' is missing. Expected one of {entity_type.model_fields[loc].validation_alias.choices} to be present" # type: ignore
174
+ )
175
+ elif err["type"] == "extra_forbidden":
176
+ raise ValueError(
177
+ f"Unexpected `{entity_type.__name__}` parameter '{loc}' with provided input '{err['input']}'. "
178
+ f"Allowed parameters are: {', '.join(entity_type.model_fields.keys())}"
179
+ )
180
+ else:
181
+ raise ValueError(
182
+ f"Error for `{entity_type.__name__}` parameter '{loc}' with provided input '{err['input']}'. Reason: {err['msg']}"
183
+ )