Jena Model Validation OntModel - owl

I have created an Ontology which i want use for validating instances, following is the test setup i have, couldnt get validation report one of uid is zero. which is xsd:minExclusive "0"^^xsd:unsignedLong.
Can anyone help m eunderstand best practice to use Jena, i am inteding to sue default model to recieve an input validating aginast ontModel and the merging in TDB backed model.
:Book rdf:type owl:Class ;
rdfs:subClassOf Model .
and data Property
:uid rdf:type owl:DatatypeProperty ,
owl:FunctionalProperty ;
rdfs:domain :Model ;
rdfs:range [ rdf:type rdfs:Datatype ;
owl:onDatatype xsd:unsignedLong ;
owl:withRestrictions ( [ xsd:minExclusive "0"^^xsd:unsignedLong
]
)
] .
Trying to use this ontology to validate data
OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM_RDFS_INF);
ontModel.read(getClass().getClassLoader().getResource("model.owl").toExternalForm(), NS);
// ontModel.write(System.out);
Reasoner reasoner = ontModel.getReasoner().bindSchema(ontModel);
Model data = createTestData();
//data.write(System.out);
InfModel infModel = ModelFactory.createInfModel(reasoner, data);
ValidityReport report = infModel.validate();
if (report.isValid())
System.out.println("valid");
and in the following code //(index - 1) ensure at least one id of 0
public static Model createTestData() {
Model instances = ModelFactory.createDefaultModel();
instances.setNsPrefix("rdfs", RDFS.getURI());
instances.setNsPrefix("rdf", RDF.getURI());
instances.setNsPrefix("a", NS);
instances.setNsPrefix("", NS + "#");
Property UID_PROPERTY = ResourceFactory.createProperty(NS + "#uid");
IntStream.of(1, 2, 3).forEach(index -> {
Resource r = instances.createResource(NS + "/item/" + (index - 1));
r.addProperty(UID_PROPERTY, ResourceFactory.createTypedLiteral((index - 1)));
});
return instances;
}

Related

OWL - associate transitive child with great-parent

I would like to simplify my SHACL definitions by reversing the relations between shapes, properties and groups.
A typical NodeShape looks like this. Two properties in a group:
<>
a sh:NodeShape ;
sh:property
[
sh:name "Property 1" ;
sh:order 1 ;
sh:group <#Group> ;
] ,
[
sh:name "Property 2" ;
sh:order 2 ;
sh:group <#Group> ;
] ;
.
It becomes a little unwieldy when there are multiple groups and many properties because all of them are tangled in the sh:property list of objects.
What I would like to achieve is to revers the relations a little using OWL rules so that I could type the RDF differently, but retain the equivalence with the above using reasoning.
<>
a sh:NodeShape ;
ex:group <#Group> ;
.
<#Property1>
sh:name "Property 1" ;
sh:order 1 ;
.
<#Property2>
sh:name "Property 2" ;
sh:order 2 ;
.
<#Group>
ex:property <#Property1>, <#Property2>
.
Is there a way to define ex:group and ex:property to infer the triples from first snippet?

using Transaction Execution Approval Language (TEAL) can I make my own coin?

Just like ERC-20 Tokens let you make a new currency on the ETH network, is there a way to use TEAL https://github.com/algorand/go-algorand/blob/master/data/transactions/logic/README.md and the algorand network for the same purpose?
i.e. you can do lots of stuff in a "bytecode based stack language that executes inside Algorand transactions" but one simple thing must be just another coin logic with a fixed set of total supply, rules for adding new coin, etc.
i.e. this GUI
Found answer at: https://developer.algorand.org/tutorials/create-dogcoin/
via https://github.com/algorand/go-algorand/issues/2142#issuecomment-835243098
I understand if this question needs to be closed.
Yes, you can use TEAL to create a new token on the Algorand network. Tokens are just a form of smart contracts, and TEAL allows developers to build smart contracts.
However, Algorand has an ASA network (Algorand Standard Asset) which means you can create a token without writing a new smart contract. You can read more about ASAs here.
If you want to do this in TEAL and create a more bespoke token, it is recommended to use PyTEAL. PyTEAL is a Python implementation of TEAL which is much easier to use.
This is an example of an asset in PyTEAL:
from pyteal import *
def approval_program():
on_creation = Seq(
[
Assert(Txn.application_args.length() == Int(1)),
App.globalPut(Bytes("total supply"), Btoi(Txn.application_args[0])),
App.globalPut(Bytes("reserve"), Btoi(Txn.application_args[0])),
App.localPut(Int(0), Bytes("admin"), Int(1)),
App.localPut(Int(0), Bytes("balance"), Int(0)),
Return(Int(1)),
]
)
is_admin = App.localGet(Int(0), Bytes("admin"))
on_closeout = Seq(
[
App.globalPut(
Bytes("reserve"),
App.globalGet(Bytes("reserve"))
+ App.localGet(Int(0), Bytes("balance")),
),
Return(Int(1)),
]
)
register = Seq([App.localPut(Int(0), Bytes("balance"), Int(0)), Return(Int(1))])
# configure the admin status of the account Txn.accounts[1]
# sender must be admin
new_admin_status = Btoi(Txn.application_args[1])
set_admin = Seq(
[
Assert(And(is_admin, Txn.application_args.length() == Int(2))),
App.localPut(Int(1), Bytes("admin"), new_admin_status),
Return(Int(1)),
]
)
# NOTE: The above set_admin code is carefully constructed. If instead we used the following code:
# Seq([
# Assert(Txn.application_args.length() == Int(2)),
# App.localPut(Int(1), Bytes("admin"), new_admin_status),
# Return(is_admin)
# ])
# It would be vulnerable to the following attack: a sender passes in their own address as
# Txn.accounts[1], so then the line App.localPut(Int(1), Bytes("admin"), new_admin_status)
# changes the sender's admin status, meaning the final Return(is_admin) can return anything the
# sender wants. This allows anyone to become an admin!
# move assets from the reserve to Txn.accounts[1]
# sender must be admin
mint_amount = Btoi(Txn.application_args[1])
mint = Seq(
[
Assert(Txn.application_args.length() == Int(2)),
Assert(mint_amount <= App.globalGet(Bytes("reserve"))),
App.globalPut(
Bytes("reserve"), App.globalGet(Bytes("reserve")) - mint_amount
),
App.localPut(
Int(1),
Bytes("balance"),
App.localGet(Int(1), Bytes("balance")) + mint_amount,
),
Return(is_admin),
]
)
# transfer assets from the sender to Txn.accounts[1]
transfer_amount = Btoi(Txn.application_args[1])
transfer = Seq(
[
Assert(Txn.application_args.length() == Int(2)),
Assert(transfer_amount <= App.localGet(Int(0), Bytes("balance"))),
App.localPut(
Int(0),
Bytes("balance"),
App.localGet(Int(0), Bytes("balance")) - transfer_amount,
),
App.localPut(
Int(1),
Bytes("balance"),
App.localGet(Int(1), Bytes("balance")) + transfer_amount,
),
Return(Int(1)),
]
)
program = Cond(
[Txn.application_id() == Int(0), on_creation],
[Txn.on_completion() == OnComplete.DeleteApplication, Return(is_admin)],
[Txn.on_completion() == OnComplete.UpdateApplication, Return(is_admin)],
[Txn.on_completion() == OnComplete.CloseOut, on_closeout],
[Txn.on_completion() == OnComplete.OptIn, register],
[Txn.application_args[0] == Bytes("set admin"), set_admin],
[Txn.application_args[0] == Bytes("mint"), mint],
[Txn.application_args[0] == Bytes("transfer"), transfer],
)
return program
def clear_state_program():
program = Seq(
[
App.globalPut(
Bytes("reserve"),
App.globalGet(Bytes("reserve"))
+ App.localGet(Int(0), Bytes("balance")),
),
Return(Int(1)),
]
)
return program
if __name__ == "__main__":
with open("asset_approval.teal", "w") as f:
compiled = compileTeal(approval_program(), mode=Mode.Application, version=2)
f.write(compiled)
with open("asset_clear_state.teal", "w") as f:
compiled = compileTeal(clear_state_program(), mode=Mode.Application, version=2)
f.write(compiled)

SPARQL, dbpedia : Retrieve values of resource linked as property, type person

I need to retrieve the name of a person's mother, and I have no idea how to do so.
This is the query I'm currently working with:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX : <http://dbpedia.org/resource/>
SELECT DISTINCT
?resource ?depiction ?label ?parent ?bd
WHERE {
?resource a dbo:Royalty ; foaf:depiction ?depiction ; rdfs:label ?label;
dbo:parent ?parent; dbo:birthDate ?bd;
dbo:birthPlace ?bp . ?bp dbo:isPartOf :England .
FILTER(
LANGMATCHES(LANG(?label), 'en') && ?bd < '1900-01-01'^^xsd:date)
}
ORDER BY DESC(?bd)
Some of it was given, some of it was added by me.
As you can see I want to retrieve all royals (with Label and depiction) who were born in England before 1900. But I also want to retrieve the name of a person's mother.
?parent contains links to the person's parents and I can't seem to figure out how to:
retrieve only the mother and
How to get her name/label, since this only returns the url.
For example:
For: http://dbpedia.org/page/Charlotte_of_Mecklenburg-Strelitz
?parents are:
http://dbpedia.org/page/Princess_Elisabeth_Albertine_of_Saxe-Hildburghausen
and
http://dbpedia.org/page/Duke_Charles_Louis_Frederick_of_Mecklenburg
But I would need :
Princess Elisabeth Albertine of Saxe-Hildburghausen
As commented by #AKSW, a possibly-incomplete query (formatted here for improved clarity) --
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX yago: <http://dbpedia.org/class/yago/>
PREFIX : <http://dbpedia.org/resource/>
SELECT DISTINCT
?resource
?label
?bd
?depiction
?parent
?parentLabel
WHERE
{ ?resource a dbo:Royalty ;
foaf:depiction ?depiction ;
rdfs:label ?label ;
dbo:parent ?parent ;
dbo:birthDate ?bd ;
dbo:birthPlace/dbo:location?/dbo:isPartOf :England .
?parent rdfs:label ?parentLabel .
FILTER ( LANGMATCHES ( LANG ( ?parentLabel ), 'en' )
&& LANGMATCHES ( LANG ( ?label ), 'en' )
&& ?bd < '1900-01-01'^^xsd:date
)
{ ?parent foaf:gender "female"#en }
UNION
{ ?parent a yago:Female109619168 }
}
ORDER BY DESC(?bd)

SWRL rules in protege 3.4.8

I created an ontology that contains the class Blood_Sugar
this class contains 4 subclasses: Normal_BS, High_BS, Low_BS and Dangerous_BS.
I would like to execute a SWRL rule on Protege 3.4.8 which permit to classify individuals of the supere class Blood_Sugar in subclasses according to their values.
Blood_Pressure(?x) ∧ hasLevelvalue(?x, ?y) ∧ swrlb:greaterThan(?y, 126) ∧ swrlb:lessThan(?y, 500) → High_BS(?x)
knowing that hasLevelValue is a DataType proprety, its domain is Blood_Sugar class and its range is INT
On the Blood_Sugar class and thier subclasses class, I created the restriction (hasLevelvalue only int)
I created som individuals that have diffrent values but they are not classified in the sub classes (High_BS, Low_BS...) the swrl rule does not give an erreur but it does not give a result :( I dont know what end wher is the problem?!!!!!
Possible problems
Your question is a bit unclear, and I'm not sure whether there are just typographical errors, or if there are genuine modeling errors. You said that you were looking at the class Blood_Sugar, and four subclasses, but then the rule that you showed starts with a Blood_Pressure atom (pressure, not sugar), and that could be the problem right there:
Blood_Pressure(?x) ∧ hasLevelvalue(?x, ?y) ∧ swrlb:greaterThan(?y, 126) ∧ swrlb:lessThan(?y, 500) → High_BS(?x)
If that's just a typo in the question, though, you could be having problems with the datatypes. Rather than using xsd:int, you should probably be using xsd:integer (so that you don't have to worry about issues with overflow, etc.) Not to mention, if you use one in your data, but declare the range differently, you could run into inconsistencies there.
Using Rules
To get you going, I've reconstructed a very minimal part of your ontology in Protégé 4.x, and using the Pellet reasoner, I've demonstrated the results that you're looking for:
I've included the ontology in N3 format toward the end of this answer.
Using Restrictions
Now, even though you can do this using SWRL rules, you can also do this using simple OWL restriction classes, and that might be a better option, because it might work with more reasoners. If nothing else, it's one less dependency, so it might be a more attractive solution. The trick is to either define Blood_HS as equivalent to the intersection of Blood_Sugar and things with a level in the desired range, or you could use an general class axiom. In both of these cases, you can get the desired result using the Pellet reasoner, and you don't need any SWRL rule.
Using an Equivalent Class Axiom
You can simply say that (using the class names that I've been using in mine ontology):
HighBloodSugar ≡ BloodSugar and (hasLevelValue some integer[>120,<600])
In Protégé that looks a little bit different, but it's pretty close:
Using a Subclass Axiom
Now, if you you don't want to make that an equivalent class axiom, you can use a general axiom like the following.
BloodSugar and (hasLevelValue some integer[>120,<600]) &sqsubseteq; HighBloodSugar
This only looks a little bit different in Protégé. This is the closest to the SWRL version, since anything that is a blood sugar and has a level in the specified range will be classified as a high blood sugar, but it's still possible that there are other high blood sugars, too. (You don't get this with the equivalent class axiom.)
Ontology with Rules
#prefix : <http://stackoverflow.com/q/21243879/1281433/blood-pressure.owl#> .
#prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
#prefix swrl: <http://www.w3.org/2003/11/swrl#> .
#prefix owl: <http://www.w3.org/2002/07/owl#> .
#prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
#prefix swrlb: <http://www.w3.org/2003/11/swrlb#> .
#prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
#prefix blood-pressure: <http://stackoverflow.com/q/21243879/1281433/blood-pressure.owl#> .
<http://stackoverflow.com/q/21243879/1281433/blood-pressure.owl>
a owl:Ontology .
blood-pressure:HighBloodSugar
a owl:Class .
blood-pressure:bs1 a owl:NamedIndividual , blood-pressure:BloodSugar ;
blood-pressure:hasLevelValue 200 .
<urn:swrl#bp> a swrl:Variable .
<urn:swrl#bs> a swrl:Variable .
blood-pressure:BloodSugar
a owl:Class .
blood-pressure:hasLevelValue
a owl:DatatypeProperty ;
rdfs:domain blood-pressure:BloodSugar ;
rdfs:range xsd:integer .
[ a swrl:Imp ;
swrl:body [ a swrl:AtomList ;
rdf:first [ a swrl:ClassAtom ;
swrl:argument1 <urn:swrl#bs> ;
swrl:classPredicate blood-pressure:BloodSugar
] ;
rdf:rest [ a swrl:AtomList ;
rdf:first [ a swrl:DatavaluedPropertyAtom ;
swrl:argument1 <urn:swrl#bp> ;
swrl:argument2 <urn:swrl#level> ;
swrl:propertyPredicate blood-pressure:hasLevelValue
] ;
rdf:rest [ a swrl:AtomList ;
rdf:first [ a swrl:BuiltinAtom ;
swrl:arguments [ a rdf:List ;
rdf:first <urn:swrl#level> ;
rdf:rest [ a rdf:List ;
rdf:first 126 ;
rdf:rest ()
]
] ;
swrl:builtin swrlb:greaterThan
] ;
rdf:rest [ a swrl:AtomList ;
rdf:first [ a swrl:BuiltinAtom ;
swrl:arguments [ a rdf:List ;
rdf:first <urn:swrl#level> ;
rdf:rest [ a rdf:List ;
rdf:first 500 ;
rdf:rest ()
]
] ;
swrl:builtin swrlb:lessThan
] ;
rdf:rest ()
]
]
]
] ;
swrl:head [ a swrl:AtomList ;
rdf:first [ a swrl:ClassAtom ;
swrl:argument1 <urn:swrl#bs> ;
swrl:classPredicate blood-pressure:HighBloodSugar
] ;
rdf:rest ()
]
] .
<urn:swrl#level> a swrl:Variable .

Optimization of SPARQL query. [ Estimated execution time exceeds the limit of 1500 (sec) ]

I am trying to run this query on http://dbpedia.org/sparql but I get an error that my query is too expensive. When I run the query trough http://dbpedia.org/snorql/ I get:
The estimated execution time 25012730 (sec) exceeds the limit of 1500 (sec) ...
When running the query through my python script using SPARQLWrapper I simply get an HTTP 500.
I figure I need to do something to optimize my SPARQL query. I need the data for iterating over educational institutions and importing it in to a local database, maybe I am using SPARQL wrong and should do this in a fundamentally different way.
Hope someone can help me!
The query
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX : <http://dbpedia.org/resource/>
PREFIX dbpedia2: <http://dbpedia.org/property/>
PREFIX dbpedia: <http://dbpedia.org/>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT DISTINCT ?uri
?name
?homepage
?student_count
?native_name
?city
?country
?type
?lat ?long
?image
WHERE {
?uri rdf:type dbpedia-owl:EducationalInstitution .
?uri foaf:name ?name .
OPTIONAL { ?uri foaf:homepage ?homepage } .
OPTIONAL { ?uri dbpedia-owl:numberOfStudents ?student_count } .
OPTIONAL { ?uri dbpprop:nativeName ?native_name } .
OPTIONAL { ?uri dbpprop:city ?city } .
OPTIONAL { ?uri dbpprop:country ?country } .
OPTIONAL { ?uri dbpprop:type ?type } .
OPTIONAL { ?uri geo:lat ?lat . ?uri geo:long ?long } .
OPTIONAL { ?uri foaf:depiction ?image } .
}
ORDER BY ?uri
LIMIT 20 OFFSET 10
Forget it. You won't be able to get that query back from dbpedia with just one SPARQL. Those optionals are very expensive.
To work it around you need to first run something like:
SELECT DISTINCT ?uri WHERE {
?uri rdf:type dbpedia-owl:EducationalInstitution .
?uri foaf:name ?name .
} ORDER BY ?uri
LIMIT 20 OFFSET 10
Then iterate over the resultset of this query to form single queries for each dbpedia-owl:EducationalInstitution such as ... (notice the filter at the end of the query):
SELECT DISTINCT ?uri
?name
?homepage
?student_count
?native_name
?city
?country
?type
?lat ?long
?image
WHERE {
?uri rdf:type dbpedia-owl:EducationalInstitution .
?uri foaf:name ?name .
OPTIONAL { ?uri foaf:homepage ?homepage } .
OPTIONAL { ?uri dbpedia-owl:numberOfStudents ?student_count } .
OPTIONAL { ?uri dbpprop:nativeName ?native_name } .
OPTIONAL { ?uri dbpprop:city ?city } .
OPTIONAL { ?uri dbpprop:country ?country } .
OPTIONAL { ?uri dbpprop:type ?type } .
OPTIONAL { ?uri geo:lat ?lat . ?uri geo:long ?long } .
OPTIONAL { ?uri foaf:depiction ?image } .
FILTER (?uri = <http://dbpedia.org/resource/%C3%89cole_%C3%A9l%C3%A9mentaire_Marie-Curie>)
}
Where <http://dbpedia.org/resource/%C3%89cole_%C3%A9l%C3%A9mentaire_Marie-Curie> has been obtained from the first query.
... and yes it will be slow and you might not be able to run this for an online application. Advice: try to work out some sort of caching mechanism to sit between your app and the dbpedia SPARQL endpoint.
Don't try and get the entire dataset at once! Add a LIMIT and a OFFSET clause and use those to page through the data.
With LIMIT 50 added I get back a result for your query almost instantly, I managed to get the limit up much higher than that and still get a response so play with it. Once you've found a page size that works for you just repeat the query with an OFFSET as well until you get no more results e.g.
SELECT * WHERE { ... } LIMIT 100
SELECT * WHERE { ... } LIMIT 100 OFFSET 100
...
If you know the exact URI (e.g. from a previous query), then putting the URI directly in the where clause is faster (at least in my experience) than putting the URI in a FILTER.
e.g., prefer:
WHERE { <http:/...> ... }
over
WHERE { ?uri .... FILTER (?uri...)
Also I've found UNION's actually perform faster than filters designed to match multiple resources.
Just because we're doing SPARQL now doesn't mean we can forget the nightmares of SQL tuning, welcome to the wonderful world of SPARQL tuning! :)

Resources