# Introduction to NetworkX

## F. Mráz

NetworkX is a Python package for modeling, analyzing, and visializing networks

- several types of networks
- several algorithms for network analysis
- read/write networks in many formats

Documentation: https://networkx.github.io/documentation/stable/

At first, we must import the module networkx

## Creating Simple Graphs

The graph can have an arbitrary additional information.

## Nodes

Nodes in graphs manipulated with networkx can be arbitrary objects that are hashable. Most commnon are *numbers* and *strings*.

The argument `X`

in `nx.add_nodes_from(X)`

can be any iterable container.

Even a graph can be a node!

## Edges

The argument E in nx.add_nodes_from(E) can be any iterable container of edge-tuples. An edge-tuple can be

- a 2-tuple -
`(node`

$_1$`,node`

$_2$`)`

, or - a 3-tuple -
`(node`

$_1$`,node`

$_2$`, dc)`

, where`dc`

is a dictionary of edge attributes.

### Notes

- Adding existing nodes is no error.
- Adding existing edges is no error.
- Even a graph can be a node!
- Any edge and node can have an arbitrary number of atributes.

## Removing Nodes and Edges

## Accessing Nodes and Edges

## Atributes of Graphs, Nodes and Edges

Each grah, node and edge can have attributes that are stored in a associated attribute dictionary. Attributes are empty by default.

### Graph Attributes

They can be added when creating a new graph

changed or added later

### Node attributes

**Warning:** Adding nodes to `G.nodes`

does not add them to the graph. It is necessary to use `add_node()`

or `add_nodes_from()`

. Similarly for edges!

### Edge Attributes

### Edge Attributes (cont)

Attribute `weight`

is special, as it is used by several algorithms implemented in `networkx`

. Therefore the attribute `weight`

must be numeric.

Oops! What is the error?

Once again with the `weight`

attribute

## Directed Graphs

Directed graph are represented by the class `DiGraph`

with some specific properties, like `DiGraph.out_edges()`

, `Digraph.in_degree()`

, `DiGraph.out_degree()`

, `DiGraph.predecessors()`

, `DiGraph.successors()`

. Actually, the directed versions of `neighbors()`

is equivalent to `successors()`

while `degree`

reports the sum of `in_degree`

and `out_degree`

.

## Drawing Graphs

## Excercises

### 1. Construct a Simple Graph

Implement function `gener_house_graph()`

that returns an undirected graph representing the following drawing

Implement the following functions, assume that graph is undirected if not said otherwise:

A center of a graph is a node where the maximum distance (number of edges) traversed to any other node is a minimum, compared to any other node. Essentially, the center of a graph is the most centrally located node. Note that there may be more than one node that qualifies as the center of the graph.