-
Notifications
You must be signed in to change notification settings - Fork 1
/
add_predicted_devices.py
143 lines (121 loc) · 4.55 KB
/
add_predicted_devices.py
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
from SPARQLWrapper import SPARQLWrapper, JSON
import pandas as pd
from pathlib import Path
from tqdm import tqdm
# noinspection PyShadowingBuiltins,PyBroadException
def get_highest_device_id(endpoint="http://193.2.205.14:7200/repositories/Electricity_Graph") -> int:
"""
Get the highest device id in the graph to know where to start adding new devices
## Parameters
endpoint : The endpoint of the graph database
## Returns
int : The highest device id
"""
query_houses = """
PREFIX saref: <https://saref.etsi.org/core/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX schema: <https://schema.org/>
SELECT DISTINCT ?device WHERE {
?device rdf:type saref:Device .
}
"""
sparlq_graphdb = SPARQLWrapper(endpoint)
sparlq_graphdb.setQuery(query_houses)
sparlq_graphdb.setReturnFormat(JSON)
try:
results_Graphdb = sparlq_graphdb.query().convert()
max_id = 0
for r in results_Graphdb["results"]["bindings"]:
id = int(r["device"]["value"].split("/")[-1])
if id > max_id:
max_id = id
return max_id
except:
print("Error in the query getting the highest device id")
return False
# noinspection PyTypeChecker,PyBroadException
def get_household(household: str, endpoint="http://193.2.205.14:7200/repositories/Electricity_Graph") -> str:
"""
Get the household uri from the graph
## Parameters
household : The name of the household
endpoint : The endpoint of the graph database
## Returns
str : The uri of the household
"""
query_houses = f"""
PREFIX saref: <https://saref.etsi.org/core/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX schema: <https://schema.org/>
SELECT DISTINCT ?household WHERE {{
?household rdf:type schema:House .
?household schema:name ?hname.
FILTER (?hname = '{household}')
}}
"""
sparlq_graphdb = SPARQLWrapper(endpoint)
sparlq_graphdb.setQuery(query_houses)
sparlq_graphdb.setReturnFormat(JSON)
try:
results_Graphdb = sparlq_graphdb.query().convert()
if len(results_Graphdb["results"]["bindings"]) == 0:
return False
else:
return results_Graphdb["results"]["bindings"]
except:
print("Error in the get household query")
return False
# noinspection PyBroadException
def insert_device(device_id: int, device_name: str, household: str,
endpoint="http://193.2.205.14:7200/repositories/Electricity_Graph"):
"""
Insert a device into the graph
## Parameters
device_id : The id of the device
device_name : The name of the device
household : The uri of the household
endpoint : The endpoint of the graph database
## Returns
bool : True if the device was inserted successfully, False otherwise
"""
sparql_insert_query = f"""
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX schema: <https://schema.org/>
INSERT DATA {{
<{household}> <https://elkg.ijs.si/ontology/containsDevice> <https://elkg.ijs.si/resource/public-devices/{device_id}> .
<https://elkg.ijs.si/resource/public-devices/{device_id}> a <https://saref.etsi.org/core/Device> .
<https://elkg.ijs.si/resource/public-devices/{device_id}> schema:name "{device_name}" .
}}
"""
sparlq_graphdb = SPARQLWrapper(endpoint)
sparlq_graphdb.setMethod('POST')
sparlq_graphdb.setQuery(sparql_insert_query)
try:
sparlq_graphdb.query()
return True
except:
print("Error in the insert query")
return False
# noinspection PyTypeChecker
def add_predicted_devices(predicted_path: Path, graph_endpoint: str):
"""
Add the predicted devices to the graph
## Parameters
predicted_path : The path to the predicted devices file
graph_endpoint : The endpoint of the graph database
## Returns
None
"""
data = pd.read_pickle(predicted_path / "predicted_devices.pkl")
start_id = get_highest_device_id(endpoint=graph_endpoint)
for house in tqdm(data):
household = get_household(house, endpoint=graph_endpoint)
if household:
household = household[0]["household"]["value"]
for device in data[house]:
start_id += 1
if not insert_device(start_id, device, household, endpoint=graph_endpoint):
print(f"Error inserting device {device} in house {house}")
break
else:
print(f"House {house} not found in the graph")