lightgraph 1.1.1__tar.gz → 1.2.1__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.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: lightgraph
3
- Version: 1.1.1
3
+ Version: 1.2.1
4
4
  Summary: A lightweight Python binding for lightGraph network visualization
5
5
  Author-email: Hao Zhu <haozhu233@gmail.com>, Aiden McComiskey <aiden.mccomiskey@tufts.edu>, Donna Slonim <donna.slonim@tufts.edu>
6
6
  Requires-Python: >=3.6
@@ -11,6 +11,7 @@ Requires-Dist: pytest>=7.0 ; extra == "test"
11
11
  Requires-Dist: pytest-cov>=4.0 ; extra == "test"
12
12
  Project-URL: Homepage, https://github.com/haozhu233/lightgraph
13
13
  Provides-Extra: test
14
+ Import-Name: lightgraph
14
15
 
15
16
  # lightgraph
16
17
 
@@ -26,3 +27,18 @@ For python binding, you can install from pypi.
26
27
  pip install lightgraph
27
28
  ```
28
29
 
30
+ ## Citation
31
+
32
+ If you use `lightgraph` in your work, please cite the software using the
33
+ following BibTeX entry:
34
+
35
+ ```bibtex
36
+ @misc{lightgraph2026,
37
+ author = {Zhu, Hao and McComiskey, Aiden and Slonim, Donna},
38
+ title = {{lightgraph}: High-Performance HTML Canvas-Based Network Visualization},
39
+ year = {2026},
40
+ howpublished = {\url{https://github.com/haozhu233/lightgraph}},
41
+ note = {Version 1.2.1}
42
+ }
43
+ ```
44
+
@@ -0,0 +1,28 @@
1
+ # lightgraph
2
+
3
+ `lightgraph` is a high-performance HTML canvas-based network visualization tool.
4
+
5
+ ![](https://raw.githubusercontent.com/haozhu233/lightgraph/refs/heads/main/assets/lg_functions.png)
6
+
7
+ ## Installation
8
+
9
+ For python binding, you can install from pypi.
10
+
11
+ ```
12
+ pip install lightgraph
13
+ ```
14
+
15
+ ## Citation
16
+
17
+ If you use `lightgraph` in your work, please cite the software using the
18
+ following BibTeX entry:
19
+
20
+ ```bibtex
21
+ @misc{lightgraph2026,
22
+ author = {Zhu, Hao and McComiskey, Aiden and Slonim, Donna},
23
+ title = {{lightgraph}: High-Performance HTML Canvas-Based Network Visualization},
24
+ year = {2026},
25
+ howpublished = {\url{https://github.com/haozhu233/lightgraph}},
26
+ note = {Version 1.2.1}
27
+ }
28
+ ```
@@ -91,7 +91,15 @@
91
91
  groups: {
92
92
  fillOpacity: 0.125,
93
93
  strokeWidth: 2,
94
- showEllipses: true
94
+ showEllipses: true,
95
+ // Pinned assignments: {groupName: hexColor}. Wins over the
96
+ // palette for the named groups; unmatched names are ignored so
97
+ // one map can be reused across filtered subsets.
98
+ colors: null,
99
+ // Explicit palette domain: [groupName, ...]. Listed groups keep
100
+ // their palette slot even when absent from the data, so a shared
101
+ // order keeps colors stable across a series of figures.
102
+ colorOrder: null
95
103
  },
96
104
  canvas: {
97
105
  backgroundColor: '#ffffff',
@@ -918,6 +926,35 @@
918
926
  ...d3.schemeSet3
919
927
  ];
920
928
  const groupColorScale = d3.scaleOrdinal(extendedColors);
929
+ // Seed the palette domain deterministically on every data load:
930
+ // config.groups.colorOrder first (listed groups keep their slot even
931
+ // when absent from the data), then the remaining groups in sorted
932
+ // order. Without an explicit domain d3 assigns colors by first paint
933
+ // order, so the same group changes color whenever the node array does.
934
+ function updateGroupColorDomain() {
935
+ const present = [...new Set(nodes.map(n => n.group).filter(Boolean))].sort();
936
+ const order = config.groups.colorOrder;
937
+ const ordered = Array.isArray(order) ? order.map(String)
938
+ : (order != null ? [String(order)] : []);
939
+ const orderSet = new Set(ordered);
940
+ const domain = [...new Set([...ordered, ...present.filter(g => !orderSet.has(g))])];
941
+ if (domain.length > extendedColors.length) {
942
+ console.warn(`lightGraph: ${domain.length} groups exceed the `
943
+ + `${extendedColors.length}-color palette; colors will repeat. `
944
+ + `Pin colors via config.groups.colors to disambiguate.`);
945
+ }
946
+ groupColorScale.domain(domain);
947
+ }
948
+ // Single resolution point for every group-colored surface (legend
949
+ // swatch, node fill, ellipse, tooltip dot, SVG export): pinned
950
+ // config.groups.colors first, palette otherwise.
951
+ function getGroupColor(group) {
952
+ const pinned = config.groups.colors;
953
+ if (pinned && Object.prototype.hasOwnProperty.call(pinned, group)) {
954
+ return pinned[group];
955
+ }
956
+ return groupColorScale(group);
957
+ }
921
958
  // Modeless interaction: d3-zoom owns wheel events and drags that
922
959
  // start on empty space; node drags and shift box-selects fall
923
960
  // through to the canvas listeners below.
@@ -1148,7 +1185,7 @@
1148
1185
  width: '11px',
1149
1186
  height: '11px',
1150
1187
  borderRadius: '3px',
1151
- backgroundColor: groupColorScale(group),
1188
+ backgroundColor: getGroupColor(group),
1152
1189
  flexShrink: '0'
1153
1190
  });
1154
1191
 
@@ -1403,7 +1440,7 @@
1403
1440
  maxNodeSize = config.nodes.defaultSize;
1404
1441
  for (const d of nodes) {
1405
1442
  if (egoSet && !egoSet.has(d)) continue;
1406
- const color = d.group ? groupColorScale(d.group) : (d.color || config.nodes.defaultColor);
1443
+ const color = d.group ? getGroupColor(d.group) : (d.color || config.nodes.defaultColor);
1407
1444
  const isSelected = selectedNodes.has(d);
1408
1445
  const isFaded = highlightSet !== null && !highlightSet.has(d);
1409
1446
  let opacity = d.opacity !== undefined ? d.opacity : config.nodes.defaultOpacity;
@@ -1608,9 +1645,9 @@
1608
1645
  context.rotate(angle);
1609
1646
  context.beginPath();
1610
1647
  context.ellipse(0, 0, radiusX + 5, radiusY + 5, 0, 0, 2 * Math.PI);
1611
- context.fillStyle = hexToRgba(groupColorScale(group), config.groups.fillOpacity);
1648
+ context.fillStyle = hexToRgba(getGroupColor(group), config.groups.fillOpacity);
1612
1649
  context.fill();
1613
- context.strokeStyle = groupColorScale(group);
1650
+ context.strokeStyle = getGroupColor(group);
1614
1651
  context.lineWidth = config.groups.strokeWidth;
1615
1652
  context.stroke();
1616
1653
  context.restore();
@@ -1648,6 +1685,7 @@
1648
1685
  nodes = newNodes;
1649
1686
  edges = newEdges;
1650
1687
 
1688
+ updateGroupColorDomain();
1651
1689
  recalculateForce();
1652
1690
  updateEdgeAlpha();
1653
1691
  updateLegend();
@@ -1929,7 +1967,7 @@
1929
1967
  if (config.ui.showTooltips && hoveredNode) {
1930
1968
  let tooltipContent = `<strong>${escapeHtml(hoveredNode.id)}</strong>`;
1931
1969
  if (hoveredNode.group) {
1932
- tooltipContent += `<br><span style="color: ${groupColorScale(hoveredNode.group)};">● ${escapeHtml(hoveredNode.group)}</span>`;
1970
+ tooltipContent += `<br><span style="color: ${getGroupColor(hoveredNode.group)};">● ${escapeHtml(hoveredNode.group)}</span>`;
1933
1971
  }
1934
1972
  // Add any custom metadata
1935
1973
  if (hoveredNode.metadata) {
@@ -2158,7 +2196,7 @@
2158
2196
  circle.setAttribute('cy', node.y);
2159
2197
  circle.setAttribute('r',
2160
2198
  (node.size || config.nodes.defaultSize) * config.nodes.sizeScale / 2);
2161
- circle.setAttribute('fill', node.group ? groupColorScale(node.group) : (node.color || config.nodes.defaultColor));
2199
+ circle.setAttribute('fill', node.group ? getGroupColor(node.group) : (node.color || config.nodes.defaultColor));
2162
2200
  circle.setAttribute('stroke', config.nodes.borderColor);
2163
2201
  circle.setAttribute('stroke-width', config.nodes.borderWidth);
2164
2202
  g.appendChild(circle);
@@ -2246,6 +2284,9 @@
2246
2284
  // Merge a partial config over the current one and re-render.
2247
2285
  this.updateConfig = (partial = {}) => {
2248
2286
  config = mergeConfig(config, partial);
2287
+ if (partial.groups && ('colors' in partial.groups || 'colorOrder' in partial.groups)) {
2288
+ updateGroupColorDomain();
2289
+ }
2249
2290
  if (partial.edges && 'showArrows' in partial.edges) {
2250
2291
  showArrows = config.edges.showArrows;
2251
2292
  arrowsToggle.checked = showArrows;
@@ -8,7 +8,7 @@ import base64
8
8
  import uuid
9
9
  import numpy as np
10
10
  import os
11
- from typing import Optional, Dict, Union, Literal
11
+ from typing import Optional, Dict, List, Union, Literal
12
12
 
13
13
  from .analytics import _normalize_edges, communities as _communities
14
14
 
@@ -30,12 +30,21 @@ class NetworkVisualization:
30
30
  """The raw HTML content as a string."""
31
31
  return self._html
32
32
 
33
- def _repr_html_(self) -> str:
34
- """Jupyter rich display: renders in an iframe for DOM isolation."""
35
- full_html = (
33
+ def _full_document(self) -> str:
34
+ """Wrap the raw fragment in a standalone HTML document with an
35
+ explicit UTF-8 charset declaration. Without this, a file opened
36
+ directly in a browser/editor (no HTTP Content-Type header, no BOM)
37
+ has its encoding guessed, which mangles the non-ASCII characters
38
+ lightGraph's own UI uses (e.g. the legend bullet '●') into mojibake.
39
+ """
40
+ return (
36
41
  "<!DOCTYPE html><html><head><meta charset='utf-8'></head>"
37
42
  f"<body style='margin:0;padding:0;overflow:hidden;'>{self._html}</body></html>"
38
43
  )
44
+
45
+ def _repr_html_(self) -> str:
46
+ """Jupyter rich display: renders in an iframe for DOM isolation."""
47
+ full_html = self._full_document()
39
48
  b64 = base64.b64encode(full_html.encode('utf-8')).decode('ascii')
40
49
  uid = uuid.uuid4().hex[:8]
41
50
  return (
@@ -63,7 +72,7 @@ class NetworkVisualization:
63
72
  def save(self, filepath: str) -> None:
64
73
  """Save the visualization as a standalone HTML file."""
65
74
  with open(filepath, 'w', encoding='utf-8') as f:
66
- f.write(self._html)
75
+ f.write(self._full_document())
67
76
 
68
77
 
69
78
  def _edges_from_dense(adj_matrix, node_names, dedup_symmetric):
@@ -151,6 +160,8 @@ def net_vis(
151
160
  adj_matrix=None,
152
161
  node_names=None,
153
162
  node_groups: Optional[Union[Dict[str, str], str]] = None,
163
+ group_colors: Optional[Dict[str, str]] = None,
164
+ group_order: Optional[List[str]] = None,
154
165
  node_colors: Optional[Dict[str, str]] = None,
155
166
  node_sizes: Optional[Dict[str, float]] = None,
156
167
  remove_unconnected: bool = True,
@@ -252,6 +263,18 @@ def net_vis(
252
263
  Dictionary mapping node names to group identifiers for coloring.
253
264
  Pass 'auto' to detect communities automatically (networkx Louvain
254
265
  when installed, else a built-in label-propagation fallback).
266
+ group_colors : dict, optional
267
+ Mapping of group name to hex color (e.g. {'alpha': '#ff7f0e'}),
268
+ pinning those groups' colors. Unpinned groups stay on the default
269
+ palette. Names matching no group are ignored, so one mapping can be
270
+ reused across filtered subsets of the same data.
271
+ group_order : list, optional
272
+ Explicit group ordering for palette assignment. Groups keep their
273
+ palette slot even when absent from the data, so passing the same
274
+ list (e.g. computed once from the full dataset) to every figure in
275
+ a series keeps each group's color stable across subsets. Groups not
276
+ listed are appended in sorted order. Without group_order, groups
277
+ are assigned palette colors in sorted-name order.
255
278
  node_colors : dict, optional
256
279
  Dictionary mapping node names to hex color strings (e.g., '#FF5733').
257
280
  node_sizes : dict, optional
@@ -381,6 +404,10 @@ def net_vis(
381
404
  raise ValueError("node_groups must be a dictionary or 'auto'.")
382
405
  if node_colors is not None and not isinstance(node_colors, dict):
383
406
  raise ValueError("node_colors must be a dictionary.")
407
+ if group_colors is not None and not isinstance(group_colors, dict):
408
+ raise ValueError("group_colors must be a dictionary of {group: hex_color}.")
409
+ if group_order is not None and isinstance(group_order, (str, dict)):
410
+ raise ValueError("group_order must be a list of group names.")
384
411
  if node_sizes is not None and not isinstance(node_sizes, dict):
385
412
  raise ValueError("node_sizes must be a dictionary.")
386
413
  if node_metric is not None and not isinstance(node_metric, dict):
@@ -573,6 +600,11 @@ def net_vis(
573
600
  graph_config['ui']['metricLegend'] = metric_legend
574
601
 
575
602
  # Only set optional values if explicitly provided
603
+ if group_colors is not None:
604
+ graph_config['groups']['colors'] = {
605
+ str(k): str(v) for k, v in group_colors.items()}
606
+ if group_order is not None:
607
+ graph_config['groups']['colorOrder'] = [str(g) for g in group_order]
576
608
  if node_color is not None:
577
609
  graph_config['nodes']['defaultColor'] = node_color
578
610
  if edge_width is not None:
@@ -4,7 +4,7 @@ build-backend = "flit_core.buildapi"
4
4
 
5
5
  [project]
6
6
  name = "lightgraph"
7
- version = "1.1.1"
7
+ version = "1.2.1"
8
8
  description = "A lightweight Python binding for lightGraph network visualization"
9
9
  authors = [
10
10
  {name = "Hao Zhu", email = "haozhu233@gmail.com"},
@@ -1,13 +0,0 @@
1
- # lightgraph
2
-
3
- `lightgraph` is a high-performance HTML canvas-based network visualization tool.
4
-
5
- ![](https://raw.githubusercontent.com/haozhu233/lightgraph/refs/heads/main/assets/lg_functions.png)
6
-
7
- ## Installation
8
-
9
- For python binding, you can install from pypi.
10
-
11
- ```
12
- pip install lightgraph
13
- ```
@@ -1,10 +0,0 @@
1
- {
2
- "cells": [],
3
- "metadata": {
4
- "language_info": {
5
- "name": "python"
6
- }
7
- },
8
- "nbformat": 4,
9
- "nbformat_minor": 5
10
- }
@@ -1 +0,0 @@
1
- # Test package for lightgraph
@@ -1,259 +0,0 @@
1
- import json
2
- import math
3
- import pytest
4
-
5
- from lightgraph import net_vis
6
- from lightgraph.analytics import (
7
- degree, betweenness, closeness, eigenvector, pagerank,
8
- communities, components, neighbors, summary, top_nodes,
9
- )
10
-
11
-
12
- # Two triangles joined by a bridge (C-D), plus a separate pair (X-Y).
13
- EDGES = [
14
- ('A', 'B', 2), ('B', 'C', 1), ('C', 'A', 1),
15
- ('C', 'D', 1),
16
- ('D', 'E', 1), ('E', 'F', 1), ('F', 'D', 1),
17
- ('X', 'Y', 1),
18
- ]
19
-
20
- # A path graph: middle node has all the betweenness.
21
- PATH = [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')]
22
-
23
-
24
- class FakeSeries(list):
25
- @property
26
- def iloc(self):
27
- return self
28
-
29
-
30
- class FakeDataFrame:
31
- """Duck-typed stand-in for a pandas DataFrame (columns + iloc)."""
32
-
33
- def __init__(self, data):
34
- self._data = {k: FakeSeries(v) for k, v in data.items()}
35
- self.columns = list(data)
36
-
37
- def __getitem__(self, key):
38
- return self._data[key]
39
-
40
- def __contains__(self, key):
41
- return key in self._data
42
-
43
-
44
- class TestDegree:
45
- def test_counts_neighbors(self):
46
- d = degree(EDGES)
47
- assert d['C'] == 3.0
48
- assert d['A'] == 2.0
49
- assert d['X'] == 1.0
50
-
51
- def test_weighted_sums_weights(self):
52
- s = degree(EDGES, weighted=True)
53
- assert s['A'] == 3.0 # weight-2 edge to B plus weight-1 edge to C
54
- assert s['C'] == 3.0
55
-
56
- def test_ignores_self_loops(self):
57
- d = degree([('A', 'A'), ('A', 'B')])
58
- assert d['A'] == 1.0
59
-
60
- def test_accepts_dataframe(self):
61
- df = FakeDataFrame({'source': ['A', 'B'], 'target': ['B', 'C'],
62
- 'weight': [2.0, 1.0]})
63
- assert degree(df, weighted=True) == {'A': 2.0, 'B': 3.0, 'C': 1.0}
64
-
65
-
66
- class TestBetweenness:
67
- def test_path_graph(self):
68
- b = betweenness(PATH, normalized=False)
69
- # Middle node c lies on paths a-d, a-e, b-d, b-e = 4 pairs.
70
- assert b['c'] == pytest.approx(4.0)
71
- assert b['a'] == 0.0
72
-
73
- def test_normalized_range(self):
74
- b = betweenness(EDGES)
75
- assert all(0.0 <= v <= 1.0 for v in b.values())
76
- # The bridge endpoints carry all betweenness.
77
- assert b['C'] == max(b.values())
78
-
79
- def test_endpoints_zero(self):
80
- b = betweenness(PATH)
81
- assert b['a'] == 0.0 and b['e'] == 0.0
82
-
83
-
84
- class TestCloseness:
85
- def test_center_highest(self):
86
- c = closeness(PATH)
87
- assert c['c'] == max(c.values())
88
-
89
- def test_component_correction(self):
90
- # Nodes in the small component score lower than the big one.
91
- c = closeness(EDGES)
92
- assert c['X'] < min(c[v] for v in 'ABCDEF')
93
-
94
- def test_isolated_pair(self):
95
- c = closeness([('A', 'B')])
96
- assert c['A'] == pytest.approx(1.0)
97
-
98
-
99
- class TestEigenvector:
100
- def test_unit_norm(self):
101
- e = eigenvector(EDGES)
102
- assert math.sqrt(sum(v * v for v in e.values())) == pytest.approx(1.0)
103
-
104
- def test_star_center_highest(self):
105
- e = eigenvector([('hub', x) for x in 'abcd'])
106
- assert e['hub'] == max(e.values())
107
-
108
-
109
- class TestPagerank:
110
- def test_sums_to_one(self):
111
- p = pagerank(EDGES)
112
- assert sum(p.values()) == pytest.approx(1.0)
113
-
114
- def test_hub_highest(self):
115
- p = pagerank([('hub', x) for x in 'abcd'])
116
- assert p['hub'] == max(p.values())
117
-
118
- def test_uniform_on_cycle(self):
119
- p = pagerank([('a', 'b'), ('b', 'c'), ('c', 'a')])
120
- for v in p.values():
121
- assert v == pytest.approx(1 / 3)
122
-
123
-
124
- class TestCommunities:
125
- def test_detects_triangles(self):
126
- c = communities(EDGES)
127
- assert c['A'] == c['B'] == c['C']
128
- assert c['D'] == c['E'] == c['F']
129
- assert c['A'] != c['D']
130
-
131
- def test_labels_are_group_strings(self):
132
- c = communities(EDGES)
133
- assert all(v.startswith('c') for v in c.values())
134
-
135
-
136
- class TestComponents:
137
- def test_two_components(self):
138
- comp = components(EDGES)
139
- assert comp['A'] == comp['F'] == 1 # largest component first
140
- assert comp['X'] == comp['Y'] == 2
141
-
142
-
143
- class TestNeighbors:
144
- def test_depth_one(self):
145
- assert neighbors(EDGES, 'C') == ['A', 'B', 'C', 'D']
146
-
147
- def test_depth_two_spans_bridge(self):
148
- assert neighbors(EDGES, 'C', depth=2) == ['A', 'B', 'C', 'D', 'E', 'F']
149
-
150
- def test_unknown_node_raises(self):
151
- with pytest.raises(KeyError):
152
- neighbors(EDGES, 'missing')
153
-
154
-
155
- class TestSummary:
156
- def test_counts(self):
157
- s = summary(EDGES)
158
- assert s['nodes'] == 8
159
- assert s['edges'] == 8
160
- assert s['components'] == 2
161
- assert s['largest_component'] == 6
162
-
163
- def test_transitivity(self):
164
- # 2 triangles; triples = 1+1+3+3+1+1 = 10 -> 3*2/10.
165
- assert summary(EDGES)['transitivity'] == pytest.approx(0.6)
166
-
167
-
168
- class TestTopNodes:
169
- def test_orders_and_limits(self):
170
- top = top_nodes({'a': 1.0, 'b': 3.0, 'c': 2.0}, n=2)
171
- assert top == [('b', 3.0), ('c', 2.0)]
172
-
173
-
174
- class TestNetVisNewParams:
175
- def _config(self, result):
176
- html = result.html
177
- start = html.index('id="lightGraphConfig">') + len('id="lightGraphConfig">')
178
- end = html.index('</script>', start)
179
- return json.loads(html[start:end])
180
-
181
- def test_js_api_config_keys(self):
182
- result = net_vis(
183
- edges=EDGES, edge_width=0.5, edge_color='#123456',
184
- node_color='#654321', neighbor_fade=0.3, ego_filter=False,
185
- ego_depth=2, warmup_ticks=50, auto_fit=False,
186
- zoom_range=(0.05, 10), pixel_ratio=1, export_scale=3,
187
- weight_width_range=(1, 5), weight_opacity_range=(0.1, 0.9))
188
- config = self._config(result)
189
- assert config['edges']['defaultWidth'] == 0.5
190
- assert config['edges']['defaultColor'] == '#123456'
191
- assert config['nodes']['defaultColor'] == '#654321'
192
- assert config['highlight']['neighborFade'] == 0.3
193
- assert config['egoFilter'] == {'enabled': False, 'depth': 2}
194
- assert config['simulation']['warmupTicks'] == 50
195
- assert config['canvas']['autoFit'] is False
196
- assert config['canvas']['zoomMin'] == 0.05
197
- assert config['canvas']['zoomMax'] == 10
198
- assert config['canvas']['pixelRatio'] == 1
199
- assert config['canvas']['exportScale'] == 3
200
- assert config['edges']['weightWidthRange'] == [1, 5]
201
- assert config['edges']['weightOpacityRange'] == [0.1, 0.9]
202
-
203
- def test_adaptive_defaults_omitted(self):
204
- config = self._config(net_vis(edges=EDGES))
205
- assert 'defaultOpacity' not in config['edges']
206
- assert 'defaultWidth' not in config['edges']
207
- assert 'defaultColor' not in config['nodes']
208
- assert 'pixelRatio' not in config['canvas']
209
- assert 'backgroundColor' not in config['canvas']
210
-
211
- def test_config_escape_hatch_deep_merges(self):
212
- result = net_vis(edges=EDGES, config={
213
- 'nodes': {'borderWidth': 2},
214
- 'simulation': {'centerStrength': 0.5},
215
- })
216
- config = self._config(result)
217
- assert config['nodes']['borderWidth'] == 2
218
- assert config['nodes']['defaultSize'] == 7 # untouched sibling
219
- assert config['simulation']['centerStrength'] == 0.5
220
- assert config['simulation']['chargeStrength'] == 4000
221
-
222
- def test_nodes_table(self):
223
- nodes = [
224
- {'id': 'A', 'group': 'g1', 'size': 12},
225
- {'id': 'B', 'group': 'g2', 'color': '#ff0000'},
226
- {'id': 'C', 'group': None},
227
- ]
228
- result = net_vis(edges=[('A', 'B'), ('B', 'C')], nodes=nodes)
229
- payload = json.loads(result.html.split('id="nodesData">')[1]
230
- .split('</script>')[0])
231
- by_id = {n['id']: n for n in payload}
232
- assert by_id['A']['group'] == 'g1' and by_id['A']['size'] == 12.0
233
- assert by_id['B']['color'] == '#ff0000'
234
- assert 'group' not in by_id['C']
235
-
236
- def test_nodes_dataframe_and_explicit_dicts_win(self):
237
- nodes = FakeDataFrame({'id': ['A', 'B'], 'group': ['g1', 'g2']})
238
- result = net_vis(edges=[('A', 'B')], nodes=nodes,
239
- node_groups={'A': 'override'})
240
- payload = json.loads(result.html.split('id="nodesData">')[1]
241
- .split('</script>')[0])
242
- by_id = {n['id']: n for n in payload}
243
- assert by_id['A']['group'] == 'override'
244
- assert by_id['B']['group'] == 'g2'
245
-
246
- def test_nodes_table_keeps_edge_only_nodes(self):
247
- result = net_vis(edges=[('A', 'B'), ('B', 'Z')],
248
- nodes=[{'id': 'A'}, {'id': 'B'}])
249
- payload = json.loads(result.html.split('id="nodesData">')[1]
250
- .split('</script>')[0])
251
- assert {n['id'] for n in payload} == {'A', 'B', 'Z'}
252
-
253
- def test_analytics_pipe_into_net_vis(self):
254
- result = net_vis(edges=EDGES, node_metric=pagerank(EDGES),
255
- node_groups=communities(EDGES), metric_map='both')
256
- payload = json.loads(result.html.split('id="nodesData">')[1]
257
- .split('</script>')[0])
258
- assert all('size' in n and 'color' in n and 'group' in n
259
- for n in payload)
@@ -1,70 +0,0 @@
1
- """Tests for the bundled example datasets."""
2
- from lightgraph import datasets, net_vis, summary
3
-
4
-
5
- def _node_set(edges):
6
- out = set()
7
- for e in edges:
8
- out.add(e['source'])
9
- out.add(e['target'])
10
- return out
11
-
12
-
13
- class TestLesMis:
14
- def test_shape(self):
15
- edges = datasets.les_mis()
16
- assert len(edges) == 254
17
- assert len(_node_set(edges)) == 77
18
- assert set(edges[0]) == {'source', 'target', 'weight'}
19
-
20
- def test_weights_are_ints(self):
21
- assert all(isinstance(e['weight'], int) for e in datasets.les_mis())
22
-
23
- def test_known_characters(self):
24
- names = _node_set(datasets.les_mis())
25
- assert 'Valjean' in names
26
- assert 'Javert' in names
27
-
28
-
29
- class TestGot:
30
- def test_shape(self):
31
- edges = datasets.got()
32
- assert len(edges) == 352
33
- assert len(_node_set(edges)) == 107
34
- assert set(edges[0]) == {'source', 'target', 'weight'}
35
-
36
- def test_known_characters(self):
37
- names = _node_set(datasets.got())
38
- assert 'Tyrion' in names
39
- assert 'Jon' in names
40
-
41
-
42
- class TestFootball:
43
- def test_shape(self):
44
- nodes, edges = datasets.football()
45
- assert len(nodes) == 115
46
- assert len(edges) == 613
47
- assert set(nodes[0]) == {'id', 'group'}
48
- assert set(edges[0]) == {'source', 'target'}
49
-
50
- def test_twelve_conferences(self):
51
- nodes, _ = datasets.football()
52
- assert len({n['group'] for n in nodes}) == 12
53
-
54
- def test_edges_reference_known_nodes(self):
55
- nodes, edges = datasets.football()
56
- ids = {n['id'] for n in nodes}
57
- assert _node_set(edges) == ids
58
-
59
-
60
- class TestIntegration:
61
- def test_analytics_accepts_datasets(self):
62
- s = summary(datasets.got())
63
- assert s['nodes'] == 107
64
- assert s['edges'] == 352
65
- assert s['components'] == 1
66
-
67
- def test_net_vis_accepts_datasets(self):
68
- nodes, edges = datasets.football()
69
- vis = net_vis(edges=edges, nodes=nodes)
70
- assert 'Atlantic Coast' in vis.html