Skip to content

Commit 74e955a

Browse files
committed
fix: update documentation for hypergraph visualization
1 parent 1680cd3 commit 74e955a

File tree

3 files changed

+78
-78
lines changed

3 files changed

+78
-78
lines changed

docs/examples/basic-usage.md

Lines changed: 61 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -133,38 +133,40 @@ def find_frequently_bought_together(product_id, min_frequency=2):
133133
"""Find products frequently bought together with the given product."""
134134
# Find all shopping sessions containing this product
135135
sessions_with_product = hg.nbr_e_of_v(product_id)
136-
136+
137137
# Count co-occurrences
138138
co_occurrence = defaultdict(int)
139139
for session in sessions_with_product:
140140
other_products = hg.nbr_v_of_e(session) - {product_id}
141141
for other_product in other_products:
142142
co_occurrence[other_product] += 1
143-
143+
144144
# Filter by minimum frequency
145-
recommendations = {product: count for product, count in co_occurrence.items()
146-
if count >= min_frequency}
147-
145+
recommendations = {product: count for product, count in co_occurrence.items() if count >= min_frequency}
146+
148147
return sorted(recommendations.items(), key=lambda x: x[1], reverse=True)
149148

149+
150150
# Generate recommendations
151151
laptop_recommendations = find_frequently_bought_together("laptop_1")
152152
print("Products frequently bought with Gaming Laptop:")
153153
for product, frequency in laptop_recommendations:
154-
product_name = hg.v[product]["name"]
154+
product_name = hg.v(product)["name"]
155155
print(f" {product_name}: {frequency} times")
156156

157157
# Find most popular product categories
158158
category_popularity = defaultdict(int)
159159
for edge in hg.all_e:
160160
products_in_session = hg.nbr_v_of_e(edge)
161161
for product in products_in_session:
162-
category = hg.v[product]["category"]
162+
category = hg.v(product)["category"]
163163
category_popularity[category] += 1
164164

165165
print("\nCategory popularity:")
166166
for category, count in sorted(category_popularity.items(), key=lambda x: x[1], reverse=True):
167167
print(f" {category}: {count} purchases")
168+
169+
hg.draw()
168170
```
169171

170172
## Example 3: Social Network Group Analysis
@@ -173,6 +175,7 @@ Analyze group dynamics in social networks:
173175

174176
```python
175177
from hyperdb import HypergraphDB
178+
from collections import defaultdict
176179

177180
# Create social network
178181
hg = HypergraphDB()
@@ -186,7 +189,7 @@ people = {
186189
5: {"name": "Eve", "age": 27, "city": "Austin", "interests": ["art", "food"]},
187190
6: {"name": "Frank", "age": 35, "city": "Chicago", "interests": ["sports", "food"]},
188191
7: {"name": "Grace", "age": 29, "city": "Portland", "interests": ["travel", "music"]},
189-
8: {"name": "Henry", "age": 31, "city": "Denver", "interests": ["tech", "art"]}
192+
8: {"name": "Henry", "age": 31, "city": "Denver", "interests": ["tech", "art"]},
190193
}
191194

192195
for person_id, info in people.items():
@@ -197,91 +200,93 @@ activities = [
197200
# Small groups
198201
((1, 2), {"type": "coffee_meeting", "location": "Cafe Central", "date": "2024-01-10"}),
199202
((3, 5), {"type": "art_gallery", "location": "MoMA", "date": "2024-01-12"}),
200-
201-
# Medium groups
203+
# Medium groups
202204
((1, 2, 4), {"type": "tech_meetup", "location": "TechHub", "date": "2024-01-15"}),
203205
((3, 5, 7), {"type": "music_concert", "location": "Music Hall", "date": "2024-01-18"}),
204206
((2, 6), {"type": "sports_game", "location": "Stadium", "date": "2024-01-20"}),
205-
206207
# Large groups
207208
((1, 2, 3, 4, 5), {"type": "birthday_party", "location": "Alice's House", "date": "2024-01-25"}),
208209
((4, 6, 7, 8), {"type": "travel_planning", "location": "Online", "date": "2024-01-28"}),
209-
210210
# Very large group
211-
((1, 2, 3, 4, 5, 6, 7, 8), {"type": "company_picnic", "location": "Central Park", "date": "2024-02-01"})
211+
((1, 2, 3, 4, 5, 6, 7, 8), {"type": "company_picnic", "location": "Central Park", "date": "2024-02-01"}),
212212
]
213213

214214
for participants, activity_info in activities:
215215
hg.add_e(participants, activity_info)
216216

217+
217218
# Social network analysis
218219
def analyze_social_network(hg):
219220
"""Analyze the social network structure."""
220-
221+
221222
# Find most social person (highest degree)
222223
most_social = max(hg.all_v, key=lambda v: hg.degree_v(v))
223-
print(f"Most social person: {hg.v(most_social)['name']} "
224-
f"(participates in {hg.degree_v(most_social)} activities)")
225-
224+
print(
225+
f"Most social person: {hg.v(most_social)['name']} " f"(participates in {hg.degree_v(most_social)} activities)"
226+
)
227+
226228
# Analyze group sizes
227229
group_sizes = [hg.degree_e(e) for e in hg.all_e]
228230
avg_group_size = sum(group_sizes) / len(group_sizes)
229231
print(f"Average group size: {avg_group_size:.1f}")
230232
print(f"Largest group: {max(group_sizes)} people")
231233
print(f"Smallest group: {min(group_sizes)} people")
232-
234+
233235
# Find common interest groups
234236
interest_groups = defaultdict(set)
235237
for edge in hg.all_e:
236238
participants = hg.nbr_v_of_e(edge)
237239
# Find common interests
238240
if len(participants) >= 2:
239-
common_interests = set(hg.v[list(participants)[0]]["interests"])
241+
common_interests = set(hg.v(list(participants)[0])["interests"])
240242
for person in participants:
241-
common_interests &= set(hg.v[person]["interests"])
242-
243+
common_interests &= set(hg.v(person)["interests"])
244+
243245
for interest in common_interests:
244246
interest_groups[interest].update(participants)
245-
247+
246248
print("\nInterest-based communities:")
247249
for interest, community in interest_groups.items():
248250
if len(community) >= 3: # Only show communities with 3+ people
249-
names = [hg.v[person]["name"] for person in community]
251+
names = [hg.v(person)["name"] for person in community]
250252
print(f" {interest}: {', '.join(names)}")
251253

254+
252255
analyze_social_network(hg)
253256

257+
254258
# Find bridges (people who connect different groups)
255259
def find_bridges(hg):
256260
"""Find people who act as bridges between groups."""
257261
bridges = []
258-
262+
259263
for person in hg.all_v:
260264
# Get all groups this person participates in
261265
person_groups = hg.nbr_e_of_v(person)
262-
266+
263267
if len(person_groups) >= 2: # Person is in multiple groups
264268
# Check if removing this person would disconnect the groups
265269
other_connections = 0
266270
for group1 in person_groups:
267271
for group2 in person_groups:
268272
if group1 != group2:
269273
# Check if groups share other members
270-
group1_members = hg.N_v_of_e(group1) - {person}
271-
group2_members = hg.N_v_of_e(group2) - {person}
274+
group1_members = set(hg.nbr_v_of_e(group1)) - {person}
275+
group2_members = set(hg.nbr_v_of_e(group2)) - {person}
272276
if group1_members & group2_members:
273277
other_connections += 1
274278
break
275-
279+
276280
if other_connections < len(person_groups) - 1:
277281
bridges.append(person)
278-
282+
279283
return bridges
280284

285+
281286
bridges = find_bridges(hg)
282287
print(f"\nBridge people (connect different groups):")
283288
for bridge in bridges:
284-
name = hg.v[bridge]["name"]
289+
name = hg.v(bridge)["name"]
285290
num_groups = hg.degree_v(bridge)
286291
print(f" {name} (connects {num_groups} groups)")
287292

@@ -305,19 +310,16 @@ entities = {
305310
"einstein": {"type": "person", "name": "Albert Einstein", "birth": 1879, "death": 1955},
306311
"curie": {"type": "person", "name": "Marie Curie", "birth": 1867, "death": 1934},
307312
"newton": {"type": "person", "name": "Isaac Newton", "birth": 1642, "death": 1727},
308-
309313
# Concepts
310314
"relativity": {"type": "theory", "name": "Theory of Relativity", "year": 1915},
311315
"radioactivity": {"type": "phenomenon", "name": "Radioactivity", "discovered": 1896},
312316
"gravity": {"type": "force", "name": "Gravitational Force", "discovered": 1687},
313-
314317
# Institutions
315318
"princeton": {"type": "university", "name": "Princeton University", "founded": 1746},
316319
"sorbonne": {"type": "university", "name": "University of Paris", "founded": 1150},
317-
318320
# Awards
319321
"nobel_physics": {"type": "award", "name": "Nobel Prize in Physics"},
320-
"nobel_chemistry": {"type": "award", "name": "Nobel Prize in Chemistry"}
322+
"nobel_chemistry": {"type": "award", "name": "Nobel Prize in Chemistry"},
321323
}
322324

323325
for entity_id, info in entities.items():
@@ -329,78 +331,76 @@ relationships = [
329331
(("einstein", "relativity"), {"relation": "developed", "year": 1915}),
330332
(("curie", "radioactivity"), {"relation": "studied", "significance": "pioneering"}),
331333
(("newton", "gravity"), {"relation": "discovered", "year": 1687}),
332-
333-
# Person-Institution relationships
334+
# Person-Institution relationships
334335
(("einstein", "princeton"), {"relation": "worked_at", "period": "1933-1955"}),
335336
(("curie", "sorbonne"), {"relation": "studied_at", "degree": "PhD"}),
336-
337337
# Award relationships
338338
(("einstein", "nobel_physics"), {"relation": "won", "year": 1921, "for": "photoelectric effect"}),
339339
(("curie", "nobel_physics"), {"relation": "won", "year": 1903, "shared_with": "Pierre Curie"}),
340340
(("curie", "nobel_chemistry"), {"relation": "won", "year": 1911, "first_woman": True}),
341-
342341
# Complex multi-way relationships
343-
(("einstein", "curie", "nobel_physics"), {
344-
"relation": "both_won",
345-
"significance": "two great physicists"
346-
}),
347-
(("relativity", "gravity", "newton", "einstein"), {
348-
"relation": "theory_evolution",
349-
"description": "Newton's gravity evolved into Einstein's relativity"
350-
})
342+
(("einstein", "curie", "nobel_physics"), {"relation": "both_won", "significance": "two great physicists"}),
343+
(
344+
("relativity", "gravity", "newton", "einstein"),
345+
{"relation": "theory_evolution", "description": "Newton's gravity evolved into Einstein's relativity"},
346+
),
351347
]
352348

353349
for entities_in_rel, rel_info in relationships:
354350
kg.add_e(entities_in_rel, rel_info)
355351

352+
356353
# Knowledge graph queries
357354
def find_related_entities(entity_id, relation_type=None):
358355
"""Find all entities related to the given entity."""
359356
related = set()
360-
357+
361358
# Get all relationships involving this entity
362-
for edge in kg.N_e(entity_id):
363-
edge_info = kg.e[edge]
364-
359+
for edge in kg.nbr_e_of_v(entity_id):
360+
edge_info = kg.e(edge)
361+
365362
# Filter by relation type if specified
366363
if relation_type and edge_info.get("relation") != relation_type:
367364
continue
368-
365+
369366
# Add all other entities in this relationship
370-
other_entities = kg.N_v_of_e(edge) - {entity_id}
367+
other_entities = kg.nbr_v_of_e(edge) - {entity_id}
371368
related.update(other_entities)
372-
369+
373370
return related
374371

372+
375373
# Find entities related to Einstein
376374
einstein_related = find_related_entities("einstein")
377375
print("Entities related to Einstein:")
378376
for entity in einstein_related:
379-
entity_info = kg.v[entity]
377+
entity_info = kg.v(entity)
380378
print(f" {entity_info['name']} ({entity_info['type']})")
381379

382380
# Find award winners
383381
award_winners = find_related_entities("nobel_physics", "won")
384382
print(f"\nNobel Physics winners in our graph:")
385383
for winner in award_winners:
386-
winner_info = kg.v[winner]
384+
winner_info = kg.v(winner)
387385
print(f" {winner_info['name']}")
388386

389387
# Find theory developers
390388
print(f"\nTheory developers:")
391389
for theory in ["relativity", "radioactivity"]:
392390
developers = find_related_entities(theory, "developed") | find_related_entities(theory, "studied")
393-
theory_name = kg.v[theory]["name"]
394-
developer_names = [kg.v[dev]["name"] for dev in developers]
391+
theory_name = kg.v(theory)["name"]
392+
developer_names = [kg.v(dev)["name"] for dev in developers]
395393
print(f" {theory_name}: {', '.join(developer_names)}")
396394

397395
# Visualize the knowledge graph
398396
kg.draw()
397+
399398
```
400399

401400
## Tips for Effective Usage
402401

403402
### 1. Choose Meaningful IDs
403+
404404
```python
405405
# Good: descriptive IDs
406406
hg.add_v("user_123", {"name": "Alice"})
@@ -412,6 +412,7 @@ hg.add_v(2, {"name": "Gaming Laptop"})
412412
```
413413

414414
### 2. Use Rich Attributes
415+
415416
```python
416417
# Rich attributes provide more analysis possibilities
417418
hg.add_v("paper_001", {
@@ -426,17 +427,19 @@ hg.add_v("paper_001", {
426427
```
427428

428429
### 3. Leverage Hypergraph Structure
430+
429431
```python
430432
# Instead of multiple binary edges:
431433
hg.add_e((1, 2), {"type": "collaboration"})
432-
hg.add_e((1, 3), {"type": "collaboration"})
434+
hg.add_e((1, 3), {"type": "collaboration"})
433435
hg.add_e((2, 3), {"type": "collaboration"})
434436

435437
# Use a single hyperedge for group relationships:
436438
hg.add_e((1, 2, 3), {"type": "collaboration", "project": "AI Research"})
437439
```
438440

439441
### 4. Plan for Analysis
442+
440443
```python
441444
# Add metadata that supports your analysis goals
442445
hg.add_e((author1, author2, author3), {

0 commit comments

Comments
 (0)