-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrophic.py
More file actions
47 lines (39 loc) · 1.39 KB
/
trophic.py
File metadata and controls
47 lines (39 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import numpy as np
def compute_trophic_influence(edges, num_nodes, decay=0.9, tol=1e-6, max_iter=100):
S = np.zeros((num_nodes, num_nodes))
# Step 1: Weighted influence
for consumer, prey in edges:
S[consumer - 1][prey - 1] = 1 / (prey + 1) # Uneven weights
# Step 2: Normalize rows
for i in range(num_nodes):
row_sum = np.sum(S[i])
if row_sum > 0:
S[i] /= row_sum
# Step 3: Power iteration with teleportation
T = np.ones(num_nodes) / num_nodes # uniform init
for _ in range(max_iter):
new_T = (1 - decay) / num_nodes + decay * (S @ T)
if np.linalg.norm(new_T - T, ord=1) < tol:
break
T = new_T
apex_node = np.argmax(T) + 1
return apex_node, T
# Your edges
edges = [
(1, 2), (1, 3), (1, 4), (1, 5), (1, 6),
(2, 1), (2, 3), (2, 4), (2, 5), (2, 7),
(3, 1), (3, 2), (3, 4), (3, 5), (3, 6),
(4, 1), (4, 2), (4, 3),
(5, 1), (5, 2), (5, 3), (5, 6),
(6, 1), (6, 3), (6, 4), (6, 9),
(7, 2), (7, 8), (7, 9),
(8, 5), (8, 7),
(9, 6), (9, 7)
]
num_nodes = 9
apex_node, trophic_levels = compute_trophic_influence(edges, num_nodes)
# Output
print(f"Highest value node (apex node): {apex_node}")
print("Trophic influence values for all nodes:")
for node, value in enumerate(trophic_levels, 1):
print(f"Node {node}: {value:.6f}")