Created
June 19, 2014 11:12
-
-
Save lawlesst/78fb1d45a2b2ba2cd55a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Mint random number based IRIs. | |
""" | |
BU = Namespace('http://vivo.brown.edu/individual/') | |
def get_next_uri(self, prefix='n', number=1, used_uris=[], max=99999): | |
""" | |
Mint new URIs in the VIVO pattern (e.g. n1234). | |
SPARQL interpretation of getNextURI here: | |
https://github.com/vivo-project/Vitro/blob/maint-rel-1.7/webapp/src/edu/cornell/mannlib/vitro/webapp/utils/jena/JenaIngestUtils.java#L250 | |
""" | |
count = 0 | |
out = [] | |
minted_uris = 0 | |
while True: | |
next_uri = URIRef(BU + prefix + str(random.randint(1, max))) | |
#Make sure we haven't used this URI already. | |
if next_uri in used_uris: | |
continue | |
if next_uri in out: | |
continue | |
count += 1 | |
q = """ | |
SELECT ?o ?s2 | |
WHERE {{ | |
OPTIONAL{{<{0}> ?p ?o}}. | |
OPTIONAL{{?s2 ?p2 <{0}>}}. | |
}} | |
""".format(next_uri) | |
results = [row for row in self.query(q)] | |
#Make sure result set is empty. | |
if results == [(None, None)]: | |
minted_uris += 1 | |
out.append(next_uri) | |
#Don't create more uris than was requested. | |
if minted_uris >= number: | |
break | |
else: | |
#Raise an exception if we try 50 URIs and none are 'new'. | |
#This probably means something is wrong. | |
vlog.debug("{0} is an assigned URI. Trying again.".format(next_uri)) | |
if count == 50: | |
raise VIVODataError(""" | |
50 random uris were tried and none returned | |
a unique uri. Verify or increase max random uri.""") | |
if number == 1: | |
return out[0] | |
else: | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment