-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_graph_csv.py
More file actions
122 lines (97 loc) · 3.47 KB
/
read_graph_csv.py
File metadata and controls
122 lines (97 loc) · 3.47 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
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
"""
Lukee verkkograafin CSV-tiedostosta.
CSV-formaatti — kaksi rivityyppiä:
- Nodes-rivi: pilkulla eroteltu lista solmujen nimistä
Ma, Mb, Mc, M4, M5, ...
- Links-rivi: pilkulla eroteltu lista yhteyksistä muodossa "A - B"
Ma - Mb, Ma - M10, Mb - Mc, ...
Rivityyppi tunnistetaan automaattisesti: jos arvo sisältää " - ", se on linkki.
"""
import csv
import json
def read_graph_csv(filepath: str) -> tuple[list[str], list[tuple[str, str]]]:
"""
Lukee verkkograafin CSV-tiedostosta.
Returns:
nodes: lista solmujen nimistä
links: lista (alku, loppu) -tupleista
"""
nodes: list[str] = []
links: list[tuple[str, str]] = []
with open(filepath, newline="", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
values = [v.strip() for v in row if v.strip()]
if not values:
continue
# Ohitetaan avainsanat "Nodes" ja "Links" rivin alussa
if values[0] in ("Nodes", "Links"):
values = values[1:]
if not values:
continue
# Tunnista rivityyppi: jos ensimmäinen arvo sisältää " - ", kaikki ovat linkkejä
if " - " in values[0]:
for item in values:
parts = [p.strip() for p in item.split(" - ")]
if len(parts) == 2:
links.append((parts[0], parts[1]))
else:
print(f"Varoitus: tuntematon linkkimuoto '{item}'")
else:
nodes.extend(values)
return nodes, links
def build_network(nodes: list[str], links: list[tuple[str, str]]) -> dict:
"""
Muodostaa verkon solmuista ja yhteyksistä.
Rakenne:
{
"nodes": [
{ "id": "Ma", "neighbors": ["Mb", "M10", "M11"] },
...
],
"links": [
{ "source": "Ma", "target": "Mb" },
...
]
}
"""
# Rakennetaan naapurilista jokaiselle solmulle
neighbor_map: dict[str, list[str]] = {node: [] for node in nodes}
for source, target in links:
if source in neighbor_map:
neighbor_map[source].append(target)
else:
print(f"Varoitus: linkissä tuntematon solmu '{source}'")
if target in neighbor_map:
neighbor_map[target].append(source) # suuntaamaton verkko
else:
print(f"Varoitus: linkissä tuntematon solmu '{target}'")
network = {
"nodes": [
{"id": node, "neighbors": neighbor_map[node]}
for node in nodes
],
"links": [
{"source": source, "target": target}
for source, target in links
]
}
return network
def main():
input_file = "J1c2n1.csv" # Vaihda tiedostopolku tarvittaessa
output_file = "J1c2n1-1.json"
nodes, links = read_graph_csv(input_file)
print("=== Solmut (Nodes) ===")
print(", ".join(nodes))
print(f"Yhteensä {len(nodes)} solmua.\n")
print("=== Yhteydet (Links) ===")
for source, target in links:
print(f" {source} --> {target}")
print(f"Yhteensä {len(links)} yhteyttä.\n")
# Muodostetaan verkko ja tallennetaan JSON:iin
network = build_network(nodes, links)
with open(output_file, "w", encoding="utf-8") as f:
json.dump(network, f, indent=2, ensure_ascii=False)
print(f"Verkko tallennettu tiedostoon: {output_file}")
if __name__ == "__main__":
main()