Skip to content

Commit 5d15b53

Browse files
committed
externalized some utils to splendid
1 parent 0d32fd3 commit 5d15b53

File tree

5 files changed

+8
-77
lines changed

5 files changed

+8
-77
lines changed

gp_query.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
from collections import defaultdict
99
from collections import Counter
1010
from collections import Sequence
11-
1211
import logging
1312
import re
1413
import socket
@@ -17,26 +16,24 @@
1716
from cachetools import LRUCache
1817
import six
1918
from rdflib.term import Identifier
20-
21-
2219
import SPARQLWrapper
2320
from SPARQLWrapper.SPARQLExceptions import EndPointNotFound
2421
from SPARQLWrapper.SPARQLExceptions import SPARQLWrapperException
2522
from xml.sax.expatreader import SAXParseException
2623
# noinspection PyUnresolvedReferences
2724
from six.moves.urllib.error import URLError
25+
from splendid import chunker
26+
from splendid import get_path
27+
from splendid import time_func
2828

2929
import config
3030
from graph_pattern import GraphPattern
3131
from graph_pattern import SOURCE_VAR
3232
from graph_pattern import TARGET_VAR
3333
from graph_pattern import ASK_VAR
3434
from graph_pattern import COUNT_VAR
35-
from utils import chunker
3635
from utils import exception_stack_catcher
37-
from utils import get_path
3836
from utils import sparql_json_result_bindings_to_rdflib
39-
from utils import time
4037
from utils import timer
4138

4239
logger = logging.getLogger(__name__)
@@ -63,7 +60,7 @@ def calibrate_query_timeout(
6360
sparql.resetQuery()
6461
sparql.setReturnFormat(SPARQLWrapper.JSON)
6562
sparql.setQuery(q)
66-
t, r = time(sparql.queryAndConvert)
63+
t, r = time_func(sparql.queryAndConvert)
6764
total_time += t
6865
avg = total_time / n_queries
6966
timeout = avg * factor
@@ -392,7 +389,7 @@ def _query(
392389
try:
393390
q_short = ' '.join((line.strip() for line in q.split('\n')))
394391
sparql.setQuery(q_short)
395-
c = time(sparql.queryAndConvert)
392+
c = time_func(sparql.queryAndConvert)
396393
except socket.timeout:
397394
c = (timeout, {})
398395
except ValueError:

prediction_baselines.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,14 @@
99
from rdflib import URIRef
1010
from rdflib import Literal
1111
from rdflib import Variable
12+
from splendid import get_path
1213

1314
import config
1415
from gp_learner import find_in_prediction
1516
from graph_pattern import TARGET_VAR
1617
from ground_truth_tools import get_semantic_associations
1718
from ground_truth_tools import split_training_test_set
1819
import gp_query
19-
from utils import get_path
2020
from utils import sparql_json_result_bindings_to_rdflib
2121

2222
TIMEOUT = 30

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ scipy>=0.18.1
1313
scoop>=0.7.1.1
1414
six>=1.10.0
1515
SPARQLWrapper>=1.7.6
16+
splendid>=1.0.2
1617

1718
# cachetools==2.0.0
1819
# click==6.6

serialization.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,12 @@
2222
import deap.base
2323
import deap.tools
2424
import numpy as np
25+
from splendid import run_once
2526

2627
import config
2728
from graph_pattern import GraphPattern
2829
from gtp_scores import GTPScores
2930
from utils import decurify
30-
from utils import run_once
3131

3232
logger = logging.getLogger(__name__)
3333

utils.py

Lines changed: 0 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -23,20 +23,6 @@
2323
import six
2424

2525

26-
def chunker(iterable, n, fillvalue=None):
27-
"""Like a grouper but last tuple is shorter.
28-
29-
>>> list(chunker([1, 2, 3, 4, 5], 3))
30-
[[1, 2, 3], [4, 5]]
31-
"""
32-
if n < 1:
33-
raise ValueError("can't chunk by n=%d" % n)
34-
args = [iter(iterable)] * n
35-
return (
36-
[e for e in t if e is not None]
37-
for t in izip_longest(*args, fillvalue=fillvalue)
38-
)
39-
4026
# TODO: maybe automagically get these from http://prefix.cc ?
4127
# TODO: make this configurable
4228
_nsm = NamespaceManager(rdflib.Graph())
@@ -216,44 +202,6 @@ def inner(*args, **kwds):
216202
return outer
217203

218204

219-
def get_path(nested, key_path, default=None):
220-
"""Walks given nested by key_path returning default on any LookupError.
221-
222-
:param nested: a nested dictionary or list like structure
223-
:param key_path: a list resembling a nested path of keys
224-
:param default: returned if any key in the path isn't found
225-
:return: value of nested[k0][k1]...[kn] or default on error
226-
227-
>>> get_path({'foo':[{'bar':3}]}, ['foo'], 'not found')
228-
[{'bar': 3}]
229-
>>> get_path({'foo':[{'bar':3}]}, ['foo', 'bar'], 'not found')
230-
'not found'
231-
>>> get_path({'foo':[{'bar':3}]}, ['foo', 0, 'bar'], 'not found')
232-
3
233-
>>> get_path({'foo':[{'bar':3}]}, ['foo', 0], 'not found')
234-
{'bar': 3}
235-
"""
236-
while len(key_path) > 0:
237-
key, rest = key_path[0], key_path[1:]
238-
try:
239-
nested = nested[key]
240-
except (LookupError, TypeError):
241-
return default
242-
key_path = rest
243-
return nested
244-
245-
246-
def run_once(func):
247-
"""Decorator that causes a function to be executed only once."""
248-
@wraps(func)
249-
def wrapper(*args, **kwds):
250-
if not wrapper.ran:
251-
wrapper.ran = True
252-
return func(*args, **kwds)
253-
wrapper.ran = False
254-
return wrapper
255-
256-
257205
def sample_from_list(l, probs, max_n=None):
258206
"""Sample list according to probs.
259207
@@ -340,18 +288,3 @@ def dict_to_rdflib(d):
340288
res_bindings_rdflib.append(tmp)
341289

342290
return res_bindings_rdflib
343-
344-
345-
346-
def time(func, *args, **kwds):
347-
"""Evaluates function with given args and returns
348-
349-
:param func: function to be evaluated
350-
:param args: args for func
351-
:param kwds: kwds for func
352-
:return: a tuple: (timediff, func(*args, **kwds)
353-
"""
354-
start = timer()
355-
res = func(*args, **kwds)
356-
stop = timer()
357-
return stop - start, res

0 commit comments

Comments
 (0)