Skip to content

Commit

Permalink
Merge branch 'networkx:main' into task2
Browse files Browse the repository at this point in the history
  • Loading branch information
achluma authored Oct 5, 2023
2 parents 371cf2a + c1f1176 commit 84fcb00
Show file tree
Hide file tree
Showing 13 changed files with 1,346 additions and 0 deletions.
1 change: 1 addition & 0 deletions 2023-round-2/KramStyles/nx_version.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.1
1 change: 1 addition & 0 deletions 2023-round-2/Olauryn/nx_version.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.1
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions 2023-round-2/PromiseFru/nx_version.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.1
320 changes: 320 additions & 0 deletions 2023-round-2/Tanya-Rawat/nx_dev_test_output.txt

Large diffs are not rendered by default.

406 changes: 406 additions & 0 deletions 2023-round-2/Ytemiloluwa/nx_dev_test_output.txt

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions 2023-round-2/achluma/nx_version.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.1
38 changes: 38 additions & 0 deletions 2023-round-2/akshayamadhuri/nx_tutorial_script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import networkx as nx
import matplotlib.pyplot as plt

# Create a directed graph object
G = nx.DiGraph()

# Add nodes of different types (int, str, tuple)
G.add_node(1)
G.add_node("aam")
G.add_node((3, 4))

# Add multiple edges between nodes
G.add_edge(1, "aam")
G.add_edge("aam", (3, 4))
G.add_edge((3, 4), 4)

# Add more nodes and edges (up to 10 nodes)
G.add_edges_from([('a', 'b'),('aam', 1),(9, (3, 4)), (9, 1),
('aam', 9),
((3, 4), 0),
('a', 9),
(0, 'b')])

# Find and print the shortest path between all pairs of nodes
for node1 in G.nodes():
for node2 in G.nodes():
if node1 != node2:
if nx.has_path(G, source=node1, target=node2):
shortest_path = nx.shortest_path(G, source=node1, target=node2)
print(f"Shortest path from {node1} to {node2}: {shortest_path}")
else:
print(f"No path from {node1} to {node2}")

# Plot the graph
pos = nx.spring_layout(G, seed=42) # Positioning nodes for visualization
nx.draw(G, pos, with_labels=True, node_size=500, node_color='skyblue')
plt.title("Directed Graph")
plt.show()
38 changes: 38 additions & 0 deletions 2023-round-2/axif0/nx_tutorial_script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import networkx as nx
import matplotlib.pyplot as plt

# Create a directed graph and add nodes and edges
def create_graph():
G = nx.DiGraph()
nodes = ['Outreachy', 1, (1, 2), 1.1, True, 'networkx', (2, 3), 2.2, False, 'asif']
G.add_nodes_from((node, {'color': 'blue'}) for node in nodes)
edges = [('Outreachy', 1), (1, (1, 2)), ((1, 2), 1.1), (1.1, True), (True, 'networkx'), ('networkx', (2, 3)), ((2, 3), 2.2), (2.2, False), (False, 'asif'), ('asif', 'Outreachy'), ('Outreachy', 2.2), (1, (2, 3)), ((1, 2), True), (1.1, False)]
G.add_edges_from((edge[0], edge[1], {'color': 'green'}) for edge in edges)
return G

# Calculate the shortest path between all pairs of nodes
def calculate_shortest_path(G):
paths = nx.floyd_warshall(G)
for source, targets in paths.items():
for target, path in targets.items():
print(f'Shortest path from {source} to {target}: {path}')

# Calculate the degree centrality of the nodes
def calculate_centrality(G):
centrality = nx.degree_centrality(G)
print('Degree centrality:', centrality)

# Draw and show the graph
def plot_graph(G):
pos = nx.spring_layout(G, seed=42)
nx.draw(G, pos, with_labels=True, node_color=[data['color'] for node, data in G.nodes(data=True)], edge_color=[data['color'] for _, _, data in G.edges(data=True)])
plt.show()

def main():
G = create_graph()
calculate_shortest_path(G)
calculate_centrality(G)
plot_graph(G)

if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions 2023-round-2/factism001/nx_version.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.1
1 change: 1 addition & 0 deletions 2023-round-2/khushishikhu/nx_version.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.1
405 changes: 405 additions & 0 deletions 2023-round-2/olami22/nx_dev_test_output.txt

Large diffs are not rendered by default.

133 changes: 133 additions & 0 deletions 2023-round-2/unna97/nx_tutorial_script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random

print(nx.__version__)


def highlight_path_given(path_highlight, position, color="yellow", alpha=0.8, width=5):

nx.draw_networkx_edges(
example_directed_graph,
edgelist=path_highlight,
pos=position,
edge_color=color,
alpha=alpha,
ax=ax,
width=width,
)

nx.draw(example_directed_graph, pos=position, ax=ax, with_labels=True)


def update_fig(i):
ax.clear()
highlight_path_given(path_edges[i], position)
fig.suptitle(f"Path {i + 1} of {len(path_edges)}")


def create_animation_highlight_paths(path_edges):

ani = animation.FuncAnimation(
fig,
update_fig,
frames=len(path_edges),
)

gif_file_path = r"shortest_paths.gif"
writergif = animation.PillowWriter(fps=1)
ani.save(gif_file_path, writer=writergif)
return ani


if __name__ == "__main__":
### Intializing the graph:
example_directed_graph = nx.DiGraph()

### Adding nodes from list:
random_nodes = {
'str': ['node_string','blue', 'random_str'],
'int': [0,2,512],
'tuple': [(1,'hey',85),((2,4), 41) ],
}
### Adding nodes from dict:
for key, values in random_nodes.items():
example_directed_graph.add_nodes_from(values, type=key)


### Only unique node_values will be added
print("nodes added:", example_directed_graph.nodes())
nodes_in_graph = list(example_directed_graph.nodes())

### Adding random edges between nodes:
for i in range(10):
example_directed_graph.add_edge(
random.choice(nodes_in_graph), random.choice(nodes_in_graph)
)

### Edges will be also added only once, above will create at max 10:
print("edges added:", example_directed_graph.edges())
print("number of edges added:", example_directed_graph.number_of_edges())

### Finding shortest paths between nodes in an unweighted directed graph:
###In case of multiple shortest paths between two pair of nodes, only one is returned in methods belows:

### Method 1:
print(
"Method 1 shortest path between nodes:",
nx.shortest_path(example_directed_graph),
)

### Method 2: Get the generator of all pairs shortest paths:
print(
"Method 2 shortest path between nodes:",
dict(nx.all_pairs_shortest_path(example_directed_graph)),
)

### Method 3: Get the generator of single source shortest paths (for all nodes):
for node in example_directed_graph.nodes():
print(
f"Method 3 shortest path between {node} and other reachable nodes",
dict(nx.single_source_shortest_path(example_directed_graph, node)),
)

### Plot the graph:
nx.draw(
example_directed_graph, with_labels=True, node_size=100, alpha=1, linewidths=10
)
plt.show()

### Create a gif, highlighting the shortest paths:
position = nx.spring_layout(example_directed_graph)
fig, ax = plt.subplots(figsize=(10, 10))
plt.close()
paths = nx.shortest_path(example_directed_graph)
path_edges = []

for source_node in paths:
for target_node in paths[source_node]:
path = paths[source_node][target_node]
path_edge = list(zip(path, path[1:]))
path_edges.append(path_edge)
print(path_edges)

create_animation_highlight_paths(path_edges)

### All shortest paths between pairs of node:
print("All shortest paths between all pairs of nodes:\n")

for source_node in paths:
for target_node in paths[source_node]:
print(
"source_node:",
source_node,
"target_node:",
target_node,
"\npaths:",
list(
nx.all_shortest_paths(
example_directed_graph, source=source_node, target=target_node
)
),
)

0 comments on commit 84fcb00

Please sign in to comment.