lightgraph 1.2.0__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.2.0
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
+ ```
@@ -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):
@@ -4,7 +4,7 @@ build-backend = "flit_core.buildapi"
4
4
 
5
5
  [project]
6
6
  name = "lightgraph"
7
- version = "1.2.0"
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