Skip to content

network_analysis

Top-level package for kiara_plugin.network_analysis.

Attributes

KIARA_METADATA = {'authors': [{'name': __author__, 'email': __email__}], 'description': 'Kiara modules for: network_analysis', 'references': {'source_repo': {'desc': 'The module package git repository.', 'url': 'https://github.com/DHARPA-Project/kiara_plugin.network_analysis'}, 'documentation': {'desc': 'The url for the module package documentation.', 'url': 'https://DHARPA-Project.github.io/kiara_plugin.network_analysis/'}}, 'tags': ['network_analysis'], 'labels': {'package': 'kiara_plugin.network_analysis'}} module-attribute

Kiara metadata for the kiara_plugin.network_analysis module.

find_modules: KiaraEntryPointItem = (find_kiara_modules_under, 'kiara_plugin.network_analysis.modules') module-attribute

Entry point to discover all kiara modules for this plugin.

find_model_classes: KiaraEntryPointItem = (find_kiara_model_classes_under, 'kiara_plugin.network_analysis.models') module-attribute

Entry point to discover all kiara model classes for this plugin.

find_data_types: KiaraEntryPointItem = (find_data_types_under, 'kiara_plugin.network_analysis.data_types') module-attribute

Entry point to discover all kiara data types for this plugin.

find_pipelines: KiaraEntryPointItem = (find_pipeline_base_path_for_module, 'kiara_plugin.network_analysis.pipelines', KIARA_METADATA) module-attribute

Entry point to discover all kiara pipelines for this plugin.

Classes

NetworkDataType

Bases: TablesType

Data that can be assembled into a graph.

This data type extends the 'tables' type from the kiara_plugin.tabular plugin, restricting the allowed tables to one called 'edges', and one called 'nodes'.

Source code in src/kiara_plugin/network_analysis/data_types.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
class NetworkDataType(TablesType):
    """Data that can be assembled into a graph.

    This data type extends the 'tables' type from the [kiara_plugin.tabular](https://github.com/DHARPA-Project/kiara_plugin.tabular) plugin, restricting the allowed tables to one called 'edges',
    and one called 'nodes'.
    """

    _data_type_name: ClassVar[str] = "network_data"
    _cached_doc: ClassVar[Union[str, None]] = None

    @classmethod
    def python_class(cls) -> Type:
        return NetworkData  # type: ignore

    @classmethod
    def type_doc(cls) -> str:
        if cls._cached_doc:
            return cls._cached_doc

        from kiara_plugin.network_analysis.models.metadata import (
            EDGE_COUNT_DUP_DIRECTED_COLUMN_METADATA,
            EDGE_COUNT_DUP_UNDIRECTED_COLUMN_METADATA,
            EDGE_ID_COLUMN_METADATA,
            EDGE_IDX_DUP_DIRECTED_COLUMN_METADATA,
            EDGE_IDX_DUP_UNDIRECTED_COLUMN_METADATA,
            EDGE_SOURCE_COLUMN_METADATA,
            EDGE_TARGET_COLUMN_METADATA,
            NODE_COUND_EDGES_MULTI_COLUMN_METADATA,
            NODE_COUNT_EDGES_COLUMN_METADATA,
            NODE_COUNT_IN_EDGES_COLUMN_METADATA,
            NODE_COUNT_IN_EDGES_MULTI_COLUMN_METADATA,
            NODE_COUNT_OUT_EDGES_COLUMN_METADATA,
            NODE_COUNT_OUT_EDGES_MULTI_COLUMN_METADATA,
            NODE_ID_COLUMN_METADATA,
            NODE_LABEL_COLUMN_METADATA,
        )

        edge_properties = {}
        edge_properties[EDGE_ID_COLUMN_NAME] = EDGE_ID_COLUMN_METADATA.doc.full_doc
        edge_properties[SOURCE_COLUMN_NAME] = EDGE_SOURCE_COLUMN_METADATA.doc.full_doc
        edge_properties[TARGET_COLUMN_NAME] = EDGE_TARGET_COLUMN_METADATA.doc.full_doc
        edge_properties[COUNT_DIRECTED_COLUMN_NAME] = (
            EDGE_COUNT_DUP_DIRECTED_COLUMN_METADATA.doc.full_doc
        )
        edge_properties[COUNT_IDX_DIRECTED_COLUMN_NAME] = (
            EDGE_IDX_DUP_DIRECTED_COLUMN_METADATA.doc.full_doc
        )
        edge_properties[COUNT_UNDIRECTED_COLUMN_NAME] = (
            EDGE_COUNT_DUP_UNDIRECTED_COLUMN_METADATA.doc.full_doc
        )
        edge_properties[COUNT_IDX_UNDIRECTED_COLUMN_NAME] = (
            EDGE_IDX_DUP_UNDIRECTED_COLUMN_METADATA.doc.full_doc
        )

        properties_node = {}
        properties_node[NODE_ID_COLUMN_NAME] = NODE_ID_COLUMN_METADATA.doc.full_doc
        properties_node[LABEL_COLUMN_NAME] = NODE_LABEL_COLUMN_METADATA.doc.full_doc
        properties_node[CONNECTIONS_COLUMN_NAME] = (
            NODE_COUNT_EDGES_COLUMN_METADATA.doc.full_doc
        )
        properties_node[CONNECTIONS_MULTI_COLUMN_NAME] = (
            NODE_COUND_EDGES_MULTI_COLUMN_METADATA.doc.full_doc
        )
        properties_node[IN_DIRECTED_COLUMN_NAME] = (
            NODE_COUNT_IN_EDGES_COLUMN_METADATA.doc.full_doc
        )
        properties_node[IN_DIRECTED_MULTI_COLUMN_NAME] = (
            NODE_COUNT_IN_EDGES_MULTI_COLUMN_METADATA.doc.full_doc
        )
        properties_node[OUT_DIRECTED_COLUMN_NAME] = (
            NODE_COUNT_OUT_EDGES_COLUMN_METADATA.doc.full_doc
        )
        properties_node[OUT_DIRECTED_MULTI_COLUMN_NAME] = (
            NODE_COUNT_OUT_EDGES_MULTI_COLUMN_METADATA.doc.full_doc
        )

        edge_properties_str = "\n\n".join(
            f"***{key}***:\n\n{value}" for key, value in edge_properties.items()
        )
        node_properties_str = "\n\n".join(
            f"***{key}***:\n\n{value}" for key, value in properties_node.items()
        )

        doc = cls.__doc__
        doc_tables = f"""

## Edges
The 'edges' table contains the following columns:

{edge_properties_str}

## Nodes

The 'nodes' table contains the following columns:

{node_properties_str}

"""

        cls._cached_doc = f"{doc}\n\n{doc_tables}"
        return cls._cached_doc

    def parse_python_obj(self, data: Any) -> NetworkData:
        if isinstance(data, KiaraTables):
            if EDGES_TABLE_NAME not in data.tables.keys():
                raise KiaraException(
                    f"Can't import network data: no '{EDGES_TABLE_NAME}' table found"
                )

            if NODES_TABLE_NAME not in data.tables.keys():
                raise KiaraException(
                    f"Can't import network data: no '{NODES_TABLE_NAME}' table found"
                )

            # return NetworkData(
            #     tables={
            #         EDGES_TABLE_NAME: data.tables[EDGES_TABLE_NAME],
            #         NODES_TABLE_NAME: data.tables[NODES_TABLE_NAME],
            #     },
            #
            # )
            return NetworkData.create_network_data(
                edges_table=data.tables[EDGES_TABLE_NAME].arrow_table,
                nodes_table=data.tables[NODES_TABLE_NAME].arrow_table,
                augment_tables=False,
            )

        if not isinstance(data, NetworkData):
            raise KiaraException(
                f"Can't parse object to network data: invalid type '{type(data)}'."
            )

        return data

    def _validate(cls, value: Any) -> None:
        if not isinstance(value, NetworkData):
            raise ValueError(
                f"Invalid type '{type(value)}': must be of 'NetworkData' (or a sub-class)."
            )

        network_data: NetworkData = value

        table_names = network_data.table_names
        if EDGES_TABLE_NAME not in table_names:
            raise Exception(
                f"Invalid 'network_data' value: database does not contain table '{EDGES_TABLE_NAME}'."
            )
        if NODES_TABLE_NAME not in table_names:
            raise Exception(
                f"Invalid 'network_data' value: database does not contain table '{NODES_TABLE_NAME}'."
            )

        edges_columns = network_data.edges.column_names
        if SOURCE_COLUMN_NAME not in edges_columns:
            raise Exception(
                f"Invalid 'network_data' value: 'edges' table does not contain a '{SOURCE_COLUMN_NAME}' column. Available columns: {', '.join(edges_columns)}."
            )
        if TARGET_COLUMN_NAME not in edges_columns:
            raise Exception(
                f"Invalid 'network_data' value: 'edges' table does not contain a '{TARGET_COLUMN_NAME}' column. Available columns: {', '.join(edges_columns)}."
            )

        nodes_columns = network_data.nodes.column_names
        if NODE_ID_COLUMN_NAME not in nodes_columns:
            raise Exception(
                f"Invalid 'network_data' value: 'nodes' table does not contain a '{NODE_ID_COLUMN_NAME}' column. Available columns: {', '.join(nodes_columns)}."
            )
        if LABEL_COLUMN_NAME not in nodes_columns:
            raise Exception(
                f"Invalid 'network_data' value: 'nodes' table does not contain a '{LABEL_COLUMN_NAME}' column. Available columns: {', '.join(nodes_columns)}."
            )

    def pretty_print_as__terminal_renderable(
        self, value: Value, render_config: Mapping[str, Any]
    ) -> Any:
        max_rows = render_config.get(
            "max_no_rows", DEFAULT_PRETTY_PRINT_CONFIG["max_no_rows"]
        )
        max_row_height = render_config.get(
            "max_row_height", DEFAULT_PRETTY_PRINT_CONFIG["max_row_height"]
        )
        max_cell_length = render_config.get(
            "max_cell_length", DEFAULT_PRETTY_PRINT_CONFIG["max_cell_length"]
        )

        half_lines: Union[int, None] = None
        if max_rows:
            half_lines = int(max_rows / 2)

        network_data: NetworkData = value.data

        result: List[Any] = [""]

        nodes_atw = ArrowTabularWrap(network_data.nodes.arrow_table)
        nodes_pretty = nodes_atw.as_terminal_renderable(
            rows_head=half_lines,
            rows_tail=half_lines,
            max_row_height=max_row_height,
            max_cell_length=max_cell_length,
        )
        result.append(f"[b]{NODES_TABLE_NAME}[/b]")
        result.append(nodes_pretty)

        edges_atw = ArrowTabularWrap(network_data.edges.arrow_table)
        edges_pretty = edges_atw.as_terminal_renderable(
            rows_head=half_lines,
            rows_tail=half_lines,
            max_row_height=max_row_height,
            max_cell_length=max_cell_length,
        )
        result.append(f"[b]{EDGES_TABLE_NAME}[/b]")
        result.append(edges_pretty)

        return Group(*result)

Functions

python_class() -> Type classmethod
Source code in src/kiara_plugin/network_analysis/data_types.py
47
48
49
@classmethod
def python_class(cls) -> Type:
    return NetworkData  # type: ignore
type_doc() -> str classmethod
Source code in src/kiara_plugin/network_analysis/data_types.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    @classmethod
    def type_doc(cls) -> str:
        if cls._cached_doc:
            return cls._cached_doc

        from kiara_plugin.network_analysis.models.metadata import (
            EDGE_COUNT_DUP_DIRECTED_COLUMN_METADATA,
            EDGE_COUNT_DUP_UNDIRECTED_COLUMN_METADATA,
            EDGE_ID_COLUMN_METADATA,
            EDGE_IDX_DUP_DIRECTED_COLUMN_METADATA,
            EDGE_IDX_DUP_UNDIRECTED_COLUMN_METADATA,
            EDGE_SOURCE_COLUMN_METADATA,
            EDGE_TARGET_COLUMN_METADATA,
            NODE_COUND_EDGES_MULTI_COLUMN_METADATA,
            NODE_COUNT_EDGES_COLUMN_METADATA,
            NODE_COUNT_IN_EDGES_COLUMN_METADATA,
            NODE_COUNT_IN_EDGES_MULTI_COLUMN_METADATA,
            NODE_COUNT_OUT_EDGES_COLUMN_METADATA,
            NODE_COUNT_OUT_EDGES_MULTI_COLUMN_METADATA,
            NODE_ID_COLUMN_METADATA,
            NODE_LABEL_COLUMN_METADATA,
        )

        edge_properties = {}
        edge_properties[EDGE_ID_COLUMN_NAME] = EDGE_ID_COLUMN_METADATA.doc.full_doc
        edge_properties[SOURCE_COLUMN_NAME] = EDGE_SOURCE_COLUMN_METADATA.doc.full_doc
        edge_properties[TARGET_COLUMN_NAME] = EDGE_TARGET_COLUMN_METADATA.doc.full_doc
        edge_properties[COUNT_DIRECTED_COLUMN_NAME] = (
            EDGE_COUNT_DUP_DIRECTED_COLUMN_METADATA.doc.full_doc
        )
        edge_properties[COUNT_IDX_DIRECTED_COLUMN_NAME] = (
            EDGE_IDX_DUP_DIRECTED_COLUMN_METADATA.doc.full_doc
        )
        edge_properties[COUNT_UNDIRECTED_COLUMN_NAME] = (
            EDGE_COUNT_DUP_UNDIRECTED_COLUMN_METADATA.doc.full_doc
        )
        edge_properties[COUNT_IDX_UNDIRECTED_COLUMN_NAME] = (
            EDGE_IDX_DUP_UNDIRECTED_COLUMN_METADATA.doc.full_doc
        )

        properties_node = {}
        properties_node[NODE_ID_COLUMN_NAME] = NODE_ID_COLUMN_METADATA.doc.full_doc
        properties_node[LABEL_COLUMN_NAME] = NODE_LABEL_COLUMN_METADATA.doc.full_doc
        properties_node[CONNECTIONS_COLUMN_NAME] = (
            NODE_COUNT_EDGES_COLUMN_METADATA.doc.full_doc
        )
        properties_node[CONNECTIONS_MULTI_COLUMN_NAME] = (
            NODE_COUND_EDGES_MULTI_COLUMN_METADATA.doc.full_doc
        )
        properties_node[IN_DIRECTED_COLUMN_NAME] = (
            NODE_COUNT_IN_EDGES_COLUMN_METADATA.doc.full_doc
        )
        properties_node[IN_DIRECTED_MULTI_COLUMN_NAME] = (
            NODE_COUNT_IN_EDGES_MULTI_COLUMN_METADATA.doc.full_doc
        )
        properties_node[OUT_DIRECTED_COLUMN_NAME] = (
            NODE_COUNT_OUT_EDGES_COLUMN_METADATA.doc.full_doc
        )
        properties_node[OUT_DIRECTED_MULTI_COLUMN_NAME] = (
            NODE_COUNT_OUT_EDGES_MULTI_COLUMN_METADATA.doc.full_doc
        )

        edge_properties_str = "\n\n".join(
            f"***{key}***:\n\n{value}" for key, value in edge_properties.items()
        )
        node_properties_str = "\n\n".join(
            f"***{key}***:\n\n{value}" for key, value in properties_node.items()
        )

        doc = cls.__doc__
        doc_tables = f"""

## Edges
The 'edges' table contains the following columns:

{edge_properties_str}

## Nodes

The 'nodes' table contains the following columns:

{node_properties_str}

"""

        cls._cached_doc = f"{doc}\n\n{doc_tables}"
        return cls._cached_doc
parse_python_obj(data: Any) -> NetworkData
Source code in src/kiara_plugin/network_analysis/data_types.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def parse_python_obj(self, data: Any) -> NetworkData:
    if isinstance(data, KiaraTables):
        if EDGES_TABLE_NAME not in data.tables.keys():
            raise KiaraException(
                f"Can't import network data: no '{EDGES_TABLE_NAME}' table found"
            )

        if NODES_TABLE_NAME not in data.tables.keys():
            raise KiaraException(
                f"Can't import network data: no '{NODES_TABLE_NAME}' table found"
            )

        # return NetworkData(
        #     tables={
        #         EDGES_TABLE_NAME: data.tables[EDGES_TABLE_NAME],
        #         NODES_TABLE_NAME: data.tables[NODES_TABLE_NAME],
        #     },
        #
        # )
        return NetworkData.create_network_data(
            edges_table=data.tables[EDGES_TABLE_NAME].arrow_table,
            nodes_table=data.tables[NODES_TABLE_NAME].arrow_table,
            augment_tables=False,
        )

    if not isinstance(data, NetworkData):
        raise KiaraException(
            f"Can't parse object to network data: invalid type '{type(data)}'."
        )

    return data
pretty_print_as__terminal_renderable(value: Value, render_config: Mapping[str, Any]) -> Any
Source code in src/kiara_plugin/network_analysis/data_types.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
def pretty_print_as__terminal_renderable(
    self, value: Value, render_config: Mapping[str, Any]
) -> Any:
    max_rows = render_config.get(
        "max_no_rows", DEFAULT_PRETTY_PRINT_CONFIG["max_no_rows"]
    )
    max_row_height = render_config.get(
        "max_row_height", DEFAULT_PRETTY_PRINT_CONFIG["max_row_height"]
    )
    max_cell_length = render_config.get(
        "max_cell_length", DEFAULT_PRETTY_PRINT_CONFIG["max_cell_length"]
    )

    half_lines: Union[int, None] = None
    if max_rows:
        half_lines = int(max_rows / 2)

    network_data: NetworkData = value.data

    result: List[Any] = [""]

    nodes_atw = ArrowTabularWrap(network_data.nodes.arrow_table)
    nodes_pretty = nodes_atw.as_terminal_renderable(
        rows_head=half_lines,
        rows_tail=half_lines,
        max_row_height=max_row_height,
        max_cell_length=max_cell_length,
    )
    result.append(f"[b]{NODES_TABLE_NAME}[/b]")
    result.append(nodes_pretty)

    edges_atw = ArrowTabularWrap(network_data.edges.arrow_table)
    edges_pretty = edges_atw.as_terminal_renderable(
        rows_head=half_lines,
        rows_tail=half_lines,
        max_row_height=max_row_height,
        max_cell_length=max_cell_length,
    )
    result.append(f"[b]{EDGES_TABLE_NAME}[/b]")
    result.append(edges_pretty)

    return Group(*result)

NetworkData

Bases: KiaraTables

A flexible, graph-type agnostic wrapper class for network datasets.

This class provides a unified interface for working with network data that can represent any type of graph structure: directed, undirected, simple, or multi-graphs. The design philosophy emphasizes flexibility and performance while maintaining a clean, intuitive API.

Design Philosophy: - Graph Type Agnostic: Supports all graph types (directed/undirected, simple/multi) within the same data structure without requiring type-specific conversions - Efficient Storage: Uses Apache Arrow tables for high-performance columnar storage - Flexible Querying: Provides SQL-based querying capabilities alongside programmatic access - Seamless Export: Easy conversion to NetworkX and RustWorkX graph objects, other representations possible in the future - Metadata Rich: Automatically computes and stores graph statistics and properties

Internal Structure: The network data is stored as two Arrow tables: - nodes table: Contains node information with required columns '_node_id' (int) and '_label' (str) - edges table: Contains edge information with required columns '_source' (int) and '_target' (int)

Additional computed columns (prefixed with '_') provide graph statistics for different interpretations: - Degree counts for directed/undirected graphs - Multi-edge counts and indices - Centrality measures

Graph Type Support: - Simple Graphs: Single edges between node pairs - Multi-graphs: Multiple edges between the same node pairs - Directed Graphs: One-way edges with source → target semantics - Undirected Graphs: Bidirectional edges - Mixed Types: The same data can be interpreted as different graph types

Note: Column names prefixed with '_' have internal meaning and are automatically computed. Original attributes from source data are stored without the prefix.

Source code in src/kiara_plugin/network_analysis/models/__init__.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
class NetworkData(KiaraTables):
    """A flexible, graph-type agnostic wrapper class for network datasets.

    This class provides a unified interface for working with network data that can represent
    any type of graph structure: directed, undirected, simple, or multi-graphs. The design
    philosophy emphasizes flexibility and performance while maintaining a clean, intuitive API.

    **Design Philosophy:**
    - **Graph Type Agnostic**: Supports all graph types (directed/undirected, simple/multi)
      within the same data structure without requiring type-specific conversions
    - **Efficient Storage**: Uses Apache Arrow tables for high-performance columnar storage
    - **Flexible Querying**: Provides SQL-based querying capabilities alongside programmatic access
    - **Seamless Export**: Easy conversion to NetworkX and RustWorkX graph objects, other representations possible in the future
    - **Metadata Rich**: Automatically computes and stores graph statistics and properties

    **Internal Structure:**
    The network data is stored as two Arrow tables:
    - **nodes table**: Contains node information with required columns '_node_id' (int) and '_label' (str)
    - **edges table**: Contains edge information with required columns '_source' (int) and '_target' (int)

    Additional computed columns (prefixed with '_') provide graph statistics for different interpretations:
    - Degree counts for directed/undirected graphs
    - Multi-edge counts and indices
    - Centrality measures

    **Graph Type Support:**
    - **Simple Graphs**: Single edges between node pairs
    - **Multi-graphs**: Multiple edges between the same node pairs
    - **Directed Graphs**: One-way edges with source → target semantics
    - **Undirected Graphs**: Bidirectional edges
    - **Mixed Types**: The same data can be interpreted as different graph types

    **Note:** Column names prefixed with '_' have internal meaning and are automatically
    computed. Original attributes from source data are stored without the prefix.
    """

    _kiara_model_id: ClassVar = "instance.network_data"

    @classmethod
    def create_augmented(
        cls,
        network_data: "NetworkData",
        additional_edges_columns: Union[None, Dict[str, "pa.Array"]] = None,
        additional_nodes_columns: Union[None, Dict[str, "pa.Array"]] = None,
        nodes_column_metadata: Union[Dict[str, Dict[str, KiaraModel]], None] = None,
        edges_column_metadata: Union[Dict[str, Dict[str, KiaraModel]], None] = None,
    ) -> "NetworkData":
        """Create a new NetworkData instance with additional columns.

        This method creates a new NetworkData instance by adding extra columns to an existing
        instance without recomputing the automatically generated internal columns (those
        prefixed with '_'). This is useful for adding derived attributes or analysis results.

        Args:
            network_data: The source NetworkData instance to augment
            additional_edges_columns: Dictionary mapping column names to PyArrow Arrays
                for new edge attributes
            additional_nodes_columns: Dictionary mapping column names to PyArrow Arrays
                for new node attributes
            nodes_column_metadata: Additional metadata to attach to nodes table columns
            edges_column_metadata: Additional metadata to attach to edges table columns

        Returns:
            NetworkData: A new NetworkData instance with the additional columns

        Example:
            ```python
            import pyarrow as pa

            # Add a weight column to edges
            weights = pa.array([1.0, 2.5, 0.8] * (network_data.num_edges // 3))
            augmented = NetworkData.create_augmented(
                network_data,
                additional_edges_columns={"weight": weights}
            )
            ```
        """

        nodes_table = network_data.nodes.arrow_table
        edges_table = network_data.edges.arrow_table

        # nodes_table = pa.Table.from_arrays(orig_nodes_table.columns, schema=orig_nodes_table.schema)
        # edges_table = pa.Table.from_arrays(orig_edges_table.columns, schema=orig_edges_table.schema)

        if additional_edges_columns is not None:
            for col_name, col_data in additional_edges_columns.items():
                edges_table = edges_table.append_column(col_name, col_data)

        if additional_nodes_columns is not None:
            for col_name, col_data in additional_nodes_columns.items():
                nodes_table = nodes_table.append_column(col_name, col_data)

        new_network_data = NetworkData.create_network_data(
            nodes_table=nodes_table,
            edges_table=edges_table,
            augment_tables=False,
            nodes_column_metadata=nodes_column_metadata,
            edges_column_metadata=edges_column_metadata,
        )

        return new_network_data

    @classmethod
    def create_network_data(
        cls,
        nodes_table: "pa.Table",
        edges_table: "pa.Table",
        augment_tables: bool = True,
        nodes_column_metadata: Union[Dict[str, Dict[str, KiaraModel]], None] = None,
        edges_column_metadata: Union[Dict[str, Dict[str, KiaraModel]], None] = None,
    ) -> "NetworkData":
        """Create a NetworkData instance from PyArrow tables.

        This is the primary factory method for creating NetworkData instances from raw tabular data.
        It supports all graph types and automatically computes necessary metadata for efficient
        graph operations.

        **Required Table Structure:**

        Nodes table must contain:
        - '_node_id' (int): Unique integer identifier for each node
        - '_label' (str): Human-readable label for the node

        Edges table must contain:
        - '_source' (int): Source node ID (must exist in nodes table)
        - '_target' (int): Target node ID (must exist in nodes table)

        **Automatic Augmentation:**
        When `augment_tables=True` (default), the method automatically adds computed columns:

        For edges:
        - '_edge_id': Unique edge identifier
        - '_count_dup_directed': Count of parallel edges (directed interpretation)
        - '_idx_dup_directed': Index within parallel edge group (directed)
        - '_count_dup_undirected': Count of parallel edges (undirected interpretation)
        - '_idx_dup_undirected': Index within parallel edge group (undirected)

        For nodes:
        - '_count_edges': Total edge count (simple graph interpretation)
        - '_count_edges_multi': Total edge count (multi-graph interpretation)
        - '_in_edges': Incoming edge count (directed, simple)
        - '_out_edges': Outgoing edge count (directed, simple)
        - '_in_edges_multi': Incoming edge count (directed, multi)
        - '_out_edges_multi': Outgoing edge count (directed, multi)
        - '_degree_centrality': Normalized degree centrality
        - '_degree_centrality_multi': Normalized degree centrality (multi-graph)

        Args:
            nodes_table: PyArrow table containing node data
            edges_table: PyArrow table containing edge data
            augment_tables: Whether to compute and add internal metadata columns.
                Set to False only if you know the metadata is already present and correct.
            nodes_column_metadata: Additional metadata to attach to nodes table columns.
                Format: {column_name: {property_name: property_value}}
            edges_column_metadata: Additional metadata to attach to edges table columns.
                Format: {column_name: {property_name: property_value}}

        Returns:
            NetworkData: A new NetworkData instance

        Raises:
            KiaraException: If required columns are missing or contain null values

        """

        from kiara_plugin.network_analysis.models.metadata import (
            EDGE_COUNT_DUP_DIRECTED_COLUMN_METADATA,
            EDGE_COUNT_DUP_UNDIRECTED_COLUMN_METADATA,
            EDGE_ID_COLUMN_METADATA,
            EDGE_IDX_DUP_DIRECTED_COLUMN_METADATA,
            EDGE_IDX_DUP_UNDIRECTED_COLUMN_METADATA,
            EDGE_SOURCE_COLUMN_METADATA,
            EDGE_TARGET_COLUMN_METADATA,
            NODE_COUND_EDGES_MULTI_COLUMN_METADATA,
            NODE_COUNT_EDGES_COLUMN_METADATA,
            NODE_COUNT_IN_EDGES_COLUMN_METADATA,
            NODE_COUNT_IN_EDGES_MULTI_COLUMN_METADATA,
            NODE_COUNT_OUT_EDGES_COLUMN_METADATA,
            NODE_COUNT_OUT_EDGES_MULTI_COLUMN_METADATA,
            NODE_DEGREE_COLUMN_METADATA,
            NODE_DEGREE_MULTI_COLUMN_METADATA,
            NODE_ID_COLUMN_METADATA,
            NODE_LABEL_COLUMN_METADATA,
        )

        if augment_tables:
            edges_table = augment_edges_table_with_id_and_weights(edges_table)
            nodes_table = augment_nodes_table_with_connection_counts(
                nodes_table, edges_table
            )
            nodes_table, edges_table = augment_tables_with_component_ids(
                nodes_table=nodes_table, edges_table=edges_table
            )

        if edges_table.column(SOURCE_COLUMN_NAME).null_count > 0:
            raise KiaraException(
                msg="Can't assemble network data.",
                details="Source column in edges table contains null values.",
            )
        if edges_table.column(TARGET_COLUMN_NAME).null_count > 0:
            raise KiaraException(
                msg="Can't assemble network data.",
                details="Target column in edges table contains null values.",
            )

        network_data: NetworkData = cls.create_tables(
            {NODES_TABLE_NAME: nodes_table, EDGES_TABLE_NAME: edges_table}
        )

        # set default column metadata
        network_data.edges.set_column_metadata(
            EDGE_ID_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            EDGE_ID_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.edges.set_column_metadata(
            SOURCE_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            EDGE_SOURCE_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.edges.set_column_metadata(
            TARGET_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            EDGE_TARGET_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.edges.set_column_metadata(
            COUNT_DIRECTED_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            EDGE_COUNT_DUP_DIRECTED_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.edges.set_column_metadata(
            COUNT_IDX_DIRECTED_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            EDGE_IDX_DUP_DIRECTED_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.edges.set_column_metadata(
            COUNT_UNDIRECTED_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            EDGE_COUNT_DUP_UNDIRECTED_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.edges.set_column_metadata(
            COUNT_IDX_UNDIRECTED_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            EDGE_IDX_DUP_UNDIRECTED_COLUMN_METADATA,
            overwrite_existing=False,
        )

        network_data.nodes.set_column_metadata(
            NODE_ID_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            NODE_ID_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.nodes.set_column_metadata(
            LABEL_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            NODE_LABEL_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.nodes.set_column_metadata(
            CONNECTIONS_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            NODE_COUNT_EDGES_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.nodes.set_column_metadata(
            UNWEIGHTED_DEGREE_CENTRALITY_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            NODE_DEGREE_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.nodes.set_column_metadata(
            CONNECTIONS_MULTI_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            NODE_COUND_EDGES_MULTI_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.nodes.set_column_metadata(
            UNWEIGHTED_DEGREE_CENTRALITY_MULTI_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            NODE_DEGREE_MULTI_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.nodes.set_column_metadata(
            IN_DIRECTED_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            NODE_COUNT_IN_EDGES_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.nodes.set_column_metadata(
            IN_DIRECTED_MULTI_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            NODE_COUNT_IN_EDGES_MULTI_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.nodes.set_column_metadata(
            OUT_DIRECTED_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            NODE_COUNT_OUT_EDGES_COLUMN_METADATA,
            overwrite_existing=False,
        )
        network_data.nodes.set_column_metadata(
            OUT_DIRECTED_MULTI_COLUMN_NAME,
            ATTRIBUTE_PROPERTY_KEY,
            NODE_COUNT_OUT_EDGES_MULTI_COLUMN_METADATA,
            overwrite_existing=False,
        )

        if nodes_column_metadata is not None:
            for col_name, col_meta in nodes_column_metadata.items():
                for prop_name, prop_value in col_meta.items():
                    network_data.nodes.set_column_metadata(
                        col_name, prop_name, prop_value, overwrite_existing=True
                    )
        if edges_column_metadata is not None:
            for col_name, col_meta in edges_column_metadata.items():
                for prop_name, prop_value in col_meta.items():
                    network_data.edges.set_column_metadata(
                        col_name, prop_name, prop_value, overwrite_existing=True
                    )

        return network_data

    @classmethod
    def from_filtered_nodes(
        cls, network_data: "NetworkData", nodes_list: List[int]
    ) -> "NetworkData":
        """Create a new, filtered instance of this class using a source network, and a list of node ids to include.

        Nodes/edges containing a node id not in the list will be removed from the resulting network data.

        Arguments:
            network_data: the source network data
            nodes_list: the list of node ids to include in the filtered network data
        """

        import duckdb
        import polars as pl

        node_columns = [NODE_ID_COLUMN_NAME, LABEL_COLUMN_NAME]
        for column_name, metadata in network_data.nodes.column_metadata.items():
            attr_prop: Union[None, NetworkNodeAttributeMetadata] = metadata.get(  # type: ignore
                ATTRIBUTE_PROPERTY_KEY, None
            )
            if attr_prop is None or not attr_prop.computed_attribute:
                node_columns.append(column_name)

        node_list_str = ", ".join([str(n) for n in nodes_list])

        nodes_table = network_data.nodes.arrow_table  # noqa
        nodes_query = f"SELECT {', '.join(node_columns)} FROM nodes_table n WHERE n.{NODE_ID_COLUMN_NAME} IN ({node_list_str})"

        nodes_result = duckdb.sql(nodes_query).pl()

        edges_table = network_data.edges.arrow_table  # noqa
        edge_columns = [SOURCE_COLUMN_NAME, TARGET_COLUMN_NAME]
        for column_name, metadata in network_data.edges.column_metadata.items():
            attr_prop = metadata.get(ATTRIBUTE_PROPERTY_KEY, None)  # type: ignore
            if attr_prop is None or not attr_prop.computed_attribute:
                edge_columns.append(column_name)

        edges_query = f"SELECT {', '.join(edge_columns)} FROM edges_table WHERE {SOURCE_COLUMN_NAME} IN ({node_list_str}) OR {TARGET_COLUMN_NAME} IN ({node_list_str})"

        edges_result = duckdb.sql(edges_query).pl()

        nodes_idx_colum = range(len(nodes_result))
        old_idx_column = nodes_result[NODE_ID_COLUMN_NAME]

        repl_map = dict(zip(old_idx_column.to_list(), nodes_idx_colum))
        nodes_result = nodes_result.with_columns(
            pl.col(NODE_ID_COLUMN_NAME).replace_strict(repl_map, default=None)
        )

        edges_result = edges_result.with_columns(
            pl.col(SOURCE_COLUMN_NAME).replace_strict(repl_map, default=None),
            pl.col(TARGET_COLUMN_NAME).replace_strict(repl_map, default=None),
        )

        filtered = NetworkData.create_network_data(
            nodes_table=nodes_result, edges_table=edges_result
        )
        return filtered

    @classmethod
    def create_from_networkx_graph(
        cls,
        graph: "nx.Graph",
        label_attr_name: Union[str, None] = None,
        ignore_node_attributes: Union[Iterable[str], None] = None,
    ) -> "NetworkData":
        """Create a NetworkData instance from any NetworkX graph type.

        This method provides seamless conversion from NetworkX graphs to NetworkData,
        preserving all node and edge attributes while automatically handling different
        graph types (Graph, DiGraph, MultiGraph, MultiDiGraph).

        **Graph Type Support:**
        - **nx.Graph**: Converted to undirected simple graph representation
        - **nx.DiGraph**: Converted to directed simple graph representation
        - **nx.MultiGraph**: Converted with multi-edge support (undirected)
        - **nx.MultiDiGraph**: Converted with multi-edge support (directed)

        **Attribute Handling:**
        All NetworkX node and edge attributes are preserved as columns in the resulting
        tables, except those starting with '_' (reserved for internal use).

        Args:
            graph: Any NetworkX graph instance (Graph, DiGraph, MultiGraph, MultiDiGraph)
            label_attr_name: Name of the node attribute to use as the node label.
                If None, the node ID is converted to string and used as label.
                Can also be an iterable of attribute names to try in order.
            ignore_node_attributes: List of node attribute names to exclude from
                the resulting nodes table

        Returns:
            NetworkData: A new NetworkData instance representing the graph

        Raises:
            KiaraException: If node/edge attributes contain names starting with '_'

        Note:
            Node IDs in the original NetworkX graph are mapped to sequential integers
            starting from 0 in the NetworkData representation. The original node IDs
            are preserved as the '_label' if no label_attr_name is specified.
        """

        # TODO: should we also index nodes/edges attributes?

        nodes_table, node_id_map = extract_networkx_nodes_as_table(
            graph=graph,
            label_attr_name=label_attr_name,
            ignore_attributes=ignore_node_attributes,
        )

        edges_table = extract_networkx_edges_as_table(graph, node_id_map)

        network_data = NetworkData.create_network_data(
            nodes_table=nodes_table, edges_table=edges_table
        )

        return network_data

    @property
    def edges(self) -> "KiaraTable":
        """Access the edges table containing all edge data and computed statistics.

        The edges table contains both original edge attributes and computed columns:
        - '_edge_id': Unique edge identifier
        - '_source', '_target': Node IDs for edge endpoints
        - '_count_dup_*': Parallel edge counts for different graph interpretations
        - '_idx_dup_*': Indices within parallel edge groups
        - Original edge attributes (without '_' prefix)

        Returns:
            KiaraTable: The edges table with full schema and data access methods
        """
        return self.tables[EDGES_TABLE_NAME]

    @property
    def nodes(self) -> "KiaraTable":
        """Access the nodes table containing all node data and computed statistics.

        The nodes table contains both original node attributes and computed columns:
        - '_node_id': Unique node identifier (sequential integers from 0)
        - '_label': Human-readable node label
        - '_count_edges*': Edge counts for different graph interpretations
        - '_in_edges*', '_out_edges*': Directional edge counts
        - '_degree_centrality*': Normalized degree centrality measures
        - Original node attributes (without '_' prefix)

        Returns:
            KiaraTable: The nodes table with full schema and data access methods
        """
        return self.tables[NODES_TABLE_NAME]

    @property
    def num_nodes(self) -> int:
        """Get the total number of nodes in the network.

        Returns:
            int: Number of nodes in the network
        """
        return self.nodes.num_rows  # type: ignore

    @property
    def num_edges(self) -> int:
        """Get the total number of edges in the network.

        Note: This returns the total number of edge records, which includes
        all parallel edges in multi-graph interpretations.

        Returns:
            int: Total number of edges (including parallel edges)
        """
        return self.edges.num_rows  # type: ignore

    def query_edges(
        self, sql_query: str, relation_name: str = EDGES_TABLE_NAME
    ) -> "pa.Table":
        """Execute SQL queries on the edges table for flexible data analysis.

        This method provides direct SQL access to the edges table, enabling complex
        queries and aggregations. All computed edge columns are available for querying.

        **Available Columns:**
        - '_edge_id': Unique edge identifier
        - '_source', '_target': Node IDs for edge endpoints
        - '_count_dup_directed': Number of parallel edges (directed interpretation)
        - '_idx_dup_directed': Index within parallel edge group (directed)
        - '_count_dup_undirected': Number of parallel edges (undirected interpretation)
        - '_idx_dup_undirected': Index within parallel edge group (undirected)
        - Original edge attributes (names without '_' prefix)

        Args:
            sql_query: SQL query string. Use 'edges' as the table name in your query.
            relation_name: Alternative table name to use in the query (default: 'edges').
                If specified, all occurrences of this name in the query will be replaced
                with 'edges'.

        Returns:
            pa.Table: Query results as a PyArrow table

        Example:
            ```python
            # Find edges with high multiplicity
            parallel_edges = network_data.query_edges(
                "SELECT _source, _target, _count_dup_directed FROM edges WHERE _count_dup_directed > 1"
            )

            # Get edge statistics
            stats = network_data.query_edges(
                "SELECT COUNT(*) as total_edges, AVG(_count_dup_directed) as avg_multiplicity FROM edges"
            )
            ```
        """
        import duckdb

        con = duckdb.connect()
        edges = self.edges.arrow_table  # noqa: F841
        if relation_name != EDGES_TABLE_NAME:
            sql_query = sql_query.replace(relation_name, EDGES_TABLE_NAME)

        result = con.execute(sql_query)
        return result.arrow()

    def query_nodes(
        self, sql_query: str, relation_name: str = NODES_TABLE_NAME
    ) -> "pa.Table":
        """Execute SQL queries on the nodes table for flexible data analysis.

        This method provides direct SQL access to the nodes table, enabling complex
        queries and aggregations. All computed node statistics are available for querying.

        **Available Columns:**
        - '_node_id': Unique node identifier
        - '_label': Human-readable node label
        - '_count_edges': Total edge count (simple graph interpretation)
        - '_count_edges_multi': Total edge count (multi-graph interpretation)
        - '_in_edges': Incoming edge count (directed, simple)
        - '_out_edges': Outgoing edge count (directed, simple)
        - '_in_edges_multi': Incoming edge count (directed, multi)
        - '_out_edges_multi': Outgoing edge count (directed, multi)
        - '_degree_centrality': Normalized degree centrality (simple)
        - '_degree_centrality_multi': Normalized degree centrality (multi)
        - Original node attributes (names without '_' prefix)

        Args:
            sql_query: SQL query string. Use 'nodes' as the table name in your query.
            relation_name: Alternative table name to use in the query (default: 'nodes').
                If specified, all occurrences of this name in the query will be replaced
                with 'nodes'.

        Returns:
            pa.Table: Query results as a PyArrow table

        Example:
            ```python
            # Find high-degree nodes
            hubs = network_data.query_nodes(
                "SELECT _node_id, _label, _count_edges FROM nodes WHERE _count_edges > 10 ORDER BY _count_edges DESC"
            )

            # Get centrality statistics
            centrality_stats = network_data.query_nodes(
                "SELECT AVG(_degree_centrality) as avg_centrality, MAX(_degree_centrality) as max_centrality FROM nodes"
            )
            ```
        """
        import duckdb

        con = duckdb.connect()
        nodes = self.nodes.arrow_table  # noqa
        if relation_name != NODES_TABLE_NAME:
            sql_query = sql_query.replace(relation_name, NODES_TABLE_NAME)

        result = con.execute(sql_query)
        return result.arrow()

    def _calculate_node_attributes(
        self, incl_node_attributes: Union[bool, str, Iterable[str]]
    ) -> List[str]:
        """Calculate the node attributes that should be included in the output."""

        if incl_node_attributes is False:
            node_attr_names: List[str] = [NODE_ID_COLUMN_NAME, LABEL_COLUMN_NAME]
        else:
            all_node_attr_names: List[str] = self.nodes.column_names  # type: ignore
            if incl_node_attributes is True:
                node_attr_names = [NODE_ID_COLUMN_NAME]
                node_attr_names.extend(
                    (x for x in all_node_attr_names if x != NODE_ID_COLUMN_NAME)
                )  # type: ignore
            elif isinstance(incl_node_attributes, str):
                if incl_node_attributes not in all_node_attr_names:
                    raise KiaraException(
                        f"Can't include node attribute {incl_node_attributes}: not part of the available attributes ({', '.join(all_node_attr_names)})."
                    )
                node_attr_names = [NODE_ID_COLUMN_NAME, incl_node_attributes]
            else:
                node_attr_names = [NODE_ID_COLUMN_NAME]
                for attr_name in incl_node_attributes:
                    if attr_name not in all_node_attr_names:
                        raise KiaraException(
                            f"Can't include node attribute {incl_node_attributes}: not part of the available attributes ({', '.join(all_node_attr_names)})."
                        )
                    node_attr_names.append(attr_name)  # type: ignore

        return node_attr_names

    def _calculate_edge_attributes(
        self, incl_edge_attributes: Union[bool, str, Iterable[str]]
    ) -> List[str]:
        """Calculate the edge attributes that should be included in the output."""

        if incl_edge_attributes is False:
            edge_attr_names: List[str] = [SOURCE_COLUMN_NAME, TARGET_COLUMN_NAME]
        else:
            all_edge_attr_names: List[str] = self.edges.column_names  # type: ignore
            if incl_edge_attributes is True:
                edge_attr_names = [SOURCE_COLUMN_NAME, TARGET_COLUMN_NAME]
                edge_attr_names.extend(
                    (
                        x
                        for x in all_edge_attr_names
                        if x not in (SOURCE_COLUMN_NAME, TARGET_COLUMN_NAME)
                    )
                )  # type: ignore
            elif isinstance(incl_edge_attributes, str):
                if incl_edge_attributes not in all_edge_attr_names:
                    raise KiaraException(
                        f"Can't include edge attribute {incl_edge_attributes}: not part of the available attributes ({', '.join(all_edge_attr_names)})."
                    )
                edge_attr_names = [
                    SOURCE_COLUMN_NAME,
                    TARGET_COLUMN_NAME,
                    incl_edge_attributes,
                ]
            else:
                edge_attr_names = [SOURCE_COLUMN_NAME, TARGET_COLUMN_NAME]
                for attr_name in incl_edge_attributes:
                    if attr_name not in all_edge_attr_names:
                        raise KiaraException(
                            f"Can't include edge attribute {incl_edge_attributes}: not part of the available attributes ({', '.join(all_edge_attr_names)})."
                        )
                    edge_attr_names.append(attr_name)  # type: ignore

        return edge_attr_names

    def retrieve_graph_data(
        self,
        nodes_callback: Union[NodesCallback, None] = None,
        edges_callback: Union[EdgesCallback, None] = None,
        incl_node_attributes: Union[bool, str, Iterable[str]] = False,
        incl_edge_attributes: Union[bool, str, Iterable[str]] = False,
        omit_self_loops: bool = False,
    ):
        """Retrieve graph data from the sqlite database, and call the specified callbacks for each node and edge.

        First the nodes will be processed, then the edges, if that does not suit your needs you can just use this method twice, and set the callback you don't need to None.

        The nodes_callback will be called with the following arguments:
            - node_id: the id of the node (int)
            - if False: nothing else
            - if True: all node attributes, in the order they are defined in the table schema
            - if str: the value of the specified node attribute
            - if Iterable[str]: the values of the specified node attributes, in the order they are specified

        The edges_callback will be called with the following aruments:
            - source_id: the id of the source node (int)
            - target_id: the id of the target node (int)
            - if False: nothing else
            - if True: all edge attributes, in the order they are defined in the table schema
            - if str: the value of the specified edge attribute
            - if Iterable[str]: the values of the specified edge attributes, in the order they are specified

        """

        if nodes_callback is not None:
            node_attr_names = self._calculate_node_attributes(incl_node_attributes)

            nodes_df = self.nodes.to_polars_dataframe()
            for row in nodes_df.select(*node_attr_names).rows(named=True):
                nodes_callback(**row)  # type: ignore

        if edges_callback is not None:
            edge_attr_names = self._calculate_edge_attributes(incl_edge_attributes)

            edges_df = self.edges.to_polars_dataframe()
            for row in edges_df.select(*edge_attr_names).rows(named=True):
                if (
                    omit_self_loops
                    and row[SOURCE_COLUMN_NAME] == row[TARGET_COLUMN_NAME]
                ):
                    continue
                edges_callback(**row)  # type: ignore

    def as_networkx_graph(
        self,
        graph_type: Type[NETWORKX_GRAPH_TYPE],
        incl_node_attributes: Union[bool, str, Iterable[str]] = False,
        incl_edge_attributes: Union[bool, str, Iterable[str]] = False,
        omit_self_loops: bool = False,
    ) -> NETWORKX_GRAPH_TYPE:
        """Export the network data as a NetworkX graph object.

        This method converts the NetworkData to any NetworkX graph type, providing
        flexibility to work with the data using NetworkX's extensive algorithm library.
        The conversion preserves node and edge attributes as specified.

        **Supported Graph Types:**
        - **nx.Graph**: Undirected simple graph (parallel edges are merged)
        - **nx.DiGraph**: Directed simple graph (parallel edges are merged)
        - **nx.MultiGraph**: Undirected multigraph (parallel edges preserved)
        - **nx.MultiDiGraph**: Directed multigraph (parallel edges preserved)

        **Attribute Handling:**
        Node and edge attributes can be selectively included in the exported graph.
        Internal columns (prefixed with '_') are available but typically excluded
        from exports to maintain clean NetworkX compatibility.

        Args:
            graph_type: NetworkX graph class to instantiate (nx.Graph, nx.DiGraph, etc.)
            incl_node_attributes: Controls which node attributes to include:
                - False: No attributes (only node IDs)
                - True: All attributes (including computed columns)
                - str: Single attribute name to include
                - Iterable[str]: List of specific attributes to include
            incl_edge_attributes: Controls which edge attributes to include:
                - False: No attributes
                - True: All attributes (including computed columns)
                - str: Single attribute name to include
                - Iterable[str]: List of specific attributes to include
            omit_self_loops: If True, edges where source equals target are excluded

        Returns:
            NETWORKX_GRAPH_TYPE: NetworkX graph instance of the specified type

        Note:
            When exporting to simple graph types (Graph, DiGraph), parallel edges
            are automatically merged. Use MultiGraph or MultiDiGraph to preserve
            all edge instances.
        """

        graph: NETWORKX_GRAPH_TYPE = graph_type()

        def add_node(_node_id: int, **attrs):
            graph.add_node(_node_id, **attrs)

        def add_edge(_source: int, _target: int, **attrs):
            graph.add_edge(_source, _target, **attrs)

        self.retrieve_graph_data(
            nodes_callback=add_node,
            edges_callback=add_edge,
            incl_node_attributes=incl_node_attributes,
            incl_edge_attributes=incl_edge_attributes,
            omit_self_loops=omit_self_loops,
        )

        return graph

    def as_rustworkx_graph(
        self,
        graph_type: Type[RUSTWORKX_GRAPH_TYPE],
        multigraph: bool = False,
        incl_node_attributes: Union[bool, str, Iterable[str]] = False,
        incl_edge_attributes: Union[bool, str, Iterable[str]] = False,
        omit_self_loops: bool = False,
        attach_node_id_map: bool = False,
    ) -> RUSTWORKX_GRAPH_TYPE:
        """Export the network data as a RustWorkX graph object.

        RustWorkX provides high-performance graph algorithms implemented in Rust with
        Python bindings. This method converts NetworkData to RustWorkX format while
        handling the differences in node ID management between the two systems.

        **Supported Graph Types:**
        - **rx.PyGraph**: Undirected graph (with optional multigraph support)
        - **rx.PyDiGraph**: Directed graph (with optional multigraph support)

        **Node ID Mapping:**
        RustWorkX uses sequential integer node IDs starting from 0, which may differ
        from the original NetworkData node IDs. The original '_node_id' values are
        preserved as node attributes, and an optional mapping can be attached to
        the graph for reference.

        **Performance Benefits:**
        RustWorkX graphs offer significant performance advantages for:
        - Large-scale graph algorithms
        - Parallel processing
        - Memory-efficient operations
        - High-performance centrality calculations

        Args:
            graph_type: RustWorkX graph class (rx.PyGraph or rx.PyDiGraph)
            multigraph: If True, parallel edges are preserved; if False, they are merged
            incl_node_attributes: Controls which node attributes to include:
                - False: No attributes (only node data structure)
                - True: All attributes (including computed columns)
                - str: Single attribute name to include
                - Iterable[str]: List of specific attributes to include
            incl_edge_attributes: Controls which edge attributes to include:
                - False: No attributes
                - True: All attributes (including computed columns)
                - str: Single attribute name to include
                - Iterable[str]: List of specific attributes to include
            omit_self_loops: If True, self-loops (edges where source == target) are excluded
            attach_node_id_map: If True, adds a 'node_id_map' attribute to the graph
                containing the mapping from RustWorkX node IDs to original NetworkData node IDs

        Returns:
            RUSTWORKX_GRAPH_TYPE: RustWorkX graph instance of the specified type

        Note:
            The original NetworkData '_node_id' values are always included in the
            node data dictionary, regardless of the incl_node_attributes setting.
        """

        from bidict import bidict

        graph = graph_type(multigraph=multigraph)

        # rustworkx uses 0-based integer indexes, so we don't neeed to look up the node ids (unless we want to
        # include node attributes)

        self._calculate_node_attributes(incl_node_attributes)[1:]
        self._calculate_edge_attributes(incl_edge_attributes)[2:]

        # we can use a 'global' dict here because we know the nodes are processed before the edges
        node_map: bidict = bidict()

        def add_node(_node_id: int, **attrs):
            data = {NODE_ID_COLUMN_NAME: _node_id}
            data.update(attrs)

            graph_node_id = graph.add_node(data)

            node_map[graph_node_id] = _node_id
            # if not _node_id == graph_node_id:
            #     raise Exception("Internal error: node ids don't match")

        def add_edge(_source: int, _target: int, **attrs):
            source = node_map[_source]
            target = node_map[_target]
            if not attrs:
                graph.add_edge(source, target, None)
            else:
                graph.add_edge(source, target, attrs)

        self.retrieve_graph_data(
            nodes_callback=add_node,
            edges_callback=add_edge,
            incl_node_attributes=incl_node_attributes,
            incl_edge_attributes=incl_edge_attributes,
            omit_self_loops=omit_self_loops,
        )

        if attach_node_id_map:
            graph.attrs = {"node_id_map": node_map}  # type: ignore

        return graph

    @property
    def component_ids(self) -> Set[int]:
        import duckdb

        nodes_table = self.nodes.arrow_table  # noqa
        query = f"""
        SELECT DISTINCT {COMPONENT_ID_COLUMN_NAME} FROM nodes_table
        """

        result: Set[int] = set([x[0] for x in duckdb.sql(query).fetchall()])
        return result

Attributes

edges: KiaraTable property

Access the edges table containing all edge data and computed statistics.

The edges table contains both original edge attributes and computed columns: - 'edge_id': Unique edge identifier - '_source', '_target': Node IDs for edge endpoints - '_count_dup': Parallel edge counts for different graph interpretations - 'idx_dup': Indices within parallel edge groups - Original edge attributes (without '_' prefix)

Returns:

Name Type Description
KiaraTable KiaraTable

The edges table with full schema and data access methods

nodes: KiaraTable property

Access the nodes table containing all node data and computed statistics.

The nodes table contains both original node attributes and computed columns: - 'node_id': Unique node identifier (sequential integers from 0) - '_label': Human-readable node label - '_count_edges': Edge counts for different graph interpretations - '_in_edges', '_out_edges': Directional edge counts - '_degree_centrality': Normalized degree centrality measures - Original node attributes (without '' prefix)

Returns:

Name Type Description
KiaraTable KiaraTable

The nodes table with full schema and data access methods

num_nodes: int property

Get the total number of nodes in the network.

Returns:

Name Type Description
int int

Number of nodes in the network

num_edges: int property

Get the total number of edges in the network.

Note: This returns the total number of edge records, which includes all parallel edges in multi-graph interpretations.

Returns:

Name Type Description
int int

Total number of edges (including parallel edges)

component_ids: Set[int] property

Functions

create_augmented(network_data: NetworkData, additional_edges_columns: Union[None, Dict[str, pa.Array]] = None, additional_nodes_columns: Union[None, Dict[str, pa.Array]] = None, nodes_column_metadata: Union[Dict[str, Dict[str, KiaraModel]], None] = None, edges_column_metadata: Union[Dict[str, Dict[str, KiaraModel]], None] = None) -> NetworkData classmethod

Create a new NetworkData instance with additional columns.

This method creates a new NetworkData instance by adding extra columns to an existing instance without recomputing the automatically generated internal columns (those prefixed with '_'). This is useful for adding derived attributes or analysis results.

Parameters:

Name Type Description Default
network_data NetworkData

The source NetworkData instance to augment

required
additional_edges_columns Union[None, Dict[str, Array]]

Dictionary mapping column names to PyArrow Arrays for new edge attributes

None
additional_nodes_columns Union[None, Dict[str, Array]]

Dictionary mapping column names to PyArrow Arrays for new node attributes

None
nodes_column_metadata Union[Dict[str, Dict[str, KiaraModel]], None]

Additional metadata to attach to nodes table columns

None
edges_column_metadata Union[Dict[str, Dict[str, KiaraModel]], None]

Additional metadata to attach to edges table columns

None

Returns:

Name Type Description
NetworkData NetworkData

A new NetworkData instance with the additional columns

Example
import pyarrow as pa

# Add a weight column to edges
weights = pa.array([1.0, 2.5, 0.8] * (network_data.num_edges // 3))
augmented = NetworkData.create_augmented(
    network_data,
    additional_edges_columns={"weight": weights}
)
Source code in src/kiara_plugin/network_analysis/models/__init__.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
@classmethod
def create_augmented(
    cls,
    network_data: "NetworkData",
    additional_edges_columns: Union[None, Dict[str, "pa.Array"]] = None,
    additional_nodes_columns: Union[None, Dict[str, "pa.Array"]] = None,
    nodes_column_metadata: Union[Dict[str, Dict[str, KiaraModel]], None] = None,
    edges_column_metadata: Union[Dict[str, Dict[str, KiaraModel]], None] = None,
) -> "NetworkData":
    """Create a new NetworkData instance with additional columns.

    This method creates a new NetworkData instance by adding extra columns to an existing
    instance without recomputing the automatically generated internal columns (those
    prefixed with '_'). This is useful for adding derived attributes or analysis results.

    Args:
        network_data: The source NetworkData instance to augment
        additional_edges_columns: Dictionary mapping column names to PyArrow Arrays
            for new edge attributes
        additional_nodes_columns: Dictionary mapping column names to PyArrow Arrays
            for new node attributes
        nodes_column_metadata: Additional metadata to attach to nodes table columns
        edges_column_metadata: Additional metadata to attach to edges table columns

    Returns:
        NetworkData: A new NetworkData instance with the additional columns

    Example:
        ```python
        import pyarrow as pa

        # Add a weight column to edges
        weights = pa.array([1.0, 2.5, 0.8] * (network_data.num_edges // 3))
        augmented = NetworkData.create_augmented(
            network_data,
            additional_edges_columns={"weight": weights}
        )
        ```
    """

    nodes_table = network_data.nodes.arrow_table
    edges_table = network_data.edges.arrow_table

    # nodes_table = pa.Table.from_arrays(orig_nodes_table.columns, schema=orig_nodes_table.schema)
    # edges_table = pa.Table.from_arrays(orig_edges_table.columns, schema=orig_edges_table.schema)

    if additional_edges_columns is not None:
        for col_name, col_data in additional_edges_columns.items():
            edges_table = edges_table.append_column(col_name, col_data)

    if additional_nodes_columns is not None:
        for col_name, col_data in additional_nodes_columns.items():
            nodes_table = nodes_table.append_column(col_name, col_data)

    new_network_data = NetworkData.create_network_data(
        nodes_table=nodes_table,
        edges_table=edges_table,
        augment_tables=False,
        nodes_column_metadata=nodes_column_metadata,
        edges_column_metadata=edges_column_metadata,
    )

    return new_network_data
create_network_data(nodes_table: pa.Table, edges_table: pa.Table, augment_tables: bool = True, nodes_column_metadata: Union[Dict[str, Dict[str, KiaraModel]], None] = None, edges_column_metadata: Union[Dict[str, Dict[str, KiaraModel]], None] = None) -> NetworkData classmethod

Create a NetworkData instance from PyArrow tables.

This is the primary factory method for creating NetworkData instances from raw tabular data. It supports all graph types and automatically computes necessary metadata for efficient graph operations.

Required Table Structure:

Nodes table must contain: - '_node_id' (int): Unique integer identifier for each node - '_label' (str): Human-readable label for the node

Edges table must contain: - '_source' (int): Source node ID (must exist in nodes table) - '_target' (int): Target node ID (must exist in nodes table)

Automatic Augmentation: When augment_tables=True (default), the method automatically adds computed columns:

For edges: - '_edge_id': Unique edge identifier - '_count_dup_directed': Count of parallel edges (directed interpretation) - '_idx_dup_directed': Index within parallel edge group (directed) - '_count_dup_undirected': Count of parallel edges (undirected interpretation) - '_idx_dup_undirected': Index within parallel edge group (undirected)

For nodes: - '_count_edges': Total edge count (simple graph interpretation) - '_count_edges_multi': Total edge count (multi-graph interpretation) - '_in_edges': Incoming edge count (directed, simple) - '_out_edges': Outgoing edge count (directed, simple) - '_in_edges_multi': Incoming edge count (directed, multi) - '_out_edges_multi': Outgoing edge count (directed, multi) - '_degree_centrality': Normalized degree centrality - '_degree_centrality_multi': Normalized degree centrality (multi-graph)

Parameters:

Name Type Description Default
nodes_table Table

PyArrow table containing node data

required
edges_table Table

PyArrow table containing edge data

required
augment_tables bool

Whether to compute and add internal metadata columns. Set to False only if you know the metadata is already present and correct.

True
nodes_column_metadata Union[Dict[str, Dict[str, KiaraModel]], None]

Additional metadata to attach to nodes table columns. Format: {column_name: {property_name: property_value}}

None
edges_column_metadata Union[Dict[str, Dict[str, KiaraModel]], None]

Additional metadata to attach to edges table columns. Format: {column_name: {property_name: property_value}}

None

Returns:

Name Type Description
NetworkData NetworkData

A new NetworkData instance

Raises:

Type Description
KiaraException

If required columns are missing or contain null values

Source code in src/kiara_plugin/network_analysis/models/__init__.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
@classmethod
def create_network_data(
    cls,
    nodes_table: "pa.Table",
    edges_table: "pa.Table",
    augment_tables: bool = True,
    nodes_column_metadata: Union[Dict[str, Dict[str, KiaraModel]], None] = None,
    edges_column_metadata: Union[Dict[str, Dict[str, KiaraModel]], None] = None,
) -> "NetworkData":
    """Create a NetworkData instance from PyArrow tables.

    This is the primary factory method for creating NetworkData instances from raw tabular data.
    It supports all graph types and automatically computes necessary metadata for efficient
    graph operations.

    **Required Table Structure:**

    Nodes table must contain:
    - '_node_id' (int): Unique integer identifier for each node
    - '_label' (str): Human-readable label for the node

    Edges table must contain:
    - '_source' (int): Source node ID (must exist in nodes table)
    - '_target' (int): Target node ID (must exist in nodes table)

    **Automatic Augmentation:**
    When `augment_tables=True` (default), the method automatically adds computed columns:

    For edges:
    - '_edge_id': Unique edge identifier
    - '_count_dup_directed': Count of parallel edges (directed interpretation)
    - '_idx_dup_directed': Index within parallel edge group (directed)
    - '_count_dup_undirected': Count of parallel edges (undirected interpretation)
    - '_idx_dup_undirected': Index within parallel edge group (undirected)

    For nodes:
    - '_count_edges': Total edge count (simple graph interpretation)
    - '_count_edges_multi': Total edge count (multi-graph interpretation)
    - '_in_edges': Incoming edge count (directed, simple)
    - '_out_edges': Outgoing edge count (directed, simple)
    - '_in_edges_multi': Incoming edge count (directed, multi)
    - '_out_edges_multi': Outgoing edge count (directed, multi)
    - '_degree_centrality': Normalized degree centrality
    - '_degree_centrality_multi': Normalized degree centrality (multi-graph)

    Args:
        nodes_table: PyArrow table containing node data
        edges_table: PyArrow table containing edge data
        augment_tables: Whether to compute and add internal metadata columns.
            Set to False only if you know the metadata is already present and correct.
        nodes_column_metadata: Additional metadata to attach to nodes table columns.
            Format: {column_name: {property_name: property_value}}
        edges_column_metadata: Additional metadata to attach to edges table columns.
            Format: {column_name: {property_name: property_value}}

    Returns:
        NetworkData: A new NetworkData instance

    Raises:
        KiaraException: If required columns are missing or contain null values

    """

    from kiara_plugin.network_analysis.models.metadata import (
        EDGE_COUNT_DUP_DIRECTED_COLUMN_METADATA,
        EDGE_COUNT_DUP_UNDIRECTED_COLUMN_METADATA,
        EDGE_ID_COLUMN_METADATA,
        EDGE_IDX_DUP_DIRECTED_COLUMN_METADATA,
        EDGE_IDX_DUP_UNDIRECTED_COLUMN_METADATA,
        EDGE_SOURCE_COLUMN_METADATA,
        EDGE_TARGET_COLUMN_METADATA,
        NODE_COUND_EDGES_MULTI_COLUMN_METADATA,
        NODE_COUNT_EDGES_COLUMN_METADATA,
        NODE_COUNT_IN_EDGES_COLUMN_METADATA,
        NODE_COUNT_IN_EDGES_MULTI_COLUMN_METADATA,
        NODE_COUNT_OUT_EDGES_COLUMN_METADATA,
        NODE_COUNT_OUT_EDGES_MULTI_COLUMN_METADATA,
        NODE_DEGREE_COLUMN_METADATA,
        NODE_DEGREE_MULTI_COLUMN_METADATA,
        NODE_ID_COLUMN_METADATA,
        NODE_LABEL_COLUMN_METADATA,
    )

    if augment_tables:
        edges_table = augment_edges_table_with_id_and_weights(edges_table)
        nodes_table = augment_nodes_table_with_connection_counts(
            nodes_table, edges_table
        )
        nodes_table, edges_table = augment_tables_with_component_ids(
            nodes_table=nodes_table, edges_table=edges_table
        )

    if edges_table.column(SOURCE_COLUMN_NAME).null_count > 0:
        raise KiaraException(
            msg="Can't assemble network data.",
            details="Source column in edges table contains null values.",
        )
    if edges_table.column(TARGET_COLUMN_NAME).null_count > 0:
        raise KiaraException(
            msg="Can't assemble network data.",
            details="Target column in edges table contains null values.",
        )

    network_data: NetworkData = cls.create_tables(
        {NODES_TABLE_NAME: nodes_table, EDGES_TABLE_NAME: edges_table}
    )

    # set default column metadata
    network_data.edges.set_column_metadata(
        EDGE_ID_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        EDGE_ID_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.edges.set_column_metadata(
        SOURCE_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        EDGE_SOURCE_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.edges.set_column_metadata(
        TARGET_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        EDGE_TARGET_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.edges.set_column_metadata(
        COUNT_DIRECTED_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        EDGE_COUNT_DUP_DIRECTED_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.edges.set_column_metadata(
        COUNT_IDX_DIRECTED_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        EDGE_IDX_DUP_DIRECTED_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.edges.set_column_metadata(
        COUNT_UNDIRECTED_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        EDGE_COUNT_DUP_UNDIRECTED_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.edges.set_column_metadata(
        COUNT_IDX_UNDIRECTED_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        EDGE_IDX_DUP_UNDIRECTED_COLUMN_METADATA,
        overwrite_existing=False,
    )

    network_data.nodes.set_column_metadata(
        NODE_ID_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        NODE_ID_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.nodes.set_column_metadata(
        LABEL_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        NODE_LABEL_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.nodes.set_column_metadata(
        CONNECTIONS_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        NODE_COUNT_EDGES_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.nodes.set_column_metadata(
        UNWEIGHTED_DEGREE_CENTRALITY_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        NODE_DEGREE_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.nodes.set_column_metadata(
        CONNECTIONS_MULTI_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        NODE_COUND_EDGES_MULTI_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.nodes.set_column_metadata(
        UNWEIGHTED_DEGREE_CENTRALITY_MULTI_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        NODE_DEGREE_MULTI_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.nodes.set_column_metadata(
        IN_DIRECTED_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        NODE_COUNT_IN_EDGES_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.nodes.set_column_metadata(
        IN_DIRECTED_MULTI_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        NODE_COUNT_IN_EDGES_MULTI_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.nodes.set_column_metadata(
        OUT_DIRECTED_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        NODE_COUNT_OUT_EDGES_COLUMN_METADATA,
        overwrite_existing=False,
    )
    network_data.nodes.set_column_metadata(
        OUT_DIRECTED_MULTI_COLUMN_NAME,
        ATTRIBUTE_PROPERTY_KEY,
        NODE_COUNT_OUT_EDGES_MULTI_COLUMN_METADATA,
        overwrite_existing=False,
    )

    if nodes_column_metadata is not None:
        for col_name, col_meta in nodes_column_metadata.items():
            for prop_name, prop_value in col_meta.items():
                network_data.nodes.set_column_metadata(
                    col_name, prop_name, prop_value, overwrite_existing=True
                )
    if edges_column_metadata is not None:
        for col_name, col_meta in edges_column_metadata.items():
            for prop_name, prop_value in col_meta.items():
                network_data.edges.set_column_metadata(
                    col_name, prop_name, prop_value, overwrite_existing=True
                )

    return network_data
from_filtered_nodes(network_data: NetworkData, nodes_list: List[int]) -> NetworkData classmethod

Create a new, filtered instance of this class using a source network, and a list of node ids to include.

Nodes/edges containing a node id not in the list will be removed from the resulting network data.

Parameters:

Name Type Description Default
network_data NetworkData

the source network data

required
nodes_list List[int]

the list of node ids to include in the filtered network data

required
Source code in src/kiara_plugin/network_analysis/models/__init__.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
@classmethod
def from_filtered_nodes(
    cls, network_data: "NetworkData", nodes_list: List[int]
) -> "NetworkData":
    """Create a new, filtered instance of this class using a source network, and a list of node ids to include.

    Nodes/edges containing a node id not in the list will be removed from the resulting network data.

    Arguments:
        network_data: the source network data
        nodes_list: the list of node ids to include in the filtered network data
    """

    import duckdb
    import polars as pl

    node_columns = [NODE_ID_COLUMN_NAME, LABEL_COLUMN_NAME]
    for column_name, metadata in network_data.nodes.column_metadata.items():
        attr_prop: Union[None, NetworkNodeAttributeMetadata] = metadata.get(  # type: ignore
            ATTRIBUTE_PROPERTY_KEY, None
        )
        if attr_prop is None or not attr_prop.computed_attribute:
            node_columns.append(column_name)

    node_list_str = ", ".join([str(n) for n in nodes_list])

    nodes_table = network_data.nodes.arrow_table  # noqa
    nodes_query = f"SELECT {', '.join(node_columns)} FROM nodes_table n WHERE n.{NODE_ID_COLUMN_NAME} IN ({node_list_str})"

    nodes_result = duckdb.sql(nodes_query).pl()

    edges_table = network_data.edges.arrow_table  # noqa
    edge_columns = [SOURCE_COLUMN_NAME, TARGET_COLUMN_NAME]
    for column_name, metadata in network_data.edges.column_metadata.items():
        attr_prop = metadata.get(ATTRIBUTE_PROPERTY_KEY, None)  # type: ignore
        if attr_prop is None or not attr_prop.computed_attribute:
            edge_columns.append(column_name)

    edges_query = f"SELECT {', '.join(edge_columns)} FROM edges_table WHERE {SOURCE_COLUMN_NAME} IN ({node_list_str}) OR {TARGET_COLUMN_NAME} IN ({node_list_str})"

    edges_result = duckdb.sql(edges_query).pl()

    nodes_idx_colum = range(len(nodes_result))
    old_idx_column = nodes_result[NODE_ID_COLUMN_NAME]

    repl_map = dict(zip(old_idx_column.to_list(), nodes_idx_colum))
    nodes_result = nodes_result.with_columns(
        pl.col(NODE_ID_COLUMN_NAME).replace_strict(repl_map, default=None)
    )

    edges_result = edges_result.with_columns(
        pl.col(SOURCE_COLUMN_NAME).replace_strict(repl_map, default=None),
        pl.col(TARGET_COLUMN_NAME).replace_strict(repl_map, default=None),
    )

    filtered = NetworkData.create_network_data(
        nodes_table=nodes_result, edges_table=edges_result
    )
    return filtered
create_from_networkx_graph(graph: nx.Graph, label_attr_name: Union[str, None] = None, ignore_node_attributes: Union[Iterable[str], None] = None) -> NetworkData classmethod

Create a NetworkData instance from any NetworkX graph type.

This method provides seamless conversion from NetworkX graphs to NetworkData, preserving all node and edge attributes while automatically handling different graph types (Graph, DiGraph, MultiGraph, MultiDiGraph).

Graph Type Support: - nx.Graph: Converted to undirected simple graph representation - nx.DiGraph: Converted to directed simple graph representation - nx.MultiGraph: Converted with multi-edge support (undirected) - nx.MultiDiGraph: Converted with multi-edge support (directed)

Attribute Handling: All NetworkX node and edge attributes are preserved as columns in the resulting tables, except those starting with '_' (reserved for internal use).

Parameters:

Name Type Description Default
graph Graph

Any NetworkX graph instance (Graph, DiGraph, MultiGraph, MultiDiGraph)

required
label_attr_name Union[str, None]

Name of the node attribute to use as the node label. If None, the node ID is converted to string and used as label. Can also be an iterable of attribute names to try in order.

None
ignore_node_attributes Union[Iterable[str], None]

List of node attribute names to exclude from the resulting nodes table

None

Returns:

Name Type Description
NetworkData NetworkData

A new NetworkData instance representing the graph

Raises:

Type Description
KiaraException

If node/edge attributes contain names starting with '_'

Note

Node IDs in the original NetworkX graph are mapped to sequential integers starting from 0 in the NetworkData representation. The original node IDs are preserved as the '_label' if no label_attr_name is specified.

Source code in src/kiara_plugin/network_analysis/models/__init__.py
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
@classmethod
def create_from_networkx_graph(
    cls,
    graph: "nx.Graph",
    label_attr_name: Union[str, None] = None,
    ignore_node_attributes: Union[Iterable[str], None] = None,
) -> "NetworkData":
    """Create a NetworkData instance from any NetworkX graph type.

    This method provides seamless conversion from NetworkX graphs to NetworkData,
    preserving all node and edge attributes while automatically handling different
    graph types (Graph, DiGraph, MultiGraph, MultiDiGraph).

    **Graph Type Support:**
    - **nx.Graph**: Converted to undirected simple graph representation
    - **nx.DiGraph**: Converted to directed simple graph representation
    - **nx.MultiGraph**: Converted with multi-edge support (undirected)
    - **nx.MultiDiGraph**: Converted with multi-edge support (directed)

    **Attribute Handling:**
    All NetworkX node and edge attributes are preserved as columns in the resulting
    tables, except those starting with '_' (reserved for internal use).

    Args:
        graph: Any NetworkX graph instance (Graph, DiGraph, MultiGraph, MultiDiGraph)
        label_attr_name: Name of the node attribute to use as the node label.
            If None, the node ID is converted to string and used as label.
            Can also be an iterable of attribute names to try in order.
        ignore_node_attributes: List of node attribute names to exclude from
            the resulting nodes table

    Returns:
        NetworkData: A new NetworkData instance representing the graph

    Raises:
        KiaraException: If node/edge attributes contain names starting with '_'

    Note:
        Node IDs in the original NetworkX graph are mapped to sequential integers
        starting from 0 in the NetworkData representation. The original node IDs
        are preserved as the '_label' if no label_attr_name is specified.
    """

    # TODO: should we also index nodes/edges attributes?

    nodes_table, node_id_map = extract_networkx_nodes_as_table(
        graph=graph,
        label_attr_name=label_attr_name,
        ignore_attributes=ignore_node_attributes,
    )

    edges_table = extract_networkx_edges_as_table(graph, node_id_map)

    network_data = NetworkData.create_network_data(
        nodes_table=nodes_table, edges_table=edges_table
    )

    return network_data
query_edges(sql_query: str, relation_name: str = EDGES_TABLE_NAME) -> pa.Table

Execute SQL queries on the edges table for flexible data analysis.

This method provides direct SQL access to the edges table, enabling complex queries and aggregations. All computed edge columns are available for querying.

Available Columns: - 'edge_id': Unique edge identifier - '_source', '_target': Node IDs for edge endpoints - '_count_dup_directed': Number of parallel edges (directed interpretation) - '_idx_dup_directed': Index within parallel edge group (directed) - '_count_dup_undirected': Number of parallel edges (undirected interpretation) - '_idx_dup_undirected': Index within parallel edge group (undirected) - Original edge attributes (names without '' prefix)

Parameters:

Name Type Description Default
sql_query str

SQL query string. Use 'edges' as the table name in your query.

required
relation_name str

Alternative table name to use in the query (default: 'edges'). If specified, all occurrences of this name in the query will be replaced with 'edges'.

EDGES_TABLE_NAME

Returns:

Type Description
Table

pa.Table: Query results as a PyArrow table

Example
# Find edges with high multiplicity
parallel_edges = network_data.query_edges(
    "SELECT _source, _target, _count_dup_directed FROM edges WHERE _count_dup_directed > 1"
)

# Get edge statistics
stats = network_data.query_edges(
    "SELECT COUNT(*) as total_edges, AVG(_count_dup_directed) as avg_multiplicity FROM edges"
)
Source code in src/kiara_plugin/network_analysis/models/__init__.py
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
def query_edges(
    self, sql_query: str, relation_name: str = EDGES_TABLE_NAME
) -> "pa.Table":
    """Execute SQL queries on the edges table for flexible data analysis.

    This method provides direct SQL access to the edges table, enabling complex
    queries and aggregations. All computed edge columns are available for querying.

    **Available Columns:**
    - '_edge_id': Unique edge identifier
    - '_source', '_target': Node IDs for edge endpoints
    - '_count_dup_directed': Number of parallel edges (directed interpretation)
    - '_idx_dup_directed': Index within parallel edge group (directed)
    - '_count_dup_undirected': Number of parallel edges (undirected interpretation)
    - '_idx_dup_undirected': Index within parallel edge group (undirected)
    - Original edge attributes (names without '_' prefix)

    Args:
        sql_query: SQL query string. Use 'edges' as the table name in your query.
        relation_name: Alternative table name to use in the query (default: 'edges').
            If specified, all occurrences of this name in the query will be replaced
            with 'edges'.

    Returns:
        pa.Table: Query results as a PyArrow table

    Example:
        ```python
        # Find edges with high multiplicity
        parallel_edges = network_data.query_edges(
            "SELECT _source, _target, _count_dup_directed FROM edges WHERE _count_dup_directed > 1"
        )

        # Get edge statistics
        stats = network_data.query_edges(
            "SELECT COUNT(*) as total_edges, AVG(_count_dup_directed) as avg_multiplicity FROM edges"
        )
        ```
    """
    import duckdb

    con = duckdb.connect()
    edges = self.edges.arrow_table  # noqa: F841
    if relation_name != EDGES_TABLE_NAME:
        sql_query = sql_query.replace(relation_name, EDGES_TABLE_NAME)

    result = con.execute(sql_query)
    return result.arrow()
query_nodes(sql_query: str, relation_name: str = NODES_TABLE_NAME) -> pa.Table

Execute SQL queries on the nodes table for flexible data analysis.

This method provides direct SQL access to the nodes table, enabling complex queries and aggregations. All computed node statistics are available for querying.

Available Columns: - 'node_id': Unique node identifier - '_label': Human-readable node label - '_count_edges': Total edge count (simple graph interpretation) - '_count_edges_multi': Total edge count (multi-graph interpretation) - '_in_edges': Incoming edge count (directed, simple) - '_out_edges': Outgoing edge count (directed, simple) - '_in_edges_multi': Incoming edge count (directed, multi) - '_out_edges_multi': Outgoing edge count (directed, multi) - '_degree_centrality': Normalized degree centrality (simple) - '_degree_centrality_multi': Normalized degree centrality (multi) - Original node attributes (names without '' prefix)

Parameters:

Name Type Description Default
sql_query str

SQL query string. Use 'nodes' as the table name in your query.

required
relation_name str

Alternative table name to use in the query (default: 'nodes'). If specified, all occurrences of this name in the query will be replaced with 'nodes'.

NODES_TABLE_NAME

Returns:

Type Description
Table

pa.Table: Query results as a PyArrow table

Example
# Find high-degree nodes
hubs = network_data.query_nodes(
    "SELECT _node_id, _label, _count_edges FROM nodes WHERE _count_edges > 10 ORDER BY _count_edges DESC"
)

# Get centrality statistics
centrality_stats = network_data.query_nodes(
    "SELECT AVG(_degree_centrality) as avg_centrality, MAX(_degree_centrality) as max_centrality FROM nodes"
)
Source code in src/kiara_plugin/network_analysis/models/__init__.py
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
def query_nodes(
    self, sql_query: str, relation_name: str = NODES_TABLE_NAME
) -> "pa.Table":
    """Execute SQL queries on the nodes table for flexible data analysis.

    This method provides direct SQL access to the nodes table, enabling complex
    queries and aggregations. All computed node statistics are available for querying.

    **Available Columns:**
    - '_node_id': Unique node identifier
    - '_label': Human-readable node label
    - '_count_edges': Total edge count (simple graph interpretation)
    - '_count_edges_multi': Total edge count (multi-graph interpretation)
    - '_in_edges': Incoming edge count (directed, simple)
    - '_out_edges': Outgoing edge count (directed, simple)
    - '_in_edges_multi': Incoming edge count (directed, multi)
    - '_out_edges_multi': Outgoing edge count (directed, multi)
    - '_degree_centrality': Normalized degree centrality (simple)
    - '_degree_centrality_multi': Normalized degree centrality (multi)
    - Original node attributes (names without '_' prefix)

    Args:
        sql_query: SQL query string. Use 'nodes' as the table name in your query.
        relation_name: Alternative table name to use in the query (default: 'nodes').
            If specified, all occurrences of this name in the query will be replaced
            with 'nodes'.

    Returns:
        pa.Table: Query results as a PyArrow table

    Example:
        ```python
        # Find high-degree nodes
        hubs = network_data.query_nodes(
            "SELECT _node_id, _label, _count_edges FROM nodes WHERE _count_edges > 10 ORDER BY _count_edges DESC"
        )

        # Get centrality statistics
        centrality_stats = network_data.query_nodes(
            "SELECT AVG(_degree_centrality) as avg_centrality, MAX(_degree_centrality) as max_centrality FROM nodes"
        )
        ```
    """
    import duckdb

    con = duckdb.connect()
    nodes = self.nodes.arrow_table  # noqa
    if relation_name != NODES_TABLE_NAME:
        sql_query = sql_query.replace(relation_name, NODES_TABLE_NAME)

    result = con.execute(sql_query)
    return result.arrow()
retrieve_graph_data(nodes_callback: Union[NodesCallback, None] = None, edges_callback: Union[EdgesCallback, None] = None, incl_node_attributes: Union[bool, str, Iterable[str]] = False, incl_edge_attributes: Union[bool, str, Iterable[str]] = False, omit_self_loops: bool = False)

Retrieve graph data from the sqlite database, and call the specified callbacks for each node and edge.

First the nodes will be processed, then the edges, if that does not suit your needs you can just use this method twice, and set the callback you don't need to None.

The nodes_callback will be called with the following arguments
  • node_id: the id of the node (int)
  • if False: nothing else
  • if True: all node attributes, in the order they are defined in the table schema
  • if str: the value of the specified node attribute
  • if Iterable[str]: the values of the specified node attributes, in the order they are specified
The edges_callback will be called with the following aruments
  • source_id: the id of the source node (int)
  • target_id: the id of the target node (int)
  • if False: nothing else
  • if True: all edge attributes, in the order they are defined in the table schema
  • if str: the value of the specified edge attribute
  • if Iterable[str]: the values of the specified edge attributes, in the order they are specified
Source code in src/kiara_plugin/network_analysis/models/__init__.py
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
def retrieve_graph_data(
    self,
    nodes_callback: Union[NodesCallback, None] = None,
    edges_callback: Union[EdgesCallback, None] = None,
    incl_node_attributes: Union[bool, str, Iterable[str]] = False,
    incl_edge_attributes: Union[bool, str, Iterable[str]] = False,
    omit_self_loops: bool = False,
):
    """Retrieve graph data from the sqlite database, and call the specified callbacks for each node and edge.

    First the nodes will be processed, then the edges, if that does not suit your needs you can just use this method twice, and set the callback you don't need to None.

    The nodes_callback will be called with the following arguments:
        - node_id: the id of the node (int)
        - if False: nothing else
        - if True: all node attributes, in the order they are defined in the table schema
        - if str: the value of the specified node attribute
        - if Iterable[str]: the values of the specified node attributes, in the order they are specified

    The edges_callback will be called with the following aruments:
        - source_id: the id of the source node (int)
        - target_id: the id of the target node (int)
        - if False: nothing else
        - if True: all edge attributes, in the order they are defined in the table schema
        - if str: the value of the specified edge attribute
        - if Iterable[str]: the values of the specified edge attributes, in the order they are specified

    """

    if nodes_callback is not None:
        node_attr_names = self._calculate_node_attributes(incl_node_attributes)

        nodes_df = self.nodes.to_polars_dataframe()
        for row in nodes_df.select(*node_attr_names).rows(named=True):
            nodes_callback(**row)  # type: ignore

    if edges_callback is not None:
        edge_attr_names = self._calculate_edge_attributes(incl_edge_attributes)

        edges_df = self.edges.to_polars_dataframe()
        for row in edges_df.select(*edge_attr_names).rows(named=True):
            if (
                omit_self_loops
                and row[SOURCE_COLUMN_NAME] == row[TARGET_COLUMN_NAME]
            ):
                continue
            edges_callback(**row)  # type: ignore
as_networkx_graph(graph_type: Type[NETWORKX_GRAPH_TYPE], incl_node_attributes: Union[bool, str, Iterable[str]] = False, incl_edge_attributes: Union[bool, str, Iterable[str]] = False, omit_self_loops: bool = False) -> NETWORKX_GRAPH_TYPE

Export the network data as a NetworkX graph object.

This method converts the NetworkData to any NetworkX graph type, providing flexibility to work with the data using NetworkX's extensive algorithm library. The conversion preserves node and edge attributes as specified.

Supported Graph Types: - nx.Graph: Undirected simple graph (parallel edges are merged) - nx.DiGraph: Directed simple graph (parallel edges are merged) - nx.MultiGraph: Undirected multigraph (parallel edges preserved) - nx.MultiDiGraph: Directed multigraph (parallel edges preserved)

Attribute Handling: Node and edge attributes can be selectively included in the exported graph. Internal columns (prefixed with '_') are available but typically excluded from exports to maintain clean NetworkX compatibility.

Parameters:

Name Type Description Default
graph_type Type[NETWORKX_GRAPH_TYPE]

NetworkX graph class to instantiate (nx.Graph, nx.DiGraph, etc.)

required
incl_node_attributes Union[bool, str, Iterable[str]]

Controls which node attributes to include: - False: No attributes (only node IDs) - True: All attributes (including computed columns) - str: Single attribute name to include - Iterable[str]: List of specific attributes to include

False
incl_edge_attributes Union[bool, str, Iterable[str]]

Controls which edge attributes to include: - False: No attributes - True: All attributes (including computed columns) - str: Single attribute name to include - Iterable[str]: List of specific attributes to include

False
omit_self_loops bool

If True, edges where source equals target are excluded

False

Returns:

Name Type Description
NETWORKX_GRAPH_TYPE NETWORKX_GRAPH_TYPE

NetworkX graph instance of the specified type

Note

When exporting to simple graph types (Graph, DiGraph), parallel edges are automatically merged. Use MultiGraph or MultiDiGraph to preserve all edge instances.

Source code in src/kiara_plugin/network_analysis/models/__init__.py
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
def as_networkx_graph(
    self,
    graph_type: Type[NETWORKX_GRAPH_TYPE],
    incl_node_attributes: Union[bool, str, Iterable[str]] = False,
    incl_edge_attributes: Union[bool, str, Iterable[str]] = False,
    omit_self_loops: bool = False,
) -> NETWORKX_GRAPH_TYPE:
    """Export the network data as a NetworkX graph object.

    This method converts the NetworkData to any NetworkX graph type, providing
    flexibility to work with the data using NetworkX's extensive algorithm library.
    The conversion preserves node and edge attributes as specified.

    **Supported Graph Types:**
    - **nx.Graph**: Undirected simple graph (parallel edges are merged)
    - **nx.DiGraph**: Directed simple graph (parallel edges are merged)
    - **nx.MultiGraph**: Undirected multigraph (parallel edges preserved)
    - **nx.MultiDiGraph**: Directed multigraph (parallel edges preserved)

    **Attribute Handling:**
    Node and edge attributes can be selectively included in the exported graph.
    Internal columns (prefixed with '_') are available but typically excluded
    from exports to maintain clean NetworkX compatibility.

    Args:
        graph_type: NetworkX graph class to instantiate (nx.Graph, nx.DiGraph, etc.)
        incl_node_attributes: Controls which node attributes to include:
            - False: No attributes (only node IDs)
            - True: All attributes (including computed columns)
            - str: Single attribute name to include
            - Iterable[str]: List of specific attributes to include
        incl_edge_attributes: Controls which edge attributes to include:
            - False: No attributes
            - True: All attributes (including computed columns)
            - str: Single attribute name to include
            - Iterable[str]: List of specific attributes to include
        omit_self_loops: If True, edges where source equals target are excluded

    Returns:
        NETWORKX_GRAPH_TYPE: NetworkX graph instance of the specified type

    Note:
        When exporting to simple graph types (Graph, DiGraph), parallel edges
        are automatically merged. Use MultiGraph or MultiDiGraph to preserve
        all edge instances.
    """

    graph: NETWORKX_GRAPH_TYPE = graph_type()

    def add_node(_node_id: int, **attrs):
        graph.add_node(_node_id, **attrs)

    def add_edge(_source: int, _target: int, **attrs):
        graph.add_edge(_source, _target, **attrs)

    self.retrieve_graph_data(
        nodes_callback=add_node,
        edges_callback=add_edge,
        incl_node_attributes=incl_node_attributes,
        incl_edge_attributes=incl_edge_attributes,
        omit_self_loops=omit_self_loops,
    )

    return graph
as_rustworkx_graph(graph_type: Type[RUSTWORKX_GRAPH_TYPE], multigraph: bool = False, incl_node_attributes: Union[bool, str, Iterable[str]] = False, incl_edge_attributes: Union[bool, str, Iterable[str]] = False, omit_self_loops: bool = False, attach_node_id_map: bool = False) -> RUSTWORKX_GRAPH_TYPE

Export the network data as a RustWorkX graph object.

RustWorkX provides high-performance graph algorithms implemented in Rust with Python bindings. This method converts NetworkData to RustWorkX format while handling the differences in node ID management between the two systems.

Supported Graph Types: - rx.PyGraph: Undirected graph (with optional multigraph support) - rx.PyDiGraph: Directed graph (with optional multigraph support)

Node ID Mapping: RustWorkX uses sequential integer node IDs starting from 0, which may differ from the original NetworkData node IDs. The original '_node_id' values are preserved as node attributes, and an optional mapping can be attached to the graph for reference.

Performance Benefits: RustWorkX graphs offer significant performance advantages for: - Large-scale graph algorithms - Parallel processing - Memory-efficient operations - High-performance centrality calculations

Parameters:

Name Type Description Default
graph_type Type[RUSTWORKX_GRAPH_TYPE]

RustWorkX graph class (rx.PyGraph or rx.PyDiGraph)

required
multigraph bool

If True, parallel edges are preserved; if False, they are merged

False
incl_node_attributes Union[bool, str, Iterable[str]]

Controls which node attributes to include: - False: No attributes (only node data structure) - True: All attributes (including computed columns) - str: Single attribute name to include - Iterable[str]: List of specific attributes to include

False
incl_edge_attributes Union[bool, str, Iterable[str]]

Controls which edge attributes to include: - False: No attributes - True: All attributes (including computed columns) - str: Single attribute name to include - Iterable[str]: List of specific attributes to include

False
omit_self_loops bool

If True, self-loops (edges where source == target) are excluded

False
attach_node_id_map bool

If True, adds a 'node_id_map' attribute to the graph containing the mapping from RustWorkX node IDs to original NetworkData node IDs

False

Returns:

Name Type Description
RUSTWORKX_GRAPH_TYPE RUSTWORKX_GRAPH_TYPE

RustWorkX graph instance of the specified type

Note

The original NetworkData '_node_id' values are always included in the node data dictionary, regardless of the incl_node_attributes setting.

Source code in src/kiara_plugin/network_analysis/models/__init__.py
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
def as_rustworkx_graph(
    self,
    graph_type: Type[RUSTWORKX_GRAPH_TYPE],
    multigraph: bool = False,
    incl_node_attributes: Union[bool, str, Iterable[str]] = False,
    incl_edge_attributes: Union[bool, str, Iterable[str]] = False,
    omit_self_loops: bool = False,
    attach_node_id_map: bool = False,
) -> RUSTWORKX_GRAPH_TYPE:
    """Export the network data as a RustWorkX graph object.

    RustWorkX provides high-performance graph algorithms implemented in Rust with
    Python bindings. This method converts NetworkData to RustWorkX format while
    handling the differences in node ID management between the two systems.

    **Supported Graph Types:**
    - **rx.PyGraph**: Undirected graph (with optional multigraph support)
    - **rx.PyDiGraph**: Directed graph (with optional multigraph support)

    **Node ID Mapping:**
    RustWorkX uses sequential integer node IDs starting from 0, which may differ
    from the original NetworkData node IDs. The original '_node_id' values are
    preserved as node attributes, and an optional mapping can be attached to
    the graph for reference.

    **Performance Benefits:**
    RustWorkX graphs offer significant performance advantages for:
    - Large-scale graph algorithms
    - Parallel processing
    - Memory-efficient operations
    - High-performance centrality calculations

    Args:
        graph_type: RustWorkX graph class (rx.PyGraph or rx.PyDiGraph)
        multigraph: If True, parallel edges are preserved; if False, they are merged
        incl_node_attributes: Controls which node attributes to include:
            - False: No attributes (only node data structure)
            - True: All attributes (including computed columns)
            - str: Single attribute name to include
            - Iterable[str]: List of specific attributes to include
        incl_edge_attributes: Controls which edge attributes to include:
            - False: No attributes
            - True: All attributes (including computed columns)
            - str: Single attribute name to include
            - Iterable[str]: List of specific attributes to include
        omit_self_loops: If True, self-loops (edges where source == target) are excluded
        attach_node_id_map: If True, adds a 'node_id_map' attribute to the graph
            containing the mapping from RustWorkX node IDs to original NetworkData node IDs

    Returns:
        RUSTWORKX_GRAPH_TYPE: RustWorkX graph instance of the specified type

    Note:
        The original NetworkData '_node_id' values are always included in the
        node data dictionary, regardless of the incl_node_attributes setting.
    """

    from bidict import bidict

    graph = graph_type(multigraph=multigraph)

    # rustworkx uses 0-based integer indexes, so we don't neeed to look up the node ids (unless we want to
    # include node attributes)

    self._calculate_node_attributes(incl_node_attributes)[1:]
    self._calculate_edge_attributes(incl_edge_attributes)[2:]

    # we can use a 'global' dict here because we know the nodes are processed before the edges
    node_map: bidict = bidict()

    def add_node(_node_id: int, **attrs):
        data = {NODE_ID_COLUMN_NAME: _node_id}
        data.update(attrs)

        graph_node_id = graph.add_node(data)

        node_map[graph_node_id] = _node_id
        # if not _node_id == graph_node_id:
        #     raise Exception("Internal error: node ids don't match")

    def add_edge(_source: int, _target: int, **attrs):
        source = node_map[_source]
        target = node_map[_target]
        if not attrs:
            graph.add_edge(source, target, None)
        else:
            graph.add_edge(source, target, attrs)

    self.retrieve_graph_data(
        nodes_callback=add_node,
        edges_callback=add_edge,
        incl_node_attributes=incl_node_attributes,
        incl_edge_attributes=incl_edge_attributes,
        omit_self_loops=omit_self_loops,
    )

    if attach_node_id_map:
        graph.attrs = {"node_id_map": node_map}  # type: ignore

    return graph

Functions

guess_node_id_column_name(nodes_table: Union[pa.Table, KiaraTable, Value], suggestions: Union[None, List[str]] = None) -> Union[str, None]

Source code in src/kiara_plugin/network_analysis/utils/__init__.py
429
430
431
432
433
434
435
def guess_node_id_column_name(
    nodes_table: Union["pa.Table", "KiaraTable", "Value"],
    suggestions: Union[None, List[str]] = None,
) -> Union[str, None]:
    if suggestions is None:
        suggestions = NODE_ID_ALIAS_NAMES
    return guess_column_name(table=nodes_table, suggestions=suggestions)

guess_node_label_column_name(nodes_table: Union[pa.Table, KiaraTable, Value], suggestions: Union[None, List[str]] = None) -> Union[str, None]

Source code in src/kiara_plugin/network_analysis/utils/__init__.py
438
439
440
441
442
443
444
def guess_node_label_column_name(
    nodes_table: Union["pa.Table", "KiaraTable", "Value"],
    suggestions: Union[None, List[str]] = None,
) -> Union[str, None]:
    if suggestions is None:
        suggestions = LABEL_ALIAS_NAMES
    return guess_column_name(table=nodes_table, suggestions=suggestions)

guess_source_column_name(edges_table: Union[pa.Table, KiaraTable, Value], suggestions: Union[None, List[str]] = None) -> Union[str, None]

Source code in src/kiara_plugin/network_analysis/utils/__init__.py
447
448
449
450
451
452
453
def guess_source_column_name(
    edges_table: Union["pa.Table", "KiaraTable", "Value"],
    suggestions: Union[None, List[str]] = None,
) -> Union[str, None]:
    if suggestions is None:
        suggestions = SOURCE_COLUMN_ALIAS_NAMES
    return guess_column_name(table=edges_table, suggestions=suggestions)

guess_target_column_name(edges_table: Union[pa.Table, KiaraTable, Value], suggestions: Union[None, List[str]] = None) -> Union[str, None]

Source code in src/kiara_plugin/network_analysis/utils/__init__.py
456
457
458
459
460
461
462
def guess_target_column_name(
    edges_table: Union["pa.Table", "KiaraTable", "Value"],
    suggestions: Union[None, List[str]] = None,
) -> Union[str, None]:
    if suggestions is None:
        suggestions = TARGET_COLUMN_ALIAS_NAMES
    return guess_column_name(table=edges_table, suggestions=suggestions)

get_version() -> str

Get the current version of the kiara_plugin.network_analysis module.

This tries to get the version from the current git commit or tag, if possible.

Returns:

Name Type Description
str str

The version string.

Source code in src/kiara_plugin/network_analysis/__init__.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def get_version() -> str:
    """Get the current version of the `kiara_plugin.network_analysis` module.

    This tries to get the version from the current git commit or tag, if possible.

    Returns:
        str: The version string.

    """

    from importlib.metadata import PackageNotFoundError, version

    try:
        # Change here if project is renamed and does not equal the package name
        dist_name = __name__
        __version__ = version(dist_name)
    except PackageNotFoundError:
        try:
            version_file = os.path.join(os.path.dirname(__file__), "version.txt")

            if os.path.exists(version_file):
                with open(version_file, encoding="utf-8") as vf:
                    __version__ = vf.read()
            else:
                __version__ = "unknown"

        except Exception:
            pass

        if __version__ is None:
            __version__ = "unknown"

    return __version__