0
# Data Import/Export and Utilities
1
2
Data conversion utilities, HIF format support, statistical reporting functions, and example datasets for experimentation and learning.
3
4
## Capabilities
5
6
### HIF Format Support
7
8
HIF (Hypergraph Interchange Format) provides standardized JSON-based serialization for hypergraphs, enabling interoperability and data exchange.
9
10
```python { .api }
11
def to_hif(
12
hg: "Hypergraph",
13
filename: Optional[str] = None,
14
network_type: str = "undirected",
15
metadata: Optional[Dict] = None
16
) -> Dict:
17
"""
18
Convert hypergraph to HIF JSON format.
19
20
Parameters:
21
- hg: Input hypergraph
22
- filename: Output file path (optional)
23
- network_type: Network type ("undirected", "directed", "asc")
24
- metadata: Additional metadata to include
25
26
Returns:
27
HIF dictionary (also saves to file if filename provided)
28
"""
29
30
def from_hif(
31
hif: Optional[Dict] = None,
32
filename: Optional[str] = None
33
) -> "Hypergraph":
34
"""
35
Create hypergraph from HIF JSON format.
36
37
Parameters:
38
- hif: HIF dictionary (if reading from memory)
39
- filename: HIF file path (if reading from file)
40
41
Returns:
42
Hypergraph object created from HIF data
43
"""
44
```
45
46
Usage example:
47
48
```python
49
import hypernetx as hnx
50
51
# Create hypergraph
52
H = hnx.Hypergraph({'E1': ['A', 'B', 'C'], 'E2': ['B', 'C', 'D']})
53
54
# Export to HIF format
55
hif_data = hnx.to_hif(H, filename='my_hypergraph.json')
56
57
# Import from HIF format
58
H_restored = hnx.from_hif(filename='my_hypergraph.json')
59
60
# Or work with HIF data directly
61
H_from_dict = hnx.from_hif(hif=hif_data)
62
```
63
64
### Statistical Reports
65
66
Comprehensive statistical analysis functions for hypergraph structure and properties.
67
68
```python { .api }
69
def info(H: "Hypergraph") -> str:
70
"""
71
General hypergraph information summary.
72
73
Parameters:
74
- H: Input hypergraph
75
76
Returns:
77
Formatted string with hypergraph statistics
78
"""
79
80
def info_dict(H: "Hypergraph") -> Dict[str, Any]:
81
"""
82
Hypergraph information as dictionary.
83
84
Parameters:
85
- H: Input hypergraph
86
87
Returns:
88
Dictionary with hypergraph statistics
89
"""
90
91
def degree_dist(H: "Hypergraph") -> Dict[int, int]:
92
"""
93
Node degree distribution.
94
95
Parameters:
96
- H: Input hypergraph
97
98
Returns:
99
Dictionary mapping degrees to counts
100
"""
101
102
def edge_size_dist(H: "Hypergraph") -> Dict[int, int]:
103
"""
104
Edge size distribution.
105
106
Parameters:
107
- H: Input hypergraph
108
109
Returns:
110
Dictionary mapping edge sizes to counts
111
"""
112
113
def comp_dist(H: "Hypergraph") -> Dict[int, int]:
114
"""Connected component size distribution."""
115
116
def s_comp_dist(
117
H: "Hypergraph",
118
s: int = 1
119
) -> Dict[int, int]:
120
"""S-connected component size distribution."""
121
122
def toplex_dist(H: "Hypergraph") -> Dict[int, int]:
123
"""Toplex (maximal edge) size distribution."""
124
125
def s_node_diameter_dist(
126
H: "Hypergraph",
127
s: int = 1
128
) -> Dict[int, int]:
129
"""S-node diameter distribution across components."""
130
131
def s_edge_diameter_dist(
132
H: "Hypergraph",
133
s: int = 1
134
) -> Dict[int, int]:
135
"""S-edge diameter distribution across components."""
136
137
def centrality_stats(
138
H: "Hypergraph",
139
measures: List[str] = None
140
) -> Dict[str, Dict]:
141
"""
142
Compute various centrality statistics.
143
144
Parameters:
145
- H: Input hypergraph
146
- measures: List of centrality measures to compute
147
148
Returns:
149
Dictionary with centrality statistics
150
"""
151
152
def dist_stats(distribution: Dict[int, int]) -> Dict[str, float]:
153
"""
154
Compute statistics for a distribution.
155
156
Parameters:
157
- distribution: Dictionary mapping values to counts
158
159
Returns:
160
Dictionary with mean, std, min, max, etc.
161
"""
162
```
163
164
### Utility Classes and Functions
165
166
Helper classes and utility functions for data manipulation and processing.
167
168
```python { .api }
169
class HNXCount:
170
"""Counter class optimized for HyperNetX operations."""
171
172
def __init__(self, data=None):
173
"""Initialize counter with optional data."""
174
175
def update(self, other):
176
"""Update counter with additional data."""
177
178
def most_common(self, n=None):
179
"""Return most common elements."""
180
181
class DefaultOrderedDict:
182
"""Ordered dictionary with default factory."""
183
184
def __init__(self, default_factory=None):
185
"""Initialize with default factory function."""
186
187
def remove_row_duplicates(df: DataFrame) -> DataFrame:
188
"""
189
Remove duplicate rows from DataFrame.
190
191
Parameters:
192
- df: Input DataFrame
193
194
Returns:
195
DataFrame with duplicates removed
196
"""
197
198
def reverse_dictionary(d: Dict) -> Dict:
199
"""
200
Reverse a dictionary (values become keys, keys become values).
201
202
Parameters:
203
- d: Input dictionary
204
205
Returns:
206
Reversed dictionary
207
"""
208
209
def not_implemented_for(*args):
210
"""
211
Decorator to mark functions as not implemented for certain graph types.
212
213
Usage:
214
@not_implemented_for('directed')
215
def my_function(H):
216
# Function implementation
217
"""
218
```
219
220
### Example Datasets
221
222
Pre-built dataset classes providing standard hypergraph examples for learning and experimentation.
223
224
```python { .api }
225
class LesMis:
226
"""Les Misérables character co-appearance hypergraph."""
227
228
def __init__(self):
229
"""Initialize Les Misérables dataset."""
230
231
def hypergraph(self) -> "Hypergraph":
232
"""Get hypergraph representation."""
233
234
def dataframe(self) -> DataFrame:
235
"""Get raw data as DataFrame."""
236
237
def lesmis_hypergraph_from_df(df: DataFrame) -> "Hypergraph":
238
"""
239
Create Les Misérables hypergraph from DataFrame.
240
241
Parameters:
242
- df: Les Misérables data DataFrame
243
244
Returns:
245
Hypergraph of character co-appearances
246
"""
247
248
def book_tour(H: "Hypergraph") -> Any:
249
"""
250
Create book tour visualization for Les Misérables hypergraph.
251
252
Parameters:
253
- H: Les Misérables hypergraph
254
255
Returns:
256
Interactive visualization
257
"""
258
259
class HarryPotter:
260
"""Harry Potter character interaction hypergraph."""
261
262
def __init__(self):
263
"""Initialize Harry Potter dataset."""
264
265
def hypergraph(self) -> "Hypergraph":
266
"""Get hypergraph representation."""
267
268
class GeneData:
269
"""Gene interaction and pathway hypergraph."""
270
271
def __init__(self):
272
"""Initialize gene data dataset."""
273
274
def hypergraph(self) -> "Hypergraph":
275
"""Get hypergraph representation."""
276
277
class TransmissionProblem:
278
"""Disease transmission network hypergraph."""
279
280
def __init__(self):
281
"""Initialize transmission problem dataset."""
282
283
def hypergraph(self) -> "Hypergraph":
284
"""Get hypergraph representation."""
285
```
286
287
Usage example with datasets:
288
289
```python
290
import hypernetx as hnx
291
292
# Use Les Misérables dataset
293
lesmis = hnx.LesMis()
294
H_lesmis = lesmis.hypergraph()
295
296
# Basic analysis
297
print(hnx.info(H_lesmis))
298
print(f"Degree distribution: {hnx.degree_dist(H_lesmis)}")
299
print(f"Edge size distribution: {hnx.edge_size_dist(H_lesmis)}")
300
301
# Use Harry Potter dataset
302
hp = hnx.HarryPotter()
303
H_hp = hp.hypergraph()
304
305
# Compare datasets
306
print(f"Les Mis: {H_lesmis.shape}")
307
print(f"Harry Potter: {H_hp.shape}")
308
309
# Gene data for biological networks
310
genes = hnx.GeneData()
311
H_genes = genes.hypergraph()
312
313
# Transmission problem for epidemiology
314
trans = hnx.TransmissionProblem()
315
H_trans = trans.hypergraph()
316
```
317
318
### Exception Handling
319
320
HyperNetX provides specific exception types for error handling.
321
322
```python { .api }
323
class HyperNetXException(Exception):
324
"""Base exception class for HyperNetX."""
325
326
class HyperNetXError(Exception):
327
"""General error class for HyperNetX operations."""
328
329
class HyperNetXNotImplementedError(NotImplementedError):
330
"""Exception for unimplemented functionality."""
331
```
332
333
Usage in error handling:
334
335
```python
336
import hypernetx as hnx
337
338
try:
339
# Some hypergraph operation
340
H = hnx.Hypergraph(invalid_data)
341
except hnx.HyperNetXError as e:
342
print(f"HyperNetX error: {e}")
343
except hnx.HyperNetXException as e:
344
print(f"General HyperNetX exception: {e}")
345
```